Code

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