Code

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