Code

last fixes from patch 1219308
[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) 2006 Johan Engelen
17  * Copyright (C) 1997-98 Peter Kirchgessner
18  * Copyright (C) 1995 Spencer Kimball and Peter Mattis
19  * George White <aa056@chebucto.ns.ca>
20  * Austin Donnelly <austin@gimp.org>
21  *
22  * Licensed under GNU GPL
23  */
25 /* Plain Print */
27 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #include <signal.h>
32 #include <errno.h>
34 #include <libnr/n-art-bpath.h>
36 #include <glib/gmem.h>
37 #include <gtk/gtkstock.h>
38 #include <gtk/gtkvbox.h>
39 #include <gtk/gtkframe.h>
40 #include <gtk/gtkradiobutton.h>
41 #include <gtk/gtkcombo.h>
42 #include <gtk/gtklabel.h>
43 #include <gtk/gtkentry.h>
44 #include <gtk/gtktooltips.h>
46 #include <glibmm/i18n.h>
47 #include "display/nr-arena-item.h"
48 #include "display/canvas-bpath.h"
49 #include "sp-item.h"
50 #include "style.h"
51 #include "sp-linear-gradient.h"
52 #include "sp-radial-gradient.h"
54 #include "libnrtype/font-instance.h"
55 #include "libnrtype/font-style-to-pos.h"
57 #include <unit-constants.h>
59 #include "ps.h"
60 #include "extension/system.h"
61 #include "extension/print.h"
63 #include "io/sys.h"
65 #include <ft2build.h>
66 #include FT_FREETYPE_H
67 #include FT_XFREE86_H
68 #include <pango/pangoft2.h>
69 #include <string>
70 #include <iostream>
71 #include <fstream>
72 using namespace std;
74 namespace Inkscape {
75 namespace Extension {
76 namespace Internal {
78 PrintPS::PrintPS() :
79     _stream(NULL),
80     _dpi(72),
81     _bitmap(false)
82 {
83     //map font types
84     _fontTypesMap["Type 1"] = FONT_TYPE1;
85     _fontTypesMap["TrueType"] = FONT_TRUETYPE;
86     //TODO: support other font types (cf. embed_font())
87 }
89 PrintPS::~PrintPS(void)
90 {
91     /* fixme: should really use pclose for popen'd streams */
92     if (_stream) fclose(_stream);
93     if(_begin_stream) fclose(_begin_stream);
94     if(_fonts) g_tree_destroy(_fonts);
96     /* restore default signal handling for SIGPIPE */
97 #if !defined(_WIN32) && !defined(__WIN32__)
98     (void) signal(SIGPIPE, SIG_DFL);
99 #endif
101     return;
104 unsigned int
105 PrintPS::setup(Inkscape::Extension::Print * mod)
107     static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
109 #ifdef TED
110     Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
111 #endif
113     unsigned int ret = FALSE;
115     /* Create dialog */
116     GtkTooltips *tt = gtk_tooltips_new();
117     g_object_ref((GObject *) tt);
118     gtk_object_sink((GtkObject *) tt);
120     GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
121 //            SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
122             NULL,
123             (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
124             GTK_STOCK_CANCEL,
125             GTK_RESPONSE_CANCEL,
126             GTK_STOCK_PRINT,
127             GTK_RESPONSE_OK,
128             NULL);
130     gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
132     GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
133     gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
134     /* Print properties frame */
135     GtkWidget *f = gtk_frame_new(_("Print properties"));
136     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
137     GtkWidget *vb = gtk_vbox_new(FALSE, 4);
138     gtk_container_add(GTK_CONTAINER(f), vb);
139     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
140     /* Print type */
141     bool const p2bm = mod->get_param_bool("bitmap");
142     GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PostScript operators"));
143     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
144                          _("Use PostScript vector operators. The resulting image is usually smaller "
145                            "in file size and can be arbitrarily scaled, but alpha transparency "
146                            "and patterns will be lost."), NULL);
147     if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
148     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
149     rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
150     gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
151                          _("Print everything as bitmap. The resulting image is usually larger "
152                            "in file size and cannot be arbitrarily scaled without quality loss, "
153                            "but all objects will be rendered exactly as displayed."), NULL);
154     if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
155     gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
156     /* Resolution */
157     GtkWidget *hb = gtk_hbox_new(FALSE, 4);
158     gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
159     GtkWidget *combo = gtk_combo_new();
160     gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
161     gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
162     gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
163     gtk_widget_set_size_request(combo, 64, -1);
164     gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
165                          _("Preferred resolution (dots per inch) of bitmap"), NULL);
166     /* Setup strings */
167     GList *sl = NULL;
168     for (unsigned i = 0; pdr[i] != NULL; i++) {
169         sl = g_list_prepend(sl, (gpointer) pdr[i]);
170     }
171     sl = g_list_reverse(sl);
172     gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
173     g_list_free(sl);
174     if (1) {
175         gchar const *val = mod->get_param_string("resolution");
176         gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
177     }
178     gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
179     GtkWidget *l = gtk_label_new(_("Resolution:"));
180     gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
182     /* Print destination frame */
183     f = gtk_frame_new(_("Print destination"));
184     gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
185     vb = gtk_vbox_new(FALSE, 4);
186     gtk_container_add(GTK_CONTAINER(f), vb);
187     gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
189     l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
190                         "leave empty to use the system default printer.\n"
191                         "Use '> filename' to print to file.\n"
192                         "Use '| prog arg...' to pipe to a program."));
193     gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
195     GtkWidget *e = gtk_entry_new();
196     if (1) {
197         gchar const *val = mod->get_param_string("destination");
198         gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
199                                            ? val
200                                            : "" ));
201     }
202     gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
204     // pressing enter in the destination field is the same as clicking Print:
205     gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
207     gtk_widget_show_all(vbox);
209     int const response = gtk_dialog_run(GTK_DIALOG(dlg));
211     g_object_unref((GObject *) tt);
213     if (response == GTK_RESPONSE_OK) {
214         gchar const *fn;
215         char const *sstr;
217         _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
218         sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
219         _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
220         /* Arrgh, have to do something */
221         fn = gtk_entry_get_text(GTK_ENTRY(e));
222         /* skip leading whitespace, bug #1068483 */
223         while (fn && *fn==' ') { fn++; }
224         /* g_print("Printing to %s\n", fn); */
226         mod->set_param_bool("bitmap", _bitmap);
227         mod->set_param_string("resolution", (gchar *)sstr);
228         mod->set_param_string("destination", (gchar *)fn);
229         ret = TRUE;
230     }
232     gtk_widget_destroy(dlg);
234     return ret;
237 unsigned int
238 PrintPS::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
240     gboolean epsexport = false;
243     _latin1_encoded_fonts.clear();
244     _newlatin1font_proc_defined = false;
246     FILE *osf = NULL;
247     FILE *osp = NULL;
248     FILE *osf_tmp = NULL;
250     gsize bytesRead = 0;
251     gsize bytesWritten = 0;
252     GError *error = NULL;
253     //check whether fonts have to be embedded in the (EPS only) output
254     bool font_embedded = mod->fontEmbedded();
255     gchar const *utf8_fn = mod->get_param_string("destination");
256     gchar *local_fn = g_filename_from_utf8( utf8_fn,
257                                             -1,  &bytesRead,  &bytesWritten, &error);
258     gchar const *fn = local_fn;
260     /* TODO: Replace the below fprintf's with something that does the right thing whether in
261      * gui or batch mode (e.g. --print=blah).  Consider throwing an exception: currently one of
262      * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
263      * return code.
264      */
265     if (fn != NULL) {
266         if (*fn == '|') {
267             fn += 1;
268             while (isspace(*fn)) fn += 1;
269 #ifndef WIN32
270             osp = popen(fn, "w");
271 #else
272             osp = _popen(fn, "w");
273 #endif
274             if (!osp) {
275                 fprintf(stderr, "inkscape: popen(%s): %s\n",
276                         fn, strerror(errno));
277                 return 0;
278             }
279             _stream = _begin_stream = osp;
280         } else if (*fn == '>') {
281             fn += 1;
282             epsexport = g_str_has_suffix(fn,".eps");
283             while (isspace(*fn)) fn += 1;
284             Inkscape::IO::dump_fopen_call(fn, "K");
285             osf = Inkscape::IO::fopen_utf8name(fn, "w+");
286             if (!osf) {
287                 fprintf(stderr, "inkscape: fopen(%s): %s\n",
288                         fn, strerror(errno));
289                 return 0;
290             }
291             _begin_stream = osf;
292              /* if font embedding is requested for EPS export...
293              * TODO:could be extended to PS export if texttopath=FALSE possible
294              */
295              if(font_embedded && epsexport)
296              {
297                /**
298                * Create temporary file where to print the main "script" part of the EPS document.
299                * Use an extra stream (_begin_stream) to print the prolog and document setup sections.
300                * Thus, once all the (main) script part printed, all the fonts used are known and can be embedded
301                * just after the prolog section, in a Begin(End)Setup section (document setup),
302                * one Begin(End)Resource (DSC comment) section for each font embedded.
303                * Then, append the final script part from the temporary file (_stream in this case).
304                * Reference: Adobe Technical note 5001, "PostScript Document Struturing Conventions Specifications"
305                * page 19
306                */
307                osf_tmp = tmpfile();
308                if(!osf_tmp)
309                {
310                  g_warning("Could not create a temporary file for font embedding. Font embedding canceled.");
311                  mod->set_param_bool("fontEmbedded", false);
312                  font_embedded = false;
313                  _stream = osf;
314                } else _stream = osf_tmp;
315              } else _stream = osf;
316         } else {
317             /* put cwd stuff in here */
318             gchar *qn = ( *fn
319                           ? g_strdup_printf("lpr -P %s", fn)  /* FIXME: quote fn */
320                           : g_strdup("lpr") );
321 #ifndef WIN32
322             osp = popen(qn, "w");
323 #else
324             osp = _popen(qn, "w");
325 #endif
326             if (!osp) {
327                 fprintf(stderr, "inkscape: popen(%s): %s\n",
328                         qn, strerror(errno));
329                 return 0;
330             }
331             g_free(qn);
332             _stream = _begin_stream = osp;
333         }
334     }
336     g_free(local_fn);
338     if (_stream) {
339         /* fixme: this is kinda icky */
340 #if !defined(_WIN32) && !defined(__WIN32__)
341         (void) signal(SIGPIPE, SIG_IGN);
342 #endif
343     }
345     int const res = fprintf(_begin_stream, ( epsexport
346                                        ? "%%!PS-Adobe-3.0 EPSF-3.0\n"
347                                        : "%%!PS-Adobe-3.0\n" ));
348     /* flush this to test output stream as early as possible */
349     if (fflush(_begin_stream)) {
350         /*g_print("caught error in sp_module_print_plain_begin\n");*/
351         if (ferror(_begin_stream)) {
352             g_print("Error %d on output stream: %s\n", errno,
353                     g_strerror(errno));
354         }
355         g_print("Printing failed\n");
356         /* fixme: should use pclose() for pipes */
357         fclose(_begin_stream);
358         _begin_stream = NULL;
359         fflush(stdout);
360         return 0;
361     }
362     //TODO: do this same test on _stream
364     // width and height in pt
365     _width = sp_document_width(doc) * PT_PER_PX;
366     _height = sp_document_height(doc) * PT_PER_PX;
368     NRRect d;
369     bool   pageBoundingBox;
370     bool   pageLandscape;
371     pageBoundingBox = mod->get_param_bool("pageBoundingBox");
372     // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
373     if (pageBoundingBox) {
374         d.x0 = d.y0 = 0;
375         d.x1 = ceil(_width);
376         d.y1 = ceil(_height);
377     } else {
378         SPItem* doc_item = SP_ITEM(sp_document_root(doc));
379         sp_item_invoke_bbox(doc_item, &d, sp_item_i2r_affine(doc_item), TRUE);
380         // convert from px to pt
381         d.x0 *= PT_PER_PX;
382         d.x1 *= PT_PER_PX;
383         d.y0 *= PT_PER_PX;
384         d.y1 *= PT_PER_PX;
385     }
387     Inkscape::SVGOStringStream os;
388     if (res >= 0) {
390         os << "%%Creator: " << PACKAGE_STRING << "\n";
391         // This will become problematic if inkscape gains the
392         // ability to handle multi paged documents. If this is
393         // the case the %%Orientation: comments should be
394         // renamed to %%PageOrientation: and moved to the
395         // respective pages.
396         os << "%%Pages: 1\n";
398         // 2004 Dec 10, BFC:
399         // The point of the following code is (1) to do the thing that's expected by users
400         // who have done File>New>A4_landscape or ...letter_landscape (i.e., rotate
401         // the output), while (2) not messing up users who simply want their output wider
402         // than it is tall (e.g., small figures for inclusion in LaTeX).
403         // The original patch by WQ only had the w>h condition.
404         {
405              double w = (d.x1 - d.x0); // width and height of bounding box, in pt
406              double h = (d.y1 - d.y0);
407              pageLandscape = (
408                  (w > 0. && h > 0.) // empty documents fail this sanity check, have w<0, h<0
409                  && (w > h)   // implies, but does not prove, the user wanted landscape
410                  && (w > 600) // approximate maximum printable width of an A4
411                  && (!epsexport) // eps should always be portrait
412              )
413              ? true : false;
414         }
416         if (pageLandscape) {
417             os << "%%Orientation: Landscape\n";
418             os << "%%BoundingBox: " << (int) (_height - d.y1) << " "
419                << (int) d.x0 << " "
420                << (int) ceil(_height - d.y0) << " "
421                << (int) ceil(d.x1) << "\n";
422             // According to Mike Sweet (the author of CUPS)
423             // HiResBoundingBox is only appropriate
424             // for EPS files. This means that we should
425             // distinguish if we export to ps or eps here.
426             // FIXME: I couldn't find HiResBoundingBox in the PS
427             // reference manual, so I guess we should skip
428             // it.
429             os << "%%HiResBoundingBox: " << (_height - d.y1) << " "
430                << d.x0 << " "
431                << (_height - d.y0) << " "
432                << d.x1 << "\n";
433             os << "%%DocumentMedia: plain "
434                << (int) ceil(_height) << " "
435                << (int) ceil(_width) << " "
436                << "0 () ()\n";
437         } else {
438             os << "%%Orientation: Portrait\n";
439             os << "%%BoundingBox: " << (int) d.x0 << " "
440                << (int) d.y0 << " "
441                << (int) ceil(d.x1) << " "
442                << (int) ceil(d.y1) << "\n";
443             os << "%%HiResBoundingBox: " << d.x0 << " "
444                << d.y0 << " "
445                << d.x1 << " "
446                << d.y1 << "\n";
447             os << "%%DocumentMedia: plain "
448                << (int) ceil(_width) << " "
449                << (int) ceil(_height) << " "
450                << "0 () ()\n";
451         }
453         os << "%%EndComments\n";
454          /* If font embedding requested, begin document setup section where to include font resources */
455          if(font_embedded) os << "%%BeginSetup\n";/* Resume it later with Begin(End)Resource sections for font embedding. So, for now, we are done with the prolog/setup part. */
456          gint ret = fprintf(_begin_stream, "%s", os.str().c_str());
457          if(ret < 0) return ret;
459          /* Main Script part (after document setup) begins */
460          /* Empty os from all previous printing */
461          std::string clrstr = "";
462          os.str(clrstr);
463         // This will become problematic if we print multi paged documents:
464         os << "%%Page: 1 1\n";
466         if (pageLandscape) {
467             os << "90 rotate\n";
468             if (_bitmap) {
469                 os << "0 " << (int) -ceil(_height) << " translate\n";
470             }
471         } else {
472             if (!_bitmap) {
473                 os << "0 " << (int) ceil(_height) << " translate\n";
474             }
475         }
477         if (!_bitmap) {
478             os << PT_PER_PX << " " << -PT_PER_PX << " scale\n";
479             // from now on we can output px, but they will be treated as pt
480         }
482         /* As a new PS document is created, _fontlist has to be reinitialized (unref fonts from possible former PS docs) */
483         _fonts = g_tree_new_full((GCompareDataFunc)strcmp, NULL, (GDestroyNotify)g_free, (GDestroyNotify)g_free);
484     }
486     os << "0 0 0 setrgbcolor\n"
487        << "[] 0 setdash\n"
488        << "1 setlinewidth\n"
489        << "0 setlinejoin\n"
490        << "0 setlinecap\n";
492     /* FIXME: This function is declared to return unsigned, whereas fprintf returns a signed int *
493      * that can be zero if the first fprintf failed (os is empty) or "negative" (i.e. very positive
494      * in unsigned int interpretation) if the first fprintf failed but this one succeeds, or
495      * positive if both succeed. */
496     return fprintf(_stream, "%s", os.str().c_str());
499 unsigned int
500 PrintPS::finish(Inkscape::Extension::Print *mod)
502     if (!_stream) return 0;
504     if (_bitmap) {
505         double const dots_per_pt = _dpi / PT_PER_IN;
507         double const x0 = 0.0;
508         double const y0 = 0.0;
509         double const x1 = x0 + _width;
510         double const y1 = y0 + _height;
512         /* Bitmap width/height in bitmap dots. */
513         int const width = (int) (_width * dots_per_pt + 0.5);
514         int const height = (int) (_height * dots_per_pt + 0.5);
516         NRMatrix affine;
517         affine.c[0] = width / ((x1 - x0) * PX_PER_PT);
518         affine.c[1] = 0.0;
519         affine.c[2] = 0.0;
520         affine.c[3] = height / ((y1 - y0) * PX_PER_PT);
521         affine.c[4] = -affine.c[0] * x0;
522         affine.c[5] = -affine.c[3] * y0;
524         nr_arena_item_set_transform(mod->root, &affine);
526         guchar *const px = g_new(guchar, 4 * width * 64);
528         for (int y = 0; y < height; y += 64) {
529             /* Set area of interest. */
530             NRRectL bbox;
531             bbox.x0 = 0;
532             bbox.y0 = y;
533             bbox.x1 = width;
534             bbox.y1 = MIN(height, y + 64);
536             /* Update to renderable state. */
537             NRGC gc(NULL);
538             nr_matrix_set_identity(&gc.transform);
539             nr_arena_item_invoke_update(mod->root, &bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
540             /* Render */
541             /* This should take guchar* instead of unsigned char*) */
542             NRPixBlock pb;
543             nr_pixblock_setup_extern(&pb, NR_PIXBLOCK_MODE_R8G8B8A8N,
544                                      bbox.x0, bbox.y0, bbox.x1, bbox.y1,
545                                      (guchar*)px, 4 * width, FALSE, FALSE);
546             memset(px, 0xff, 4 * width * 64);
547             nr_arena_item_invoke_render(mod->root, &bbox, &pb, 0);
548             /* Blitter goes here */
549             NRMatrix imgt;
550             imgt.c[0] = (bbox.x1 - bbox.x0) / dots_per_pt;
551             imgt.c[1] = 0.0;
552             imgt.c[2] = 0.0;
553             imgt.c[3] = (bbox.y1 - bbox.y0) / dots_per_pt;
554             imgt.c[4] = 0.0;
555             imgt.c[5] = _height - y / dots_per_pt - (bbox.y1 - bbox.y0) / dots_per_pt;
557             print_image(_stream, px, bbox.x1 - bbox.x0, bbox.y1 - bbox.y0, 4 * width, &imgt);
558         }
560         g_free(px);
561     }
563     fprintf(_stream, "showpage\n");
564     int const res = fprintf(_stream, "%%%%EOF\n");
566     /* Flush stream to be sure. */
567     (void) fflush(_stream);
569     char c;
570     /* If font embedding... */
571     if(mod->get_param_bool("fontEmbedded"))
572     {
573         /* Close the document setup section that had been started (because all the needed resources are supposed to be included now) */
574        /*res = */fprintf(_begin_stream, "%s", "%%EndSetup\n");
575        /* If font embedding requested, the following PS script part was printed to a different file from the prolog/setup, so script part (current _stream) needs to be copied to prolog/setup file to get the complete (E)PS document */
576        if(fseek(_stream, 0, SEEK_SET) == 0)
577        {
578            while((c = fgetc(_stream))!=EOF) fputc(c, _begin_stream);
579        }
580        fclose(_begin_stream);
581     }
583     /* fixme: should really use pclose for popen'd streams */
584     fclose(_stream);
585     _stream = 0;
586     _latin1_encoded_fonts.clear();
588     g_tree_destroy(_fonts);
590     return res;
593 unsigned int
594 PrintPS::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
596     if (!_stream) return 0;  // XXX: fixme, returning -1 as unsigned.
597     if (_bitmap) return 0;
599     Inkscape::SVGOStringStream os;
600     os << "gsave [" << transform->c[0] << " "
601        << transform->c[1] << " "
602        << transform->c[2] << " "
603        << transform->c[3] << " "
604        << transform->c[4] << " "
605        << transform->c[5] << "] concat\n";
607     return fprintf(_stream, "%s", os.str().c_str());
610 unsigned int
611 PrintPS::release(Inkscape::Extension::Print *mod)
613     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
614     if (_bitmap) return 0;
616     return fprintf(_stream, "grestore\n");
619 unsigned int
620 PrintPS::comment(Inkscape::Extension::Print *mod, char const *comment)
622     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
623     if (_bitmap) return 0;
625     return fprintf(_stream, "%%! %s\n",comment);
628 void
629 PrintPS::print_fill_style(SVGOStringStream &os, SPStyle const *const style, NRRect const *pbox)
631     g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
632                       || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
633                            && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
635     if (style->fill.type == SP_PAINT_TYPE_COLOR) {
636         float rgb[3];
637         sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
639         os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
641     } else {
642         g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
643                   && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
645         if (SP_IS_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style))) {
647             SPLinearGradient *lg = SP_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style));
648             NR::Point p1 (lg->x1.computed, lg->y1.computed);
649             NR::Point p2 (lg->x2.computed, lg->y2.computed);
650             if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
651                 // convert to userspace
652                 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
653                 p1 *= bbox2user;
654                 p2 *= bbox2user;
655             }
657             os << "<<\n/ShadingType 2\n/ColorSpace /DeviceRGB\n";
658             os << "/Coords [" << p1[NR::X] << " " << p1[NR::Y] << " " << p2[NR::X] << " " << p2[NR::Y] <<"]\n";
659             os << "/Extend [true true]\n";
660             os << "/Domain [0 1]\n";
661             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
663             sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
664             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
665                 float rgb[3];
666                 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
667                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
668                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
669                 sp_color_get_rgb_floatv(&lg->vector.stops[i+1].color, rgb);
670                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
671                 os << "/N 1\n>>\n";
672             }
673             os << "]\n/Domain [0 1]\n";
674             os << "/Bounds [ ";
675             for (unsigned i = 0; i + 2 < lg->vector.stops.size(); i++) {
676                 os << lg->vector.stops[i+1].offset <<" ";
677             }
678             os << "]\n";
679             os << "/Encode [ ";
680             for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
681                 os << "0 1 ";
682             }
683             os << "]\n";
684             os << ">>\n>>\n";
686         } else if (SP_IS_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style))) {
688             SPRadialGradient *rg = SP_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style));
689             NR::Point c(rg->cx.computed, rg->cy.computed);
690             NR::Point f(rg->fx.computed, rg->fy.computed);
691             double r = rg->r.computed;
692             if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
693                 // convert to userspace
694                 NR::Matrix const bbox2user(pbox->x1 - pbox->x0, 0,
695                                            0, pbox->y1 - pbox->y0,
696                                            pbox->x0, pbox->y0);
697                 c *= bbox2user;
698                 f *= bbox2user;
699                 r *= bbox2user.expansion();
700             }
702             os << "<<\n/ShadingType 3\n/ColorSpace /DeviceRGB\n";
703             os << "/Coords ["<< f[NR::X] <<" "<< f[NR::Y] <<" 0 "<< c[NR::X] <<" "<< c[NR::Y] <<" "<< r <<"]\n";
704             os << "/Extend [true true]\n";
705             os << "/Domain [0 1]\n";
706             os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
708             sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
709             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
710                 float rgb[3];
711                 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
712                 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
713                 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
714                 sp_color_get_rgb_floatv(&rg->vector.stops[i+1].color, rgb);
715                 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
716                 os << "/N 1\n>>\n";
717             }
718             os << "]\n/Domain [0 1]\n";
719             os << "/Bounds [ ";
720             for (unsigned i = 0; i + 2 < rg->vector.stops.size(); i++) {
721                 os << rg->vector.stops[i+1].offset << " ";
722             }
723             os << "]\n";
724             os << "/Encode [ ";
725             for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
726                 os << "0 1 ";
727             }
728             os << "]\n";
729             os << ">>\n>>\n";
730         }
731     }
734 void
735 PrintPS::print_stroke_style(SVGOStringStream &os, SPStyle const *style)
737     float rgb[3];
738     sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
740     os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
742     // There are rare cases in which for a solid line stroke_dasharray_set is true. To avoid
743     // invalid PS-lines such as "[0.0000000 0.0000000] 0.0000000 setdash", which should be "[] 0 setdash",
744     // we first check if all components of stroke_dash.dash are 0.
745     bool LineSolid = true;
746     if (style->stroke_dash.n_dash   &&
747         style->stroke_dash.dash       )
748     {
749         int i = 0;
750         while (LineSolid && (i < style->stroke_dash.n_dash)) {
751                 if (style->stroke_dash.dash[i] > 0.00000001)
752                     LineSolid = false;
753                 i++;
754         }
755         if (!LineSolid) {
756             os << "[";
757             for (i = 0; i < style->stroke_dash.n_dash; i++) {
758                 if (i > 0) {
759                     os << " ";
760                 }
761                 os << style->stroke_dash.dash[i];
762             }
763             os << "] " << style->stroke_dash.offset << " setdash\n";
764         } else {
765             os << "[] 0 setdash\n";
766         }
767     } else {
768         os << "[] 0 setdash\n";
769     }
771     os << style->stroke_width.computed << " setlinewidth\n";
772     os << style->stroke_linejoin.computed << " setlinejoin\n";
773     os << style->stroke_linecap.computed << " setlinecap\n";
777 unsigned int
778 PrintPS::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
779               NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
781     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
782     if (_bitmap) return 0;
784     if ( style->fill.type == SP_PAINT_TYPE_COLOR
785          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
786               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
787     {
788         Inkscape::SVGOStringStream os;
790         os << "gsave\n";
792         print_fill_style(os, style, pbox);
794         print_bpath(os, bpath->path);
796         if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
797             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
798                 os << "eofill\n";
799             } else {
800                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
801                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
802                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
803                 os << "eoclip\n";
804                 if (g->gradientTransform_set) {
805                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
806                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
807                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
808                 }
809                 os << "shfill\n";
810                 if (g->gradientTransform_set) {
811                     os << "grestore\n";
812                 }
813             }
814         } else {
815             if (style->fill.type == SP_PAINT_TYPE_COLOR) {
816                 os << "fill\n";
817             } else {
818                 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
819                           && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
820                 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
821                 os << "clip\n";
822                 if (g->gradientTransform_set) {
823                     os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
824                         << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
825                         << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
826                 }
827                 os << "shfill\n";
828                 if (g->gradientTransform_set) {
829                     os << "grestore\n";
830                 }
831             }
832         }
834         os << "grestore\n";
836         fprintf(_stream, "%s", os.str().c_str());
837     }
839     return 0;
843 unsigned int
844 PrintPS::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
845                 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
847     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
848     if (_bitmap) return 0;
850     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
851         Inkscape::SVGOStringStream os;
853         print_stroke_style(os, style);
855         print_bpath(os, bpath->path);
857         os << "stroke\n";
859         fprintf(_stream, "%s", os.str().c_str());
860     }
862     return 0;
865 unsigned int
866 PrintPS::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
867                NRMatrix const *transform, SPStyle const *style)
869     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
870     if (_bitmap) return 0;
872     return print_image(_stream, px, w, h, rs, transform);
875 /* PSFontName is now useless (cf. text() method code) */
876 char const *
877 PrintPS::PSFontName(SPStyle const *style)
879     font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
881     char const *n;
882     char name_buf[256];
884     // PS does not like spaces in fontnames, replace them with the usual dashes.
886     if (tf) {
887         tf->PSName(name_buf, sizeof(name_buf));
888         n = g_strdelimit(name_buf, " ", '-');
889         tf->Unref();
890     } else {
891         // 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
892         bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
893         bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
894         bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
895             (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
897         n = g_strdup_printf("%s%s%s%s",
898                             g_strdelimit(style->text->font_family.value, " ", '-'), 
899                             (b || i || o) ? "-" : "",
900                             (b) ? "Bold" : "",
901                             (i) ? "Italic" : ((o) ? "Oblique" : "") );
902     }
904     return g_strdup(n);
907 //LSB = Least Significant Byte
908 //converts 4-byte array to "LSB first" to "LSB last"
909 /**
910 * (Used by PrintPS::embed_t1 (from libgnomeprint/gnome-font-face.c),
911 * to get the length of data segment (bytes 3-6 in IBM PC (PostScript) font file format.
912 * Reference: Adobe technical note 5040, "Supporting Downloadable PostScript
913 * Language Fonts", page 9)
914 */
916 #define INT32_LSB_2_5(q) ((q)[2] + ((q)[3] << 8) + ((q)[4] << 16) + ((q)[5] << 24))
918 /**
919 * \brief For "Type 1" font only, print font data in output stream, to embed font data in PS output.
920 * \param os Stream of output.
921 * \param font Font whose data to embed.
922 * \return FALSE if font embedding canceled (due to error or not supported font type), TRUE otherwise
923 * TODO: enable font embedding for True Type
924 */
925 //adapted more/less from libgnomeprint/gnome_font_face_ps_embed_t1()
926 bool
927 PrintPS::embed_t1 (SVGOStringStream &os, font_instance* font)
929         //check font type
930         FT_Face font_face = pango_ft2_font_get_face(font->pFont);
931         const FT_String* font_type = FT_Get_X11_Font_Format(font_face);
932         g_return_val_if_fail (_fontTypesMap[font_type] == FONT_TYPE1, false);
933         //get font filename, stream to font file and size
934         FT_Stream font_stream = font_face->stream;
935         const char* font_filename = (char*) font_stream->pathname.pointer;
936         unsigned long font_stream_size = font_stream->size;
937         //first detect if font file is in IBM PC format
938         /**
939         * if first byte is 0x80, font file is pfb, do the same as a pfb to pfa converter
940         * Reference: Adobe technical note 5040, "Supporting Downloadable PostScript
941         * Language Fonts", page 9
942         * else: include all the ASCII data in the font pfa file
943         **/
944         char* buf = new char[7];
945         unsigned char* buffer = new unsigned char[7];//for the 6 header bytes (data segment length is unknown at this point) and final '\0'
946         std::string ascii_data;//for data segment "type 1" in IBM PC Format
947         //read the 6 header bytes
948         //for debug: g_warning("Reading from font file %s...", font_filename);
949         font_stream->close(font_stream);
950         ifstream font_file (font_filename, ios::in|ios::binary);
951         if (!font_file.is_open()) {
952                 g_warning ("file %s: line %d: Cannot open font file %s", __FILE__, __LINE__, font_filename);
953                 return false;
954         }
955         font_file.read(buf, 6);
956         buffer = (unsigned char*) buf;
958         //If font file is pfb, do the same as pfb to pfa converter
959         //check byte 1
960         if (buffer[0] == 0x80) {
961                 const char hextab[17] = "0123456789abcdef";
962                 unsigned long offset = 0;
964                 while (offset < font_stream_size) {
965                         gint length, i;
966                         if (buffer[0] != 0x80) {
967                                 g_warning ("file %s: line %d: Corrupt %s", __FILE__, __LINE__, font_filename);
968                                 //TODO: print some default font data anyway like libgnomeprint/gnome_font_face_ps_embed_empty
969                                 return false;
970                         }
971                         switch (buffer[1]) {
972                         case 1:
973                                 //get data segment length from bytes 3-6
974                                 //(Note: byte 1 is first byte in comments to match Adobe technical note 5040, but index 0 in code)
975                                 length = INT32_LSB_2_5 (buffer);
976                                 offset += 6;
977                                 //resize the buffer to fit the data segment length
978                                 delete [] buf;
979                                 buf = new char[length + 1];
980                                 buffer = new unsigned char[length + 1];
981                                 //read and print all the data segment length
982                                 font_file.read(buf, length);
983                                 buffer = (unsigned char*) buf;
984                                 /**
985                                 * Assigning a part from the buffer of length "length" ensures
986                                 * that no incorrect extra character will be printed and make the PS output invalid
987                                 * That was the case with the code:
988                                 * os << buffer;
989                                 * (A substring method could have been used as well.)
990                                 */
991                                 ascii_data.assign(buf, 0, length);
992                                 os << ascii_data;
993                                 offset += length;
994                                 //read next 6 header bytes
995                                 font_file.read(buf, 6);
996                                 break;
997                         case 2:
998                                 length = INT32_LSB_2_5 (buffer);
999                                 offset += 6;
1000                                 //resize the buffer to fit the data segment length
1001                                 delete [] buf;
1002                                 buf = new char[length + 1];
1003                                 buffer = new unsigned char[length + 1];
1004                                 //read and print all the data segment length
1005                                 font_file.read(buf, length);
1006                                 buffer = (unsigned char*) buf;
1007                                 for (i = 0; i < length; i++) {
1008                                         os << hextab[buffer[i] >> 4];
1009                                         os << hextab[buffer[i] & 15];
1010                                         offset += 1;
1011                                         if ((i & 31) == 31 || i == length - 1)
1012                                                 os << "\n";
1013                                 }
1014                                 //read next 6 header bytes
1015                                 font_file.read(buf, 6);
1016                                 break;
1017                         case 3:
1018                                 /* Finished */
1019                                 os << "\n";
1020                                 offset = font_stream_size;
1021                                 break;
1022                         default:
1023                                 os << "%%%ERROR: Font file corrupted at byte " << offset << "\n";
1024                                 //TODO: print some default font data anyway like libgnomeprint/gnome_font_face_ps_embed_empty
1025                                 return false;
1026                         }
1027                 }
1028         }
1029         //else: font file is pfa, include all directly
1030         else {
1031                 //font is not in IBM PC format, all the file content can be directly printed
1032                 //resize buffer
1033                 delete [] buf;
1034                 buf = new char[font_stream_size + 1];
1035                 delete [] buffer;
1036                 font_file.seekg (0, ios::beg);
1037                 font_file.read(buf, font_stream_size);
1038                 /**
1039                  * Assigning a part from the buffer of length "length" ensures
1040                  * that no incorrect extra character will be printed and make the PS output invalid
1041                  * That was the case with the code:
1042                  * os << buffer;
1043                  * (A substring method could have been used as well.)
1044                  */
1045                 ascii_data.assign(buf, 0, font_stream_size);
1046                 os << ascii_data;
1047         }
1048         font_file.close();
1049         delete [] buf;
1050         buf = NULL;
1051         buffer = NULL;// Clear buffer to prevent using invalid memory reference.
1053         char font_psname[256];
1054         font->PSName(font_psname, sizeof(font_psname));
1055         FT_Long font_num_glyphs = font_face->num_glyphs;
1056         if (font_num_glyphs < 256) {
1057                 gint glyph;
1058                 /* 8-bit vector */
1059                 os << "(" << font_psname << ") cvn findfont dup length dict begin\n";
1060                 os << "{1 index /FID ne {def} {pop pop} ifelse} forall\n";
1061                 os << "/Encoding [\n";
1062                 for (glyph = 0; glyph < 256; glyph++) {
1063                         guint g;
1064                         gchar c[256];
1065                         FT_Error status;
1066                         g = (glyph < font_num_glyphs) ? glyph : 0;
1067                         status = FT_Get_Glyph_Name (font_face, g, c, 256);
1069                         if (status != FT_Err_Ok) {
1070                                 g_warning ("file %s: line %d: Glyph %d has no name in %s", __FILE__, __LINE__, g, font_filename);
1071                                 g_snprintf (c, 256, ".notdef");
1072                         }
1074                         os << "/" << c << ( ((glyph & 0xf) == 0xf)?"\n":" " );
1075                 }
1076                 os << "] def currentdict end\n";
1077                 //TODO: manage several font instances for same ps name like in libgnomeprint/gnome_print_ps2_set_font_real()
1078                 //gf_pso_sprintf (pso, "(%s) cvn exch definefont pop\n", pso->encodedname);
1079                 os << "(" << font_psname << ") cvn exch definefont pop\n";
1080         } else {
1081                 gint nfonts, i, j;
1082                 /* 16-bit vector */
1083                 nfonts = (font_num_glyphs + 255) >> 8;
1085                 os << "32 dict begin\n";
1086                 /* Common entries */
1087                 os << "/FontType 0 def\n";
1088                 os << "/FontMatrix [1 0 0 1 0 0] def\n";
1089                 os << "/FontName (" << font_psname << "-Glyph-Composite) cvn def\n";
1090                 os << "/LanguageLevel 2 def\n";
1092                 /* Type 0 entries */
1093                 os << "/FMapType 2 def\n";
1095                 /* Bitch 'o' bitches */
1096                 os << "/FDepVector [\n";
1098                 for (i = 0; i < nfonts; i++) {
1099                         os << "(" << font_psname << ") cvn findfont dup length dict begin\n";
1100                         os << "{1 index /FID ne {def} {pop pop} ifelse} forall\n";
1101                         os << "/Encoding [\n";
1102                         for (j = 0; j < 256; j++) {
1103                                 gint glyph;
1104                                 gchar c[256];
1105                                 FT_Error status;
1106                                 glyph = 256 * i + j;
1107                                 if (glyph >= font_num_glyphs)
1108                                         glyph = 0;
1109                                 status = FT_Get_Glyph_Name (font_face, glyph, c, 256);
1110                                 if (status != FT_Err_Ok) {
1111                                         g_warning ("file %s: line %d: Glyph %d has no name in %s", __FILE__, __LINE__, glyph, font_filename);
1112                                         g_snprintf (c, 256, ".notdef");
1113                                 }
1114                                 os << "/" << c << ( ((j & 0xf) == 0xf)?"\n":" " );
1115                         }
1116                         os << "] def\n";
1117                         os << "currentdict end (" << font_psname << "-Glyph-Page-";
1118                         os << std::dec << i;
1119                         os << ") cvn exch definefont\n";
1120                 }
1121                 os << "] def\n";
1122                 os << "/Encoding [\n";
1123                 for (i = 0; i < 256; i++) {
1124                         gint fn;
1125                         fn = (i < nfonts) ? i : 0;
1126                         os << std::dec << fn;
1127                         os << ( ((i & 0xf) == 0xf) ? "\n" : " " );
1128                 }
1129                 os << "] def\n";
1130                 os << "currentdict end\n";
1131                 //TODO: manage several font instances for same ps name like in libgnomeprint/gnome_print_ps2_set_font_real()
1132                 //gf_pso_sprintf (pso, "(%s) cvn exch definefont pop\n", pso->encodedname);
1133                 os << "(" << font_psname << ") cvn exch definefont pop\n";
1134         }
1135         //font embedding completed
1136         return true;
1141 /**
1142 * \brief Print font data in output stream, to embed font data in PS output.
1143 * \param os Stream of output.
1144 * \param font Font whose data to embed.
1145 * \return FALSE if font embedding canceled (due to error or not supported font type), TRUE otherwise
1146 */
1147 //adapted from libgnomeprint/gnome_font_face_ps_embed()
1148 bool PrintPS::embed_font(SVGOStringStream &os, font_instance* font)
1150   //Hinted at by a comment in libgnomeprint/fcpattern_to_gp_font_entry()
1151   //Determining the font type in the "Pango way"
1152   FT_Face font_face = pango_ft2_font_get_face(font->pFont);
1153   const FT_String* font_type = FT_Get_X11_Font_Format(font_face);
1155   /**
1156   * Possible values of "font_type": Type 1, TrueType, etc.
1157   * Embedding available only for Type 1 fonts so far.
1158   */
1159   //TODO: provide support for other font types (TrueType is a priority)
1160   switch(_fontTypesMap[font_type])
1161   {
1162     case FONT_TYPE1:
1163       return embed_t1 (os, font);
1164     //TODO: implement TT font embedding
1165     /*case FONT_TRUETYPE:
1166       embed_tt (os, font);
1167       break;*/
1168     default:
1169       g_warning("Unknown (not supported) font type for embedding: %s", font_type);
1170       //TODO: embed something like in libgnomeprint/gnome_font_face_ps_embed_empty();
1171       return false;
1172   }
1176 /**
1177 * \brief Converts UTF-8 string to sequence of glyph numbers for PostScript string (cf. "show" commands.).
1178 * \param os Stream of output.
1179 * \param font Font used for unicode->glyph mapping.
1180 * \param unistring UTF-8 encoded string to convert.
1181 */
1182 void PrintPS::print_glyphlist(SVGOStringStream &os, font_instance* font, Glib::ustring unistring)
1184   //iterate through unicode chars in unistring
1185   Glib::ustring::iterator unistring_iter;
1186   gunichar unichar;
1187   gint glyph_index, glyph_page;
1188   
1189   FT_Face font_face = pango_ft2_font_get_face(font->pFont);
1190   FT_Long font_num_glyphs = font_face->num_glyphs;
1191   //whether font has more than one glyph pages (16-bit encoding)
1192   bool two_bytes_encoded = (font_num_glyphs > 255);
1194   for (unistring_iter = unistring.begin();   unistring_iter!=unistring.end();  unistring_iter++)
1195   {
1196     //get unicode char
1197     unichar = *unistring_iter;
1198     //get matching glyph index in current font for unicode char
1199     //default glyph index is 0 for undefined font character (glyph unavailable)
1200     //TODO: if glyph unavailable for current font, use a default font among the most Unicode-compliant - e.g. Bitstream Cyberbit - I guess
1201     glyph_index = font->MapUnicodeChar(unichar);
1202     //if more than one glyph pages for current font (16-bit encoding),
1203     if(two_bytes_encoded)
1204     {
1205       //add glyph page before glyph index.
1206       glyph_page = (glyph_index >> 8) & 0xff;
1207       os << "\\";
1208       //convert in octal code before printing
1209       os << std::oct << glyph_page;
1210     }
1211     //(If one page - 8-bit encoding -, nothing to add.)
1212     //TODO: explain the following line inspired from libgnomeprint/gnome_print_ps2_glyphlist()
1213     glyph_index = glyph_index & 0xff;
1214     //TODO: mark glyph as used for current font, if Inkscape has to embed minimal font data in PS
1215     os << "\\";
1216     //convert in octal code before printing
1217     os << std::oct << glyph_index;
1218   }
1221 unsigned int
1222 PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
1223               SPStyle const *const style)
1225     if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
1226     if (_bitmap) return 0;
1228     //check whether fonts have to be embedded in the PS output
1229     //if not, use the former way of Inkscape to print text
1230     gboolean font_embedded = mod->fontEmbedded();
1232     Inkscape::SVGOStringStream os;
1233     //find font
1234     /**
1235     * A font_instance object is necessary for the next steps,
1236     * that's why using PSFontName() method just to get the PS fontname
1237     * is not enough and not appropriate
1238     */
1239     font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
1240     const gchar *fn = NULL;
1241     char name_buf[256];
1243     //check whether font was found
1244     /**
1245     * This check is not strictly reliable
1246     * since Inkscape returns a default font if font not found.
1247     * This is just to be consistent with the method PSFontName().
1248     */
1249     if (tf) {
1250         //get font PS name
1251         tf->PSName(name_buf, sizeof(name_buf));
1252         fn = name_buf;
1253     } else {
1254         // this system does not have this font, so cancel font embedding...
1255         font_embedded = FALSE;
1256         //this case seems to never happen since Inkscape uses a default font instead (like BitstreamVeraSans on Windows)
1257         g_warning("Font %s not found.", fn);
1258         //...and just use the name from SVG in the hope that PS interpreter will make sense of it
1259         bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
1260         bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
1261         bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
1262             (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
1264         fn = g_strdup_printf("%s%s%s%s",
1265                             g_strdelimit(style->text->font_family.value, " ", '-'),
1266                             (b || i || o) ? "-" : "",
1267                             (b) ? "Bold" : "",
1268                             (i) ? "Italic" : ((o) ? "Oblique" : "") );
1269     }
1271     /**
1272     * If font embedding is requested, tempt to embed the font the first time it is used, once and for all.
1273     * There is no selection of the glyph descriptions to embed, based on the characters used effectively in the document.
1274     * (TODO?)
1275     * Else, back to the former way of printing.
1276     */
1277     gpointer  is_embedded;
1278     //if not first time the font is used and if font embedding requested, check whether the font has been embedded (successfully the first time).
1279     if(g_tree_lookup_extended(_fonts, fn, NULL, &is_embedded)) font_embedded = font_embedded && (strcmp((char *)is_embedded, "TRUE") == 0);
1280     else
1281     {
1282       //first time the font is used
1283       if(font_embedded)
1284       {
1285         //embed font in PS output
1286         //adapted from libgnomeprint/gnome_print_ps2_close()
1287         os << "%%BeginResource: font " << fn << "\n";
1288         font_embedded = embed_font(os, tf);
1289         os << "%%EndResource: font " << fn << "\n";
1290         if(!font_embedded) g_warning("Font embedding canceled for font: %s", fn);
1291         else fprintf(_begin_stream, "%s", os.str().c_str());
1292         //empty os before resume printing to the script stream
1293         std::string clrstr = "";
1294         os.str(clrstr);
1296       }
1297       //add to the list
1298       g_tree_insert(_fonts, g_strdup(fn), g_strdup((font_embedded)?"TRUE":"FALSE"));
1299     }
1300     
1301     Glib::ustring s;
1302     // Escape chars
1303     Inkscape::SVGOStringStream escaped_text;
1304     //if font embedding, all characters will be converted to glyph indices (cf. PrintPS::print_glyphlist()),
1305     //so no need to escape characters
1306     //else back to the old way, i.e. escape chars: '\',')','(' and UTF-8 ones
1307     if(font_embedded) s = text;
1308     else {
1309         escaped_text << std::oct;
1310         for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
1311                 gunichar const c = g_utf8_get_char(p_text);
1312                 if (c == '\\' || c == ')' || c == '(')
1313                 escaped_text << '\\' << static_cast<char>(c);
1314                 else if (c >= 0x80)
1315                 escaped_text << '\\' << c;
1316                 else
1317                 escaped_text << static_cast<char>(c);
1318         }
1319     }
1321     os << "gsave\n";
1323     // set font
1324     if(font_embedded) os << "/" << fn << " findfont\n";
1325     else {
1326         if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
1327                 if (!_newlatin1font_proc_defined) {
1328                 // input: newfontname, existingfontname
1329                 // output: new font object, also defined to newfontname
1330                 os << "/newlatin1font "         // name of the proc
1331                         "{findfont dup length dict copy "     // load the font and create a copy of it
1332                         "dup /Encoding ISOLatin1Encoding put "     // change the encoding in the copy
1333                         "definefont} def\n";      // create the new font and leave it on the stack, define the proc
1334                 _newlatin1font_proc_defined = true;
1335                 }
1336                 os << "/" << fn << "-ISOLatin1 /" << fn << " newlatin1font\n";
1337                 _latin1_encoded_fonts.insert(fn);
1338         } else
1339                 os << "/" << fn << "-ISOLatin1 findfont\n";
1340     }
1341     os << style->font_size.computed << " scalefont\n";
1342     os << "setfont\n";
1343    //The commented line beneath causes Inkscape to crash under Linux but not under Windows
1344     //g_free((void*) fn);
1346     if ( style->fill.type == SP_PAINT_TYPE_COLOR
1347          || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
1348               && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
1349     {
1350         // set fill style
1351         print_fill_style(os, style, NULL);
1352         // FIXME: we don't know the pbox of text, so have to pass NULL. This means gradients with
1353         // bbox units won't work with text. However userspace gradients don't work with text either
1354         // (text is black) for some reason.
1356         os << "newpath\n";
1357         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
1358         os << "(";
1359         if(font_embedded) print_glyphlist(os, tf, s);
1360         else os << escaped_text.str();
1361         os << ") show\n";
1362     }
1364     if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
1366         // set stroke style
1367         print_stroke_style(os, style);
1369         // paint stroke
1370         os << "newpath\n";
1371         os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
1372         os << "(";
1373         if(font_embedded) print_glyphlist(os, tf, s);
1374         else os << escaped_text.str();
1375         os << ") false charpath stroke\n";
1376     }
1378     if(tf) tf->Unref();
1380     os << "grestore\n";
1382     fprintf(_stream, "%s", os.str().c_str());
1384     return 0;
1389 /* PostScript helpers */
1391 void
1392 PrintPS::print_bpath(SVGOStringStream &os, NArtBpath const *bp)
1394     os << "newpath\n";
1395     bool closed = false;
1396     while (bp->code != NR_END) {
1397         switch (bp->code) {
1398             case NR_MOVETO:
1399                 if (closed) {
1400                     os << "closepath\n";
1401                 }
1402                 closed = true;
1403                 os << bp->x3 << " " << bp->y3 << " moveto\n";
1404                 break;
1405             case NR_MOVETO_OPEN:
1406                 if (closed) {
1407                     os << "closepath\n";
1408                 }
1409                 closed = false;
1410                 os << bp->x3 << " " << bp->y3 << " moveto\n";
1411                 break;
1412             case NR_LINETO:
1413                 os << bp->x3 << " " << bp->y3 << " lineto\n";
1414                 break;
1415             case NR_CURVETO:
1416                 os << bp->x1 << " " << bp->y1 << " "
1417                    << bp->x2 << " " << bp->y2 << " "
1418                    << bp->x3 << " " << bp->y3 << " curveto\n";
1419                 break;
1420             default:
1421                 break;
1422         }
1423         bp += 1;
1424     }
1425     if (closed) {
1426         os << "closepath\n";
1427     }
1430 /* The following code is licensed under GNU GPL.
1431 ** The packbits, ascii85 and imaging printing code
1432 ** is from the gimp's postscript.c.
1433 */
1435 /**
1436 * \param nin Number of bytes of source data.
1437 * \param src Source data.
1438 * \param nout Number of output bytes.
1439 * \param dst Buffer for output.
1440 */
1441 void
1442 PrintPS::compress_packbits(int nin,
1443                            guchar *src,
1444                            int *nout,
1445                            guchar *dst)
1448     register guchar c;
1449     int nrepeat, nliteral;
1450     guchar *run_start;
1451     guchar *start_dst = dst;
1452     guchar *last_literal = NULL;
1454     for (;;) {
1455         if (nin <= 0) break;
1457         run_start = src;
1458         c = *run_start;
1460         /* Search repeat bytes */
1461         if ((nin > 1) && (c == src[1])) {
1462             nrepeat = 1;
1463             nin -= 2;
1464             src += 2;
1465             while ((nin > 0) && (c == *src)) {
1466                 nrepeat++;
1467                 src++;
1468                 nin--;
1469                 if (nrepeat == 127) break; /* Maximum repeat */
1470             }
1472             /* Add two-byte repeat to last literal run ? */
1473             if ( (nrepeat == 1)
1474                  && (last_literal != NULL) && (((*last_literal)+1)+2 <= 128) )
1475             {
1476                 *last_literal += 2;
1477                 *(dst++) = c;
1478                 *(dst++) = c;
1479                 continue;
1480             }
1482             /* Add repeat run */
1483             *(dst++) = (guchar)((-nrepeat) & 0xff);
1484             *(dst++) = c;
1485             last_literal = NULL;
1486             continue;
1487         }
1488         /* Search literal bytes */
1489         nliteral = 1;
1490         nin--;
1491         src++;
1493         for (;;) {
1494             if (nin <= 0) break;
1496             if ((nin >= 2) && (src[0] == src[1])) /* A two byte repeat ? */
1497                 break;
1499             nliteral++;
1500             nin--;
1501             src++;
1502             if (nliteral == 128) break; /* Maximum literal run */
1503         }
1505         /* Could be added to last literal run ? */
1506         if ((last_literal != NULL) && (((*last_literal)+1)+nliteral <= 128)) {
1507             *last_literal += nliteral;
1508         } else {
1509             last_literal = dst;
1510             *(dst++) = (guchar)(nliteral-1);
1511         }
1512         while (nliteral-- > 0) *(dst++) = *(run_start++);
1513     }
1514     *nout = dst - start_dst;
1517 void
1518 PrintPS::ascii85_init(void)
1520     ascii85_len = 0;
1521     ascii85_linewidth = 0;
1524 void
1525 PrintPS::ascii85_flush(SVGOStringStream &os)
1527     char c[5];
1528     bool const zero_case = (ascii85_buf == 0);
1529     static int const max_linewidth = 75;
1531     for (int i = 4; i >= 0; i--) {
1532         c[i] = (ascii85_buf % 85) + '!';
1533         ascii85_buf /= 85;
1534     }
1535     /* check for special case: "!!!!!" becomes "z", but only if not
1536      * at end of data. */
1537     if (zero_case && (ascii85_len == 4)) {
1538         if (ascii85_linewidth >= max_linewidth) {
1539             os << '\n';
1540             ascii85_linewidth = 0;
1541         }
1542         os << 'z';
1543         ascii85_linewidth++;
1544     } else {
1545         for (int i = 0; i < ascii85_len+1; i++) {
1546             if ((ascii85_linewidth >= max_linewidth) && (c[i] != '%')) {
1547                 os << '\n';
1548                 ascii85_linewidth = 0;
1549             }
1550             os << c[i];
1551             ascii85_linewidth++;
1552         }
1553     }
1555     ascii85_len = 0;
1556     ascii85_buf = 0;
1559 inline void
1560 PrintPS::ascii85_out(guchar byte, SVGOStringStream &os)
1562     if (ascii85_len == 4)
1563         ascii85_flush(os);
1565     ascii85_buf <<= 8;
1566     ascii85_buf |= byte;
1567     ascii85_len++;
1570 void
1571 PrintPS::ascii85_nout(int n, guchar *uptr, SVGOStringStream &os)
1573     while (n-- > 0) {
1574         ascii85_out(*uptr, os);
1575         uptr++;
1576     }
1579 void
1580 PrintPS::ascii85_done(SVGOStringStream &os)
1582     if (ascii85_len) {
1583         /* zero any unfilled buffer portion, then flush */
1584         ascii85_buf <<= (8 * (4-ascii85_len));
1585         ascii85_flush(os);
1586     }
1588     os << "~>\n";
1591 unsigned int
1592 PrintPS::print_image(FILE *ofp, guchar *px, unsigned int width, unsigned int height, unsigned int rs,
1593                      NRMatrix const *transform)
1595     Inkscape::SVGOStringStream os;
1597     os << "gsave\n";
1599     os << "[" << transform->c[0] << " "
1600        << transform->c[1] << " "
1601        << transform->c[2] << " "
1602        << transform->c[3] << " "
1603        << transform->c[4] << " "
1604        << transform->c[5] << "] concat\n";
1606     /* Write read image procedure */
1607     os << "<<\n";
1608     os << "  /ImageType 3\n";
1609     os << "  /InterleaveType 1\n";
1611     os << "  /MaskDict\n";
1612     os << "  <<\n";
1613     os << "    /ImageType 1\n";
1614     os << "    /Width " << width << "\n";
1615     os << "    /Height " << height << "\n";
1616     os << "    /ImageMatrix "
1617        << "[" << width << " "
1618        << 0 << " "
1619        << 0 << " "
1620        << -((long) height) << " "
1621        << 0 << " "
1622        << height << "]\n";
1623     os << "    /BitsPerComponent 8\n";
1624     os << "    /Decode [1 0]\n";
1625     os << "  >>\n";
1627     os << "  /DataDict\n";
1628     os << "  <<\n";
1629     os << "    /ImageType 1\n";
1630     os << "    /Width " << width << "\n";
1631     os << "    /Height " << height << "\n";
1632     os << "    /ImageMatrix "
1633        << "[" << width << " "
1634        << 0 << " "
1635        << 0 << " "
1636        << -((long )height) << " "
1637        << 0 << " "
1638        << height << "]\n";
1639     os << "    /DataSource currentfile /ASCII85Decode filter\n";
1640     os << "    /BitsPerComponent 8\n";
1641     os << "    /Decode [0 1 0 1 0 1]\n";
1642     os << "  >>\n";
1644     os << ">>\n";
1646     /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
1647     guchar *const packb = (guchar *)g_malloc((4*width * 105)/100+2);
1648     guchar *const plane = (guchar *)g_malloc(4*width);
1650     os << "image\n";
1652     ascii85_init();
1653     
1654     for (unsigned i = 0; i < height; i++) {
1655         guchar const *const src = px + i * rs;
1657         guchar const *src_ptr = src;
1658         guchar *plane_ptr = plane;
1659         for (unsigned j = 0; j < width; j++) {
1660             *(plane_ptr++) = *(src_ptr+3);
1661             *(plane_ptr++) = *(src_ptr+0);
1662             *(plane_ptr++) = *(src_ptr+1);
1663             *(plane_ptr++) = *(src_ptr+2);
1664             src_ptr += 4;
1665         }
1666         
1667         ascii85_nout(4*width, plane, os);
1668     }
1669     ascii85_done(os);
1671     g_free(packb);
1672     g_free(plane);
1674     os << "grestore\n";
1676     fprintf(ofp, "%s", os.str().c_str());
1678     return 0;
1681 bool
1682 PrintPS::textToPath(Inkscape::Extension::Print * ext)
1684     return ext->get_param_bool("textToPath");
1687 /**
1688 * \brief Get "fontEmbedded" param
1689 * \retval TRUE Fonts have to be embedded in the output so that the user might not need to install fonts to have the interpreter read the document correctly
1690 * \retval FALSE No font embedding
1692 * Only available for Adobe Type 1 fonts in EPS output till now
1693 */
1694 bool
1695 PrintPS::fontEmbedded(Inkscape::Extension::Print * ext)
1697     return ext->get_param_bool("fontEmbedded");
1700 #include "clear-n_.h"
1702 void
1703 PrintPS::init(void)
1705     /* SVG in */
1706     (void) Inkscape::Extension::build_from_mem(
1707         "<inkscape-extension>\n"
1708         "<name>" N_("Postscript Print") "</name>\n"
1709         "<id>" SP_MODULE_KEY_PRINT_PS "</id>\n"
1710         "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1711         "<param name=\"resolution\" type=\"string\">72</param>\n"
1712         "<param name=\"destination\" type=\"string\">| lp</param>\n"
1713         "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1714         "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1715         "<param name=\"fontEmbedded\" type=\"boolean\">FALSE</param>\n"
1716         "<print/>\n"
1717         "</inkscape-extension>", new PrintPS());
1721 }  /* namespace Internal */
1722 }  /* namespace Extension */
1723 }  /* namespace Inkscape */
1725 /* End of GNU GPL code */
1728 /*
1729   Local Variables:
1730   mode:c++
1731   c-file-style:"stroustrup"
1732   c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1733   indent-tabs-mode:nil
1734   fill-column:99
1735   End:
1736 */
1737 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :