Code

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