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