Code

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