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