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