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