Code

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