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) 1995 Spencer Kimball and Peter Mattis
17 * Copyright (C) 1997-98 Peter Kirchgessner
18 * George White <aa056@chebucto.ns.ca>
19 * Austin Donnelly <austin@gimp.org>
20 *
21 * Licensed under GNU GPL
22 */
24 /* Plain Print */
26 #ifdef HAVE_CONFIG_H
27 # include "config.h"
28 #endif
30 #include <signal.h>
31 #include <errno.h>
33 #include <libnr/n-art-bpath.h>
35 #include <glib/gmem.h>
36 #include <gtk/gtkstock.h>
37 #include <gtk/gtkvbox.h>
38 #include <gtk/gtkframe.h>
39 #include <gtk/gtkradiobutton.h>
40 #include <gtk/gtkcombo.h>
41 #include <gtk/gtklabel.h>
42 #include <gtk/gtkentry.h>
43 #include <gtk/gtktooltips.h>
45 #include <glibmm/i18n.h>
46 #include "display/nr-arena-item.h"
47 #include "display/canvas-bpath.h"
48 #include "sp-item.h"
49 #include "style.h"
50 #include "sp-linear-gradient.h"
51 #include "sp-radial-gradient.h"
53 #include "libnrtype/font-instance.h"
54 #include "libnrtype/font-style-to-pos.h"
56 #include <unit-constants.h>
58 #include "ps.h"
59 #include "extension/system.h"
60 #include "extension/print.h"
62 #include "io/sys.h"
64 namespace Inkscape {
65 namespace Extension {
66 namespace Internal {
68 PrintPS::PrintPS() :
69 _stream(NULL),
70 _dpi(72),
71 _bitmap(false)
72 {
73 }
75 PrintPS::~PrintPS(void)
76 {
77 /* fixme: should really use pclose for popen'd streams */
78 if (_stream) fclose(_stream);
80 /* restore default signal handling for SIGPIPE */
81 #if !defined(_WIN32) && !defined(__WIN32__)
82 (void) signal(SIGPIPE, SIG_DFL);
83 #endif
85 return;
86 }
88 unsigned int
89 PrintPS::setup(Inkscape::Extension::Print * mod)
90 {
91 static gchar const *const pdr[] = {"72", "75", "100", "144", "150", "200", "300", "360", "600", "1200", "2400", NULL};
93 #ifdef TED
94 Inkscape::XML::Node *repr = ((SPModule *) mod)->repr;
95 #endif
97 unsigned int ret = FALSE;
99 /* Create dialog */
100 GtkTooltips *tt = gtk_tooltips_new();
101 g_object_ref((GObject *) tt);
102 gtk_object_sink((GtkObject *) tt);
104 GtkWidget *dlg = gtk_dialog_new_with_buttons(_("Print Destination"),
105 // SP_DT_WIDGET(SP_ACTIVE_DESKTOP)->window,
106 NULL,
107 (GtkDialogFlags) (GTK_DIALOG_MODAL | GTK_DIALOG_NO_SEPARATOR | GTK_DIALOG_DESTROY_WITH_PARENT),
108 GTK_STOCK_CANCEL,
109 GTK_RESPONSE_CANCEL,
110 GTK_STOCK_PRINT,
111 GTK_RESPONSE_OK,
112 NULL);
114 gtk_dialog_set_default_response(GTK_DIALOG(dlg), GTK_RESPONSE_OK);
116 GtkWidget *vbox = GTK_DIALOG(dlg)->vbox;
117 gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
118 /* Print properties frame */
119 GtkWidget *f = gtk_frame_new(_("Print properties"));
120 gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
121 GtkWidget *vb = gtk_vbox_new(FALSE, 4);
122 gtk_container_add(GTK_CONTAINER(f), vb);
123 gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
124 /* Print type */
125 bool const p2bm = mod->get_param_bool("bitmap");
126 GtkWidget *rb = gtk_radio_button_new_with_label(NULL, _("Print using PostScript operators"));
127 gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
128 _("Use PostScript vector operators. The resulting image is usually smaller "
129 "in file size and can be arbitrarily scaled, but alpha transparency "
130 "and patterns will be lost."), NULL);
131 if (!p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
132 gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
133 rb = gtk_radio_button_new_with_label(gtk_radio_button_get_group((GtkRadioButton *) rb), _("Print as bitmap"));
134 gtk_tooltips_set_tip((GtkTooltips *) tt, rb,
135 _("Print everything as bitmap. The resulting image is usually larger "
136 "in file size and cannot be arbitrarily scaled without quality loss, "
137 "but all objects will be rendered exactly as displayed."), NULL);
138 if (p2bm) gtk_toggle_button_set_active((GtkToggleButton *) rb, TRUE);
139 gtk_box_pack_start(GTK_BOX(vb), rb, FALSE, FALSE, 0);
140 /* Resolution */
141 GtkWidget *hb = gtk_hbox_new(FALSE, 4);
142 gtk_box_pack_start(GTK_BOX(vb), hb, FALSE, FALSE, 0);
143 GtkWidget *combo = gtk_combo_new();
144 gtk_combo_set_value_in_list(GTK_COMBO(combo), FALSE, FALSE);
145 gtk_combo_set_use_arrows(GTK_COMBO(combo), TRUE);
146 gtk_combo_set_use_arrows_always(GTK_COMBO(combo), TRUE);
147 gtk_widget_set_size_request(combo, 64, -1);
148 gtk_tooltips_set_tip((GtkTooltips *) tt, GTK_COMBO(combo)->entry,
149 _("Preferred resolution (dots per inch) of bitmap"), NULL);
150 /* Setup strings */
151 GList *sl = NULL;
152 for (unsigned i = 0; pdr[i] != NULL; i++) {
153 sl = g_list_prepend(sl, (gpointer) pdr[i]);
154 }
155 sl = g_list_reverse(sl);
156 gtk_combo_set_popdown_strings(GTK_COMBO(combo), sl);
157 g_list_free(sl);
158 if (1) {
159 gchar const *val = mod->get_param_string("resolution");
160 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), val);
161 }
162 gtk_box_pack_end(GTK_BOX(hb), combo, FALSE, FALSE, 0);
163 GtkWidget *l = gtk_label_new(_("Resolution:"));
164 gtk_box_pack_end(GTK_BOX(hb), l, FALSE, FALSE, 0);
166 /* Print destination frame */
167 f = gtk_frame_new(_("Print destination"));
168 gtk_box_pack_start(GTK_BOX(vbox), f, FALSE, FALSE, 4);
169 vb = gtk_vbox_new(FALSE, 4);
170 gtk_container_add(GTK_CONTAINER(f), vb);
171 gtk_container_set_border_width(GTK_CONTAINER(vb), 4);
173 l = gtk_label_new(_("Printer name (as given by lpstat -p);\n"
174 "leave empty to use the system default printer.\n"
175 "Use '> filename' to print to file.\n"
176 "Use '| prog arg...' to pipe to a program."));
177 gtk_box_pack_start(GTK_BOX(vb), l, FALSE, FALSE, 0);
179 GtkWidget *e = gtk_entry_new();
180 if (1) {
181 gchar const *val = mod->get_param_string("destination");
182 gtk_entry_set_text(GTK_ENTRY(e), ( val != NULL
183 ? val
184 : "" ));
185 }
186 gtk_box_pack_start(GTK_BOX(vb), e, FALSE, FALSE, 0);
188 // pressing enter in the destination field is the same as clicking Print:
189 gtk_entry_set_activates_default(GTK_ENTRY(e), TRUE);
191 gtk_widget_show_all(vbox);
193 int const response = gtk_dialog_run(GTK_DIALOG(dlg));
195 g_object_unref((GObject *) tt);
197 if (response == GTK_RESPONSE_OK) {
198 gchar const *fn;
199 char const *sstr;
201 _bitmap = gtk_toggle_button_get_active((GtkToggleButton *) rb);
202 sstr = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
203 _dpi = (unsigned int) MAX((int)(atof(sstr)), 1);
204 /* Arrgh, have to do something */
205 fn = gtk_entry_get_text(GTK_ENTRY(e));
206 /* skip leading whitespace, bug #1068483 */
207 while (fn && *fn==' ') { fn++; }
208 /* g_print("Printing to %s\n", fn); */
210 mod->set_param_bool("bitmap", _bitmap);
211 mod->set_param_string("resolution", (gchar *)sstr);
212 mod->set_param_string("destination", (gchar *)fn);
213 ret = TRUE;
214 }
216 gtk_widget_destroy(dlg);
218 return ret;
219 }
221 unsigned int
222 PrintPS::begin(Inkscape::Extension::Print *mod, SPDocument *doc)
223 {
224 gboolean epsexport = false;
226 _latin1_encoded_fonts.clear();
227 _newlatin1font_proc_defined = false;
229 FILE *osf = NULL;
230 FILE *osp = NULL;
232 gsize bytesRead = 0;
233 gsize bytesWritten = 0;
234 GError *error = NULL;
235 gchar const *utf8_fn = mod->get_param_string("destination");
236 gchar *local_fn = g_filename_from_utf8( utf8_fn,
237 -1, &bytesRead, &bytesWritten, &error);
238 gchar const *fn = local_fn;
240 /* TODO: Replace the below fprintf's with something that does the right thing whether in
241 * gui or batch mode (e.g. --print=blah). Consider throwing an exception: currently one of
242 * the callers (sp_print_document_to_file, "ret = mod->begin(doc)") wrongly ignores the
243 * return code.
244 */
245 if (fn != NULL) {
246 if (*fn == '|') {
247 fn += 1;
248 while (isspace(*fn)) fn += 1;
249 #ifndef WIN32
250 osp = popen(fn, "w");
251 #else
252 osp = _popen(fn, "w");
253 #endif
254 if (!osp) {
255 fprintf(stderr, "inkscape: popen(%s): %s\n",
256 fn, strerror(errno));
257 return 0;
258 }
259 _stream = osp;
260 } else if (*fn == '>') {
261 fn += 1;
262 epsexport = g_str_has_suffix(fn,".eps");
263 while (isspace(*fn)) fn += 1;
264 Inkscape::IO::dump_fopen_call(fn, "K");
265 osf = Inkscape::IO::fopen_utf8name(fn, "w+");
266 if (!osf) {
267 fprintf(stderr, "inkscape: fopen(%s): %s\n",
268 fn, strerror(errno));
269 return 0;
270 }
271 _stream = osf;
272 } else {
273 /* put cwd stuff in here */
274 gchar *qn = ( *fn
275 ? g_strdup_printf("lpr -P %s", fn) /* FIXME: quote fn */
276 : g_strdup("lpr") );
277 #ifndef WIN32
278 osp = popen(qn, "w");
279 #else
280 osp = _popen(qn, "w");
281 #endif
282 if (!osp) {
283 fprintf(stderr, "inkscape: popen(%s): %s\n",
284 qn, strerror(errno));
285 return 0;
286 }
287 g_free(qn);
288 _stream = osp;
289 }
290 }
292 g_free(local_fn);
294 if (_stream) {
295 /* fixme: this is kinda icky */
296 #if !defined(_WIN32) && !defined(__WIN32__)
297 (void) signal(SIGPIPE, SIG_IGN);
298 #endif
299 }
301 int const res = fprintf(_stream, ( epsexport
302 ? "%%!PS-Adobe-3.0 EPSF-3.0\n"
303 : "%%!PS-Adobe-3.0\n" ));
304 /* flush this to test output stream as early as possible */
305 if (fflush(_stream)) {
306 /*g_print("caught error in sp_module_print_plain_begin\n");*/
307 if (ferror(_stream)) {
308 g_print("Error %d on output stream: %s\n", errno,
309 g_strerror(errno));
310 }
311 g_print("Printing failed\n");
312 /* fixme: should use pclose() for pipes */
313 fclose(_stream);
314 _stream = NULL;
315 fflush(stdout);
316 return 0;
317 }
319 // width and height in pt
320 _width = sp_document_width(doc) * PT_PER_PX;
321 _height = sp_document_height(doc) * PT_PER_PX;
323 NRRect d;
324 bool pageBoundingBox;
325 bool pageLandscape;
326 pageBoundingBox = mod->get_param_bool("pageBoundingBox");
327 // printf("Page Bounding Box: %s\n", pageBoundingBox ? "TRUE" : "FALSE");
328 if (pageBoundingBox) {
329 d.x0 = d.y0 = 0;
330 d.x1 = ceil(_width);
331 d.y1 = ceil(_height);
332 } else {
333 SPItem* doc_item = SP_ITEM(sp_document_root(doc));
334 sp_item_invoke_bbox(doc_item, &d, sp_item_i2r_affine(doc_item), TRUE);
335 // convert from px to pt
336 d.x0 *= PT_PER_PX;
337 d.x1 *= PT_PER_PX;
338 d.y0 *= PT_PER_PX;
339 d.y1 *= PT_PER_PX;
340 }
342 Inkscape::SVGOStringStream os;
343 if (res >= 0) {
345 os << "%%Creator: " << PACKAGE_STRING << "\n";
346 // This will become problematic if inkscape gains the
347 // ability to handle multi paged documents. If this is
348 // the case the %%Orientation: comments should be
349 // renamed to %%PageOrientation: and moved to the
350 // respective pages.
351 os << "%%Pages: 1\n";
353 // 2004 Dec 10, BFC:
354 // The point of the following code is (1) to do the thing that's expected by users
355 // who have done File>New>A4_landscape or ...letter_landscape (i.e., rotate
356 // the output), while (2) not messing up users who simply want their output wider
357 // than it is tall (e.g., small figures for inclusion in LaTeX).
358 // The original patch by WQ only had the w>h condition.
359 {
360 double w = (d.x1 - d.x0); // width and height of bounding box, in pt
361 double h = (d.y1 - d.y0);
362 pageLandscape = (
363 (w > 0. && h > 0.) // empty documents fail this sanity check, have w<0, h<0
364 && (w > h) // implies, but does not prove, the user wanted landscape
365 && (w > 600) // approximate maximum printable width of an A4
366 && (!epsexport) // eps should always be portrait
367 )
368 ? true : false;
369 }
371 if (pageLandscape) {
372 os << "%%Orientation: Landscape\n";
373 os << "%%BoundingBox: " << (int) (_height - d.y1) << " "
374 << (int) d.x0 << " "
375 << (int) ceil(_height - d.y0) << " "
376 << (int) ceil(d.x1) << "\n";
377 // According to Mike Sweet (the author of CUPS)
378 // HiResBoundingBox is only appropriate
379 // for EPS files. This means that we should
380 // distinguish if we export to ps or eps here.
381 // FIXME: I couldn't find HiResBoundingBox in the PS
382 // reference manual, so I guess we should skip
383 // it.
384 os << "%%HiResBoundingBox: " << (_height - d.y1) << " "
385 << d.x0 << " "
386 << (_height - d.y0) << " "
387 << d.x1 << "\n";
388 os << "%%DocumentMedia: plain "
389 << (int) ceil(_height) << " "
390 << (int) ceil(_width) << " "
391 << "0 () ()\n";
392 } else {
393 os << "%%Orientation: Portrait\n";
394 os << "%%BoundingBox: " << (int) d.x0 << " "
395 << (int) d.y0 << " "
396 << (int) ceil(d.x1) << " "
397 << (int) ceil(d.y1) << "\n";
398 os << "%%HiResBoundingBox: " << d.x0 << " "
399 << d.y0 << " "
400 << d.x1 << " "
401 << d.y1 << "\n";
402 os << "%%DocumentMedia: plain "
403 << (int) ceil(_width) << " "
404 << (int) ceil(_height) << " "
405 << "0 () ()\n";
406 }
408 os << "%%EndComments\n";
409 // This will become problematic if we print multi paged documents:
410 os << "%%Page: 1 1\n";
412 if (pageLandscape) {
413 os << "90 rotate\n";
414 if (_bitmap) {
415 os << "0 " << (int) -ceil(_height) << " translate\n";
416 }
417 } else {
418 if (!_bitmap) {
419 os << "0 " << (int) ceil(_height) << " translate\n";
420 }
421 }
423 if (!_bitmap) {
424 os << PT_PER_PX << " " << -PT_PER_PX << " scale\n";
425 // from now on we can output px, but they will be treated as pt
426 }
427 }
429 os << "0 0 0 setrgbcolor\n"
430 << "[] 0 setdash\n"
431 << "1 setlinewidth\n"
432 << "0 setlinejoin\n"
433 << "0 setlinecap\n";
435 /* FIXME: This function is declared to return unsigned, whereas fprintf returns a signed int *
436 * that can be zero if the first fprintf failed (os is empty) or "negative" (i.e. very positive
437 * in unsigned int interpretation) if the first fprintf failed but this one succeeds, or
438 * positive if both succeed. */
439 return fprintf(_stream, "%s", os.str().c_str());
440 }
442 unsigned int
443 PrintPS::finish(Inkscape::Extension::Print *mod)
444 {
445 if (!_stream) return 0;
447 if (_bitmap) {
448 double const dots_per_pt = _dpi / PT_PER_IN;
450 double const x0 = 0.0;
451 double const y0 = 0.0;
452 double const x1 = x0 + _width;
453 double const y1 = y0 + _height;
455 /* Bitmap width/height in bitmap dots. */
456 int const width = (int) (_width * dots_per_pt + 0.5);
457 int const height = (int) (_height * dots_per_pt + 0.5);
459 NRMatrix affine;
460 affine.c[0] = width / ((x1 - x0) * PX_PER_PT);
461 affine.c[1] = 0.0;
462 affine.c[2] = 0.0;
463 affine.c[3] = height / ((y1 - y0) * PX_PER_PT);
464 affine.c[4] = -affine.c[0] * x0;
465 affine.c[5] = -affine.c[3] * y0;
467 nr_arena_item_set_transform(mod->root, &affine);
469 guchar *const px = g_new(guchar, 4 * width * 64);
471 for (int y = 0; y < height; y += 64) {
472 /* Set area of interest. */
473 NRRectL bbox;
474 bbox.x0 = 0;
475 bbox.y0 = y;
476 bbox.x1 = width;
477 bbox.y1 = MIN(height, y + 64);
479 /* Update to renderable state. */
480 NRGC gc(NULL);
481 nr_matrix_set_identity(&gc.transform);
482 nr_arena_item_invoke_update(mod->root, &bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
483 /* Render */
484 /* This should take guchar* instead of unsigned char*) */
485 NRPixBlock pb;
486 nr_pixblock_setup_extern(&pb, NR_PIXBLOCK_MODE_R8G8B8A8N,
487 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
488 (guchar*)px, 4 * width, FALSE, FALSE);
489 memset(px, 0xff, 4 * width * 64);
490 nr_arena_item_invoke_render(mod->root, &bbox, &pb, 0);
491 /* Blitter goes here */
492 NRMatrix imgt;
493 imgt.c[0] = (bbox.x1 - bbox.x0) / dots_per_pt;
494 imgt.c[1] = 0.0;
495 imgt.c[2] = 0.0;
496 imgt.c[3] = (bbox.y1 - bbox.y0) / dots_per_pt;
497 imgt.c[4] = 0.0;
498 imgt.c[5] = _height - y / dots_per_pt - (bbox.y1 - bbox.y0) / dots_per_pt;
500 print_image(_stream, px, bbox.x1 - bbox.x0, bbox.y1 - bbox.y0, 4 * width, &imgt);
501 }
503 g_free(px);
504 }
506 fprintf(_stream, "showpage\n");
507 int const res = fprintf(_stream, "%%%%EOF\n");
509 /* Flush stream to be sure. */
510 (void) fflush(_stream);
512 /* fixme: should really use pclose for popen'd streams */
513 fclose(_stream);
514 _stream = 0;
515 _latin1_encoded_fonts.clear();
517 return res;
518 }
520 unsigned int
521 PrintPS::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
522 {
523 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
524 if (_bitmap) return 0;
526 Inkscape::SVGOStringStream os;
527 os << "gsave [" << transform->c[0] << " "
528 << transform->c[1] << " "
529 << transform->c[2] << " "
530 << transform->c[3] << " "
531 << transform->c[4] << " "
532 << transform->c[5] << "] concat\n";
534 return fprintf(_stream, "%s", os.str().c_str());
535 }
537 unsigned int
538 PrintPS::release(Inkscape::Extension::Print *mod)
539 {
540 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
541 if (_bitmap) return 0;
543 return fprintf(_stream, "grestore\n");
544 }
546 unsigned int
547 PrintPS::comment(Inkscape::Extension::Print *mod, char const *comment)
548 {
549 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
550 if (_bitmap) return 0;
552 return fprintf(_stream, "%%! %s\n",comment);
553 }
555 void
556 PrintPS::print_fill_style(SVGOStringStream &os, SPStyle const *const style, NRRect const *pbox)
557 {
558 g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
559 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
560 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
562 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
563 float rgb[3];
564 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
566 os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
568 } else {
569 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
570 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
572 if (SP_IS_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style))) {
574 SPLinearGradient *lg = SP_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style));
575 NR::Point p1 (lg->x1.computed, lg->y1.computed);
576 NR::Point p2 (lg->x2.computed, lg->y2.computed);
577 if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
578 // convert to userspace
579 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
580 p1 *= bbox2user;
581 p2 *= bbox2user;
582 }
584 os << "<<\n/ShadingType 2\n/ColorSpace /DeviceRGB\n";
585 os << "/Coords [" << p1[NR::X] << " " << p1[NR::Y] << " " << p2[NR::X] << " " << p2[NR::Y] <<"]\n";
586 os << "/Extend [true true]\n";
587 os << "/Domain [0 1]\n";
588 os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
590 sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
591 for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
592 float rgb[3];
593 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
594 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
595 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
596 sp_color_get_rgb_floatv(&lg->vector.stops[i+1].color, rgb);
597 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
598 os << "/N 1\n>>\n";
599 }
600 os << "]\n/Domain [0 1]\n";
601 os << "/Bounds [ ";
602 for (unsigned i = 0; i + 2 < lg->vector.stops.size(); i++) {
603 os << lg->vector.stops[i+1].offset <<" ";
604 }
605 os << "]\n";
606 os << "/Encode [ ";
607 for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
608 os << "0 1 ";
609 }
610 os << "]\n";
611 os << ">>\n>>\n";
613 } else if (SP_IS_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style))) {
615 SPRadialGradient *rg = SP_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style));
616 NR::Point c(rg->cx.computed, rg->cy.computed);
617 NR::Point f(rg->fx.computed, rg->fy.computed);
618 double r = rg->r.computed;
619 if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
620 // convert to userspace
621 NR::Matrix const bbox2user(pbox->x1 - pbox->x0, 0,
622 0, pbox->y1 - pbox->y0,
623 pbox->x0, pbox->y0);
624 c *= bbox2user;
625 f *= bbox2user;
626 r *= bbox2user.expansion();
627 }
629 os << "<<\n/ShadingType 3\n/ColorSpace /DeviceRGB\n";
630 os << "/Coords ["<< f[NR::X] <<" "<< f[NR::Y] <<" 0 "<< c[NR::X] <<" "<< c[NR::Y] <<" "<< r <<"]\n";
631 os << "/Extend [true true]\n";
632 os << "/Domain [0 1]\n";
633 os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
635 sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
636 for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
637 float rgb[3];
638 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
639 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
640 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
641 sp_color_get_rgb_floatv(&rg->vector.stops[i+1].color, rgb);
642 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
643 os << "/N 1\n>>\n";
644 }
645 os << "]\n/Domain [0 1]\n";
646 os << "/Bounds [ ";
647 for (unsigned i = 0; i + 2 < rg->vector.stops.size(); i++) {
648 os << rg->vector.stops[i+1].offset << " ";
649 }
650 os << "]\n";
651 os << "/Encode [ ";
652 for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
653 os << "0 1 ";
654 }
655 os << "]\n";
656 os << ">>\n>>\n";
657 }
658 }
659 }
661 void
662 PrintPS::print_stroke_style(SVGOStringStream &os, SPStyle const *style)
663 {
664 float rgb[3];
665 sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
667 os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
669 // There are rare cases in which for a solid line stroke_dasharray_set is true. To avoid
670 // invalid PS-lines such as "[0.0000000 0.0000000] 0.0000000 setdash", which should be "[] 0 setdash",
671 // we first check if all components of stroke_dash.dash are 0.
672 bool LineSolid = true;
673 if (style->stroke_dash.n_dash &&
674 style->stroke_dash.dash )
675 {
676 int i = 0;
677 while (LineSolid && (i < style->stroke_dash.n_dash)) {
678 if (style->stroke_dash.dash[i] > 0.00000001)
679 LineSolid = false;
680 i++;
681 }
682 if (!LineSolid) {
683 os << "[";
684 for (i = 0; i < style->stroke_dash.n_dash; i++) {
685 if (i > 0) {
686 os << " ";
687 }
688 os << style->stroke_dash.dash[i];
689 }
690 os << "] " << style->stroke_dash.offset << " setdash\n";
691 } else {
692 os << "[] 0 setdash\n";
693 }
694 } else {
695 os << "[] 0 setdash\n";
696 }
698 os << style->stroke_width.computed << " setlinewidth\n";
699 os << style->stroke_linejoin.computed << " setlinejoin\n";
700 os << style->stroke_linecap.computed << " setlinecap\n";
701 }
704 unsigned int
705 PrintPS::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
706 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
707 {
708 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
709 if (_bitmap) return 0;
711 if ( style->fill.type == SP_PAINT_TYPE_COLOR
712 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
713 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
714 {
715 Inkscape::SVGOStringStream os;
717 os << "gsave\n";
719 print_fill_style(os, style, pbox);
721 print_bpath(os, bpath->path);
723 if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
724 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
725 os << "eofill\n";
726 } else {
727 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
728 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
729 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
730 os << "eoclip\n";
731 if (g->gradientTransform_set) {
732 os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
733 << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
734 << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
735 }
736 os << "shfill\n";
737 if (g->gradientTransform_set) {
738 os << "grestore\n";
739 }
740 }
741 } else {
742 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
743 os << "fill\n";
744 } else {
745 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
746 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
747 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
748 os << "clip\n";
749 if (g->gradientTransform_set) {
750 os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
751 << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
752 << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
753 }
754 os << "shfill\n";
755 if (g->gradientTransform_set) {
756 os << "grestore\n";
757 }
758 }
759 }
761 os << "grestore\n";
763 fprintf(_stream, "%s", os.str().c_str());
764 }
766 return 0;
767 }
770 unsigned int
771 PrintPS::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
772 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
773 {
774 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
775 if (_bitmap) return 0;
777 if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
778 Inkscape::SVGOStringStream os;
780 print_stroke_style(os, style);
782 print_bpath(os, bpath->path);
784 os << "stroke\n";
786 fprintf(_stream, "%s", os.str().c_str());
787 }
789 return 0;
790 }
792 unsigned int
793 PrintPS::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
794 NRMatrix const *transform, SPStyle const *style)
795 {
796 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
797 if (_bitmap) return 0;
799 return print_image(_stream, px, w, h, rs, transform);
800 }
802 char const *
803 PrintPS::PSFontName(SPStyle const *style)
804 {
805 font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
807 char const *n;
808 char name_buf[256];
810 if (tf) {
811 tf->PSName(name_buf, sizeof(name_buf));
812 n = name_buf;
813 tf->Unref();
814 } else {
815 // 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
816 bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
817 bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
818 bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
819 (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
821 n = g_strdup_printf("%s%s%s%s",
822 g_strdelimit(style->text->font_family.value, " ", '-'),
823 (b || i || o) ? "-" : "",
824 (b) ? "Bold" : "",
825 (i) ? "Italic" : ((o) ? "Oblique" : "") );
826 }
828 return g_strdup(n);
829 }
832 unsigned int
833 PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
834 SPStyle const *const style)
835 {
836 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
837 if (_bitmap) return 0;
839 Inkscape::SVGOStringStream os;
841 // Escape chars
842 Inkscape::SVGOStringStream escaped_text;
843 escaped_text << std::oct;
844 for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
845 gunichar const c = g_utf8_get_char(p_text);
846 if (c == '\\' || c == ')' || c == '(')
847 escaped_text << '\\' << static_cast<char>(c);
848 else if (c >= 0x80)
849 escaped_text << '\\' << c;
850 else
851 escaped_text << static_cast<char>(c);
852 }
854 os << "gsave\n";
856 // set font
857 char const *fn = PSFontName(style);
858 if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
859 if (!_newlatin1font_proc_defined) {
860 // input: newfontname, existingfontname
861 // output: new font object, also defined to newfontname
862 os << "/newlatin1font " // name of the proc
863 "{findfont dup length dict copy " // load the font and create a copy of it
864 "dup /Encoding ISOLatin1Encoding put " // change the encoding in the copy
865 "definefont} def\n"; // create the new font and leave it on the stack, define the proc
866 _newlatin1font_proc_defined = true;
867 }
868 os << "/(" << fn << "-ISOLatin1) /(" << fn << ") newlatin1font\n";
869 _latin1_encoded_fonts.insert(fn);
870 } else
871 os << "/(" << fn << "-ISOLatin1) findfont\n";
872 os << style->font_size.computed << " scalefont\n";
873 os << "setfont\n";
874 g_free((void *) fn);
876 if ( style->fill.type == SP_PAINT_TYPE_COLOR
877 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
878 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
879 {
880 // set fill style
881 print_fill_style(os, style, NULL);
882 // FIXME: we don't know the pbox of text, so have to pass NULL. This means gradients with
883 // bbox units won't work with text. However userspace gradients don't work with text either
884 // (text is black) for some reason.
886 os << "newpath\n";
887 os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
888 os << "(" << escaped_text.str() << ") show\n";
889 }
891 if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
893 // set stroke style
894 print_stroke_style(os, style);
896 // paint stroke
897 os << "newpath\n";
898 os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
899 os << "(" << escaped_text.str() << ") false charpath stroke\n";
900 }
902 os << "grestore\n";
904 fprintf(_stream, "%s", os.str().c_str());
906 return 0;
907 }
911 /* PostScript helpers */
913 void
914 PrintPS::print_bpath(SVGOStringStream &os, NArtBpath const *bp)
915 {
916 os << "newpath\n";
917 bool closed = false;
918 while (bp->code != NR_END) {
919 switch (bp->code) {
920 case NR_MOVETO:
921 if (closed) {
922 os << "closepath\n";
923 }
924 closed = true;
925 os << bp->x3 << " " << bp->y3 << " moveto\n";
926 break;
927 case NR_MOVETO_OPEN:
928 if (closed) {
929 os << "closepath\n";
930 }
931 closed = false;
932 os << bp->x3 << " " << bp->y3 << " moveto\n";
933 break;
934 case NR_LINETO:
935 os << bp->x3 << " " << bp->y3 << " lineto\n";
936 break;
937 case NR_CURVETO:
938 os << bp->x1 << " " << bp->y1 << " "
939 << bp->x2 << " " << bp->y2 << " "
940 << bp->x3 << " " << bp->y3 << " curveto\n";
941 break;
942 default:
943 break;
944 }
945 bp += 1;
946 }
947 if (closed) {
948 os << "closepath\n";
949 }
950 }
952 /* The following code is licensed under GNU GPL.
953 ** The packbits, ascii85 and imaging printing code
954 ** is from the gimp's postscript.c.
955 */
957 /**
958 * \param nin Number of bytes of source data.
959 * \param src Source data.
960 * \param nout Number of output bytes.
961 * \param dst Buffer for output.
962 */
963 void
964 PrintPS::compress_packbits(int nin,
965 guchar *src,
966 int *nout,
967 guchar *dst)
969 {
970 register guchar c;
971 int nrepeat, nliteral;
972 guchar *run_start;
973 guchar *start_dst = dst;
974 guchar *last_literal = NULL;
976 for (;;) {
977 if (nin <= 0) break;
979 run_start = src;
980 c = *run_start;
982 /* Search repeat bytes */
983 if ((nin > 1) && (c == src[1])) {
984 nrepeat = 1;
985 nin -= 2;
986 src += 2;
987 while ((nin > 0) && (c == *src)) {
988 nrepeat++;
989 src++;
990 nin--;
991 if (nrepeat == 127) break; /* Maximum repeat */
992 }
994 /* Add two-byte repeat to last literal run ? */
995 if ( (nrepeat == 1)
996 && (last_literal != NULL) && (((*last_literal)+1)+2 <= 128) )
997 {
998 *last_literal += 2;
999 *(dst++) = c;
1000 *(dst++) = c;
1001 continue;
1002 }
1004 /* Add repeat run */
1005 *(dst++) = (guchar)((-nrepeat) & 0xff);
1006 *(dst++) = c;
1007 last_literal = NULL;
1008 continue;
1009 }
1010 /* Search literal bytes */
1011 nliteral = 1;
1012 nin--;
1013 src++;
1015 for (;;) {
1016 if (nin <= 0) break;
1018 if ((nin >= 2) && (src[0] == src[1])) /* A two byte repeat ? */
1019 break;
1021 nliteral++;
1022 nin--;
1023 src++;
1024 if (nliteral == 128) break; /* Maximum literal run */
1025 }
1027 /* Could be added to last literal run ? */
1028 if ((last_literal != NULL) && (((*last_literal)+1)+nliteral <= 128)) {
1029 *last_literal += nliteral;
1030 } else {
1031 last_literal = dst;
1032 *(dst++) = (guchar)(nliteral-1);
1033 }
1034 while (nliteral-- > 0) *(dst++) = *(run_start++);
1035 }
1036 *nout = dst - start_dst;
1037 }
1039 void
1040 PrintPS::ascii85_init(void)
1041 {
1042 ascii85_len = 0;
1043 ascii85_linewidth = 0;
1044 }
1046 void
1047 PrintPS::ascii85_flush(SVGOStringStream &os)
1048 {
1049 char c[5];
1050 bool const zero_case = (ascii85_buf == 0);
1051 static int const max_linewidth = 75;
1053 for (int i = 4; i >= 0; i--) {
1054 c[i] = (ascii85_buf % 85) + '!';
1055 ascii85_buf /= 85;
1056 }
1057 /* check for special case: "!!!!!" becomes "z", but only if not
1058 * at end of data. */
1059 if (zero_case && (ascii85_len == 4)) {
1060 if (ascii85_linewidth >= max_linewidth) {
1061 os << '\n';
1062 ascii85_linewidth = 0;
1063 }
1064 os << 'z';
1065 ascii85_linewidth++;
1066 } else {
1067 for (int i = 0; i < ascii85_len+1; i++) {
1068 if ((ascii85_linewidth >= max_linewidth) && (c[i] != '%')) {
1069 os << '\n';
1070 ascii85_linewidth = 0;
1071 }
1072 os << c[i];
1073 ascii85_linewidth++;
1074 }
1075 }
1077 ascii85_len = 0;
1078 ascii85_buf = 0;
1079 }
1081 inline void
1082 PrintPS::ascii85_out(guchar byte, SVGOStringStream &os)
1083 {
1084 if (ascii85_len == 4)
1085 ascii85_flush(os);
1087 ascii85_buf <<= 8;
1088 ascii85_buf |= byte;
1089 ascii85_len++;
1090 }
1092 void
1093 PrintPS::ascii85_nout(int n, guchar *uptr, SVGOStringStream &os)
1094 {
1095 while (n-- > 0) {
1096 ascii85_out(*uptr, os);
1097 uptr++;
1098 }
1099 }
1101 void
1102 PrintPS::ascii85_done(SVGOStringStream &os)
1103 {
1104 if (ascii85_len) {
1105 /* zero any unfilled buffer portion, then flush */
1106 ascii85_buf <<= (8 * (4-ascii85_len));
1107 ascii85_flush(os);
1108 }
1110 os << "~>\n";
1111 }
1113 unsigned int
1114 PrintPS::print_image(FILE *ofp, guchar *px, unsigned int width, unsigned int height, unsigned int rs,
1115 NRMatrix const *transform)
1116 {
1117 Inkscape::SVGOStringStream os;
1119 os << "gsave\n";
1121 os << "[" << transform->c[0] << " "
1122 << transform->c[1] << " "
1123 << transform->c[2] << " "
1124 << transform->c[3] << " "
1125 << transform->c[4] << " "
1126 << transform->c[5] << "] concat\n";
1128 /* Write read image procedure */
1129 os << "<<\n";
1130 os << " /ImageType 3\n";
1131 os << " /InterleaveType 1\n";
1133 os << " /MaskDict\n";
1134 os << " <<\n";
1135 os << " /ImageType 1\n";
1136 os << " /Width " << width << "\n";
1137 os << " /Height " << height << "\n";
1138 os << " /ImageMatrix "
1139 << "[" << width << " "
1140 << 0 << " "
1141 << 0 << " "
1142 << -((long) height) << " "
1143 << 0 << " "
1144 << height << "]\n";
1145 os << " /BitsPerComponent 8\n";
1146 os << " /Decode [1 0]\n";
1147 os << " >>\n";
1149 os << " /DataDict\n";
1150 os << " <<\n";
1151 os << " /ImageType 1\n";
1152 os << " /Width " << width << "\n";
1153 os << " /Height " << height << "\n";
1154 os << " /ImageMatrix "
1155 << "[" << width << " "
1156 << 0 << " "
1157 << 0 << " "
1158 << -((long )height) << " "
1159 << 0 << " "
1160 << height << "]\n";
1161 os << " /DataSource currentfile /ASCII85Decode filter\n";
1162 os << " /BitsPerComponent 8\n";
1163 os << " /Decode [0 1 0 1 0 1]\n";
1164 os << " >>\n";
1166 os << ">>\n";
1168 /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
1169 guchar *const packb = (guchar *)g_malloc((4*width * 105)/100+2);
1170 guchar *const plane = (guchar *)g_malloc(4*width);
1172 os << "image\n";
1174 ascii85_init();
1176 for (unsigned i = 0; i < height; i++) {
1177 guchar const *const src = px + i * rs;
1179 guchar const *src_ptr = src;
1180 guchar *plane_ptr = plane;
1181 for (unsigned j = 0; j < width; j++) {
1182 *(plane_ptr++) = *(src_ptr+3);
1183 *(plane_ptr++) = *(src_ptr+0);
1184 *(plane_ptr++) = *(src_ptr+1);
1185 *(plane_ptr++) = *(src_ptr+2);
1186 src_ptr += 4;
1187 }
1189 ascii85_nout(4*width, plane, os);
1190 }
1191 ascii85_done(os);
1193 g_free(packb);
1194 g_free(plane);
1196 os << "grestore\n";
1198 fprintf(ofp, "%s", os.str().c_str());
1200 return 0;
1201 }
1203 bool
1204 PrintPS::textToPath(Inkscape::Extension::Print * ext)
1205 {
1206 return ext->get_param_bool("textToPath");
1207 }
1209 #include "clear-n_.h"
1211 void
1212 PrintPS::init(void)
1213 {
1214 /* SVG in */
1215 (void) Inkscape::Extension::build_from_mem(
1216 "<inkscape-extension>\n"
1217 "<name>" N_("Postscript Print") "</name>\n"
1218 "<id>" SP_MODULE_KEY_PRINT_PS "</id>\n"
1219 "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1220 "<param name=\"resolution\" type=\"string\">72</param>\n"
1221 "<param name=\"destination\" type=\"string\">| lp</param>\n"
1222 "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1223 "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1224 "<print/>\n"
1225 "</inkscape-extension>", new PrintPS());
1226 }
1229 } /* namespace Internal */
1230 } /* namespace Extension */
1231 } /* namespace Inkscape */
1233 /* End of GNU GPL code */
1236 /*
1237 Local Variables:
1238 mode:c++
1239 c-file-style:"stroustrup"
1240 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1241 indent-tabs-mode:nil
1242 fill-column:99
1243 End:
1244 */
1245 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :