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 } else {
389 os << "%%Orientation: Portrait\n";
390 os << "%%BoundingBox: " << (int) d.x0 << " "
391 << (int) d.y0 << " "
392 << (int) ceil(d.x1) << " "
393 << (int) ceil(d.y1) << "\n";
394 os << "%%HiResBoundingBox: " << d.x0 << " "
395 << d.y0 << " "
396 << d.x1 << " "
397 << d.y1 << "\n";
398 }
400 os << "%%EndComments\n";
401 // This will become problematic if we print multi paged documents:
402 os << "%%Page: 1 1\n";
404 if (pageLandscape) {
405 os << "90 rotate\n";
406 if (_bitmap) {
407 os << "0 " << (int) -ceil(_height) << " translate\n";
408 }
409 } else {
410 if (!_bitmap) {
411 os << "0 " << (int) ceil(_height) << " translate\n";
412 }
413 }
415 if (!_bitmap) {
416 os << PT_PER_PX << " " << -PT_PER_PX << " scale\n";
417 // from now on we can output px, but they will be treated as pt
418 }
419 }
421 /* FIXME: This function is declared to return unsigned, whereas fprintf returns a signed int *
422 * that can be zero if the first fprintf failed (os is empty) or "negative" (i.e. very positive
423 * in unsigned int interpretation) if the first fprintf failed but this one succeeds, or
424 * positive if both succeed. */
425 return fprintf(_stream, "%s", os.str().c_str());
426 }
428 unsigned int
429 PrintPS::finish(Inkscape::Extension::Print *mod)
430 {
431 if (!_stream) return 0;
433 if (_bitmap) {
434 double const dots_per_pt = _dpi / PT_PER_IN;
436 double const x0 = 0.0;
437 double const y0 = 0.0;
438 double const x1 = x0 + _width;
439 double const y1 = y0 + _height;
441 /* Bitmap width/height in bitmap dots. */
442 int const width = (int) (_width * dots_per_pt + 0.5);
443 int const height = (int) (_height * dots_per_pt + 0.5);
445 NRMatrix affine;
446 affine.c[0] = width / ((x1 - x0) * PX_PER_PT);
447 affine.c[1] = 0.0;
448 affine.c[2] = 0.0;
449 affine.c[3] = height / ((y1 - y0) * PX_PER_PT);
450 affine.c[4] = -affine.c[0] * x0;
451 affine.c[5] = -affine.c[3] * y0;
453 nr_arena_item_set_transform(mod->root, &affine);
455 guchar *const px = g_new(guchar, 4 * width * 64);
457 for (int y = 0; y < height; y += 64) {
458 /* Set area of interest. */
459 NRRectL bbox;
460 bbox.x0 = 0;
461 bbox.y0 = y;
462 bbox.x1 = width;
463 bbox.y1 = MIN(height, y + 64);
465 /* Update to renderable state. */
466 NRGC gc(NULL);
467 nr_matrix_set_identity(&gc.transform);
468 nr_arena_item_invoke_update(mod->root, &bbox, &gc, NR_ARENA_ITEM_STATE_ALL, NR_ARENA_ITEM_STATE_NONE);
469 /* Render */
470 /* This should take guchar* instead of unsigned char*) */
471 NRPixBlock pb;
472 nr_pixblock_setup_extern(&pb, NR_PIXBLOCK_MODE_R8G8B8A8N,
473 bbox.x0, bbox.y0, bbox.x1, bbox.y1,
474 (guchar*)px, 4 * width, FALSE, FALSE);
475 memset(px, 0xff, 4 * width * 64);
476 nr_arena_item_invoke_render(mod->root, &bbox, &pb, 0);
477 /* Blitter goes here */
478 NRMatrix imgt;
479 imgt.c[0] = (bbox.x1 - bbox.x0) / dots_per_pt;
480 imgt.c[1] = 0.0;
481 imgt.c[2] = 0.0;
482 imgt.c[3] = (bbox.y1 - bbox.y0) / dots_per_pt;
483 imgt.c[4] = 0.0;
484 imgt.c[5] = _height - y / dots_per_pt - (bbox.y1 - bbox.y0) / dots_per_pt;
486 print_image(_stream, px, bbox.x1 - bbox.x0, bbox.y1 - bbox.y0, 4 * width, &imgt);
487 }
489 g_free(px);
490 }
492 fprintf(_stream, "showpage\n");
493 int const res = fprintf(_stream, "%%%%EOF\n");
495 /* Flush stream to be sure. */
496 (void) fflush(_stream);
498 /* fixme: should really use pclose for popen'd streams */
499 fclose(_stream);
500 _stream = 0;
501 _latin1_encoded_fonts.clear();
503 return res;
504 }
506 unsigned int
507 PrintPS::bind(Inkscape::Extension::Print *mod, NRMatrix const *transform, float opacity)
508 {
509 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
510 if (_bitmap) return 0;
512 Inkscape::SVGOStringStream os;
513 os << "gsave [" << transform->c[0] << " "
514 << transform->c[1] << " "
515 << transform->c[2] << " "
516 << transform->c[3] << " "
517 << transform->c[4] << " "
518 << transform->c[5] << "] concat\n";
520 return fprintf(_stream, "%s", os.str().c_str());
521 }
523 unsigned int
524 PrintPS::release(Inkscape::Extension::Print *mod)
525 {
526 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
527 if (_bitmap) return 0;
529 return fprintf(_stream, "grestore\n");
530 }
532 unsigned int
533 PrintPS::comment(Inkscape::Extension::Print *mod, char const *comment)
534 {
535 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
536 if (_bitmap) return 0;
538 return fprintf(_stream, "%%! %s\n",comment);
539 }
541 void
542 PrintPS::print_fill_style(SVGOStringStream &os, SPStyle const *const style, NRRect const *pbox)
543 {
544 g_return_if_fail( style->fill.type == SP_PAINT_TYPE_COLOR
545 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
546 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) );
548 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
549 float rgb[3];
550 sp_color_get_rgb_floatv(&style->fill.value.color, rgb);
552 os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
554 } else {
555 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
556 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
558 if (SP_IS_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style))) {
560 SPLinearGradient *lg = SP_LINEARGRADIENT(SP_STYLE_FILL_SERVER(style));
561 NR::Point p1 (lg->x1.computed, lg->y1.computed);
562 NR::Point p2 (lg->x2.computed, lg->y2.computed);
563 if (pbox && SP_GRADIENT(lg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
564 // convert to userspace
565 NR::Matrix bbox2user(pbox->x1 - pbox->x0, 0, 0, pbox->y1 - pbox->y0, pbox->x0, pbox->y0);
566 p1 *= bbox2user;
567 p2 *= bbox2user;
568 }
570 os << "<<\n/ShadingType 2\n/ColorSpace /DeviceRGB\n";
571 os << "/Coords [" << p1[NR::X] << " " << p1[NR::Y] << " " << p2[NR::X] << " " << p2[NR::Y] <<"]\n";
572 os << "/Extend [true true]\n";
573 os << "/Domain [0 1]\n";
574 os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
576 sp_gradient_ensure_vector(SP_GRADIENT(lg)); // when exporting from commandline, vector is not built
577 for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
578 float rgb[3];
579 sp_color_get_rgb_floatv(&lg->vector.stops[i].color, rgb);
580 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
581 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
582 sp_color_get_rgb_floatv(&lg->vector.stops[i+1].color, rgb);
583 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
584 os << "/N 1\n>>\n";
585 }
586 os << "]\n/Domain [0 1]\n";
587 os << "/Bounds [ ";
588 for (unsigned i = 0; i + 2 < lg->vector.stops.size(); i++) {
589 os << lg->vector.stops[i+1].offset <<" ";
590 }
591 os << "]\n";
592 os << "/Encode [ ";
593 for (unsigned i = 0; i + 1 < lg->vector.stops.size(); i++) {
594 os << "0 1 ";
595 }
596 os << "]\n";
597 os << ">>\n>>\n";
599 } else if (SP_IS_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style))) {
601 SPRadialGradient *rg = SP_RADIALGRADIENT(SP_STYLE_FILL_SERVER(style));
602 NR::Point c(rg->cx.computed, rg->cy.computed);
603 NR::Point f(rg->fx.computed, rg->fy.computed);
604 double r = rg->r.computed;
605 if (pbox && SP_GRADIENT(rg)->units == SP_GRADIENT_UNITS_OBJECTBOUNDINGBOX) {
606 // convert to userspace
607 NR::Matrix const bbox2user(pbox->x1 - pbox->x0, 0,
608 0, pbox->y1 - pbox->y0,
609 pbox->x0, pbox->y0);
610 c *= bbox2user;
611 f *= bbox2user;
612 r *= bbox2user.expansion();
613 }
615 os << "<<\n/ShadingType 3\n/ColorSpace /DeviceRGB\n";
616 os << "/Coords ["<< f[NR::X] <<" "<< f[NR::Y] <<" 0 "<< c[NR::X] <<" "<< c[NR::Y] <<" "<< r <<"]\n";
617 os << "/Extend [true true]\n";
618 os << "/Domain [0 1]\n";
619 os << "/Function <<\n/FunctionType 3\n/Functions\n[\n";
621 sp_gradient_ensure_vector(SP_GRADIENT(rg)); // when exporting from commandline, vector is not built
622 for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
623 float rgb[3];
624 sp_color_get_rgb_floatv(&rg->vector.stops[i].color, rgb);
625 os << "<<\n/FunctionType 2\n/Domain [0 1]\n";
626 os << "/C0 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
627 sp_color_get_rgb_floatv(&rg->vector.stops[i+1].color, rgb);
628 os << "/C1 [" << rgb[0] << " " << rgb[1] << " " << rgb[2] << "]\n";
629 os << "/N 1\n>>\n";
630 }
631 os << "]\n/Domain [0 1]\n";
632 os << "/Bounds [ ";
633 for (unsigned i = 0; i + 2 < rg->vector.stops.size(); i++) {
634 os << rg->vector.stops[i+1].offset << " ";
635 }
636 os << "]\n";
637 os << "/Encode [ ";
638 for (unsigned i = 0; i + 1 < rg->vector.stops.size(); i++) {
639 os << "0 1 ";
640 }
641 os << "]\n";
642 os << ">>\n>>\n";
643 }
644 }
645 }
647 void
648 PrintPS::print_stroke_style(SVGOStringStream &os, SPStyle const *style)
649 {
650 float rgb[3];
651 sp_color_get_rgb_floatv(&style->stroke.value.color, rgb);
653 os << rgb[0] << " " << rgb[1] << " " << rgb[2] << " setrgbcolor\n";
655 // There are rare cases in which for a solid line stroke_dasharray_set is true. To avoid
656 // invalid PS-lines such as "[0.0000000 0.0000000] 0.0000000 setdash", which should be "[] 0 setdash",
657 // we first check if all components of stroke_dash.dash are 0.
658 bool LineSolid = true;
659 if (style->stroke_dasharray_set &&
660 style->stroke_dash.n_dash &&
661 style->stroke_dash.dash )
662 {
663 int i = 0;
664 while (LineSolid && (i < style->stroke_dash.n_dash)) {
665 if (style->stroke_dash.dash[i] > 0.00000001)
666 LineSolid = false;
667 i++;
668 }
669 if (!LineSolid) {
670 os << "[";
671 for (i = 0; i < style->stroke_dash.n_dash; i++) {
672 if (i > 0) {
673 os << " ";
674 }
675 os << style->stroke_dash.dash[i];
676 }
677 os << "] " << style->stroke_dash.offset << " setdash\n";
678 } else {
679 os << "[] 0 setdash\n";
680 }
681 } else {
682 os << "[] 0 setdash\n";
683 }
685 os << style->stroke_width.computed << " setlinewidth\n";
686 os << style->stroke_linejoin.computed << " setlinejoin\n";
687 os << style->stroke_linecap.computed << " setlinecap\n";
688 }
691 unsigned int
692 PrintPS::fill(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *const style,
693 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
694 {
695 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
696 if (_bitmap) return 0;
698 if ( style->fill.type == SP_PAINT_TYPE_COLOR
699 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
700 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
701 {
702 Inkscape::SVGOStringStream os;
704 os << "gsave\n";
706 print_fill_style(os, style, pbox);
708 print_bpath(os, bpath->path);
710 if (style->fill_rule.value == SP_WIND_RULE_EVENODD) {
711 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
712 os << "eofill\n";
713 } else {
714 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
715 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
716 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
717 os << "eoclip\n";
718 if (g->gradientTransform_set) {
719 os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
720 << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
721 << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
722 }
723 os << "shfill\n";
724 if (g->gradientTransform_set) {
725 os << "grestore\n";
726 }
727 }
728 } else {
729 if (style->fill.type == SP_PAINT_TYPE_COLOR) {
730 os << "fill\n";
731 } else {
732 g_assert( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
733 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) );
734 SPGradient const *g = SP_GRADIENT(SP_STYLE_FILL_SERVER(style));
735 os << "clip\n";
736 if (g->gradientTransform_set) {
737 os << "gsave [" << g->gradientTransform[0] << " " << g->gradientTransform[1]
738 << " " << g->gradientTransform[2] << " " << g->gradientTransform[3]
739 << " " << g->gradientTransform[4] << " " << g->gradientTransform[5] << "] concat\n";
740 }
741 os << "shfill\n";
742 if (g->gradientTransform_set) {
743 os << "grestore\n";
744 }
745 }
746 }
748 os << "grestore\n";
750 fprintf(_stream, "%s", os.str().c_str());
751 }
753 return 0;
754 }
757 unsigned int
758 PrintPS::stroke(Inkscape::Extension::Print *mod, NRBPath const *bpath, NRMatrix const *ctm, SPStyle const *style,
759 NRRect const *pbox, NRRect const *dbox, NRRect const *bbox)
760 {
761 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
762 if (_bitmap) return 0;
764 if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
765 Inkscape::SVGOStringStream os;
767 print_stroke_style(os, style);
769 print_bpath(os, bpath->path);
771 os << "stroke\n";
773 fprintf(_stream, "%s", os.str().c_str());
774 }
776 return 0;
777 }
779 unsigned int
780 PrintPS::image(Inkscape::Extension::Print *mod, guchar *px, unsigned int w, unsigned int h, unsigned int rs,
781 NRMatrix const *transform, SPStyle const *style)
782 {
783 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
784 if (_bitmap) return 0;
786 return print_image(_stream, px, w, h, rs, transform);
787 #if 0
788 fprintf(_stream, "gsave\n");
789 fprintf(_stream, "/rowdata %d string def\n", 3 * w);
790 fprintf(_stream, "[%g %g %g %g %g %g] concat\n",
791 transform->c[0],
792 transform->c[1],
793 transform->c[2],
794 transform->c[3],
795 transform->c[4],
796 transform->c[5]);
797 fprintf(_stream, "%d %d 8 [%d 0 0 -%d 0 %d]\n", w, h, w, h, h);
798 fprintf(_stream, "{currentfile rowdata readhexstring pop}\n");
799 fprintf(_stream, "false 3 colorimage\n");
801 for (unsigned int r = 0; r < h; r++) {
802 guchar *s;
803 unsigned int c0, c1, c;
804 s = px + r * rs;
805 for (c0 = 0; c0 < w; c0 += 24) {
806 c1 = MIN(w, c0 + 24);
807 for (c = c0; c < c1; c++) {
808 static char const xtab[] = {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
809 fputc(xtab[s[0] >> 4], _stream);
810 fputc(xtab[s[0] & 0xf], _stream);
811 fputc(xtab[s[1] >> 4], _stream);
812 fputc(xtab[s[1] & 0xf], _stream);
813 fputc(xtab[s[2] >> 4], _stream);
814 fputc(xtab[s[2] & 0xf], _stream);
815 s += 4;
816 }
817 fputs("\n", _stream);
818 }
819 }
821 fprintf(_stream, "grestore\n");
823 return 0;
824 #endif
825 }
827 char const *
828 PrintPS::PSFontName(SPStyle const *style)
829 {
830 font_instance *tf = (font_factory::Default())->Face(style->text->font_family.value, font_style_to_pos(*style));
832 char const *n;
833 char name_buf[256];
835 if (tf) {
836 tf->PSName(name_buf, sizeof(name_buf));
837 n = name_buf;
838 tf->Unref();
839 } else {
840 // 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
841 bool i = (style->font_style.value == SP_CSS_FONT_STYLE_ITALIC);
842 bool o = (style->font_style.value == SP_CSS_FONT_STYLE_OBLIQUE);
843 bool b = (style->font_weight.value == SP_CSS_FONT_WEIGHT_BOLD) ||
844 (style->font_weight.value >= SP_CSS_FONT_WEIGHT_500 && style->font_weight.value <= SP_CSS_FONT_WEIGHT_900);
846 n = g_strdup_printf("%s%s%s%s",
847 g_strdelimit(style->text->font_family.value, " ", '-'),
848 (b || i || o) ? "-" : "",
849 (b) ? "Bold" : "",
850 (i) ? "Italic" : ((o) ? "Oblique" : "") );
851 }
853 return g_strdup(n);
854 }
857 unsigned int
858 PrintPS::text(Inkscape::Extension::Print *mod, char const *text, NR::Point p,
859 SPStyle const *const style)
860 {
861 if (!_stream) return 0; // XXX: fixme, returning -1 as unsigned.
862 if (_bitmap) return 0;
864 Inkscape::SVGOStringStream os;
866 // Escape chars
867 Inkscape::SVGOStringStream escaped_text;
868 escaped_text << std::oct;
869 for (gchar const *p_text = text ; *p_text ; p_text = g_utf8_next_char(p_text)) {
870 gunichar const c = g_utf8_get_char(p_text);
871 if (c == '\\' || c == ')' || c == '(')
872 escaped_text << '\\' << static_cast<char>(c);
873 else if (c >= 0x80)
874 escaped_text << '\\' << c;
875 else
876 escaped_text << static_cast<char>(c);
877 }
879 os << "gsave\n";
881 // set font
882 char const *fn = PSFontName(style);
883 if (_latin1_encoded_fonts.find(fn) == _latin1_encoded_fonts.end()) {
884 if (!_newlatin1font_proc_defined) {
885 // input: newfontname, existingfontname
886 // output: new font object, also defined to newfontname
887 os << "/newlatin1font " // name of the proc
888 "{findfont dup length dict copy " // load the font and create a copy of it
889 "dup /Encoding ISOLatin1Encoding put " // change the encoding in the copy
890 "definefont} def\n"; // create the new font and leave it on the stack, define the proc
891 _newlatin1font_proc_defined = true;
892 }
893 os << "/" << fn << "-ISOLatin1 /" << fn << " newlatin1font\n";
894 _latin1_encoded_fonts.insert(fn);
895 } else
896 os << "/" << fn << "-ISOLatin1 findfont\n";
897 os << style->font_size.computed << " scalefont\n";
898 os << "setfont\n";
899 g_free((void *) fn);
901 if ( style->fill.type == SP_PAINT_TYPE_COLOR
902 || ( style->fill.type == SP_PAINT_TYPE_PAINTSERVER
903 && SP_IS_GRADIENT(SP_STYLE_FILL_SERVER(style)) ) )
904 {
905 // set fill style
906 print_fill_style(os, style, NULL);
907 // FIXME: we don't know the pbox of text, so have to pass NULL. This means gradients with
908 // bbox units won't work with text. However userspace gradients don't work with text either
909 // (text is black) for some reason.
911 os << "newpath\n";
912 os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
913 os << "(" << escaped_text.str() << ") show\n";
914 }
916 if (style->stroke.type == SP_PAINT_TYPE_COLOR) {
918 // set stroke style
919 print_stroke_style(os, style);
921 // paint stroke
922 os << "newpath\n";
923 os << p[NR::X] << " " << p[NR::Y] << " moveto\n";
924 os << "(" << escaped_text.str() << ") false charpath stroke\n";
925 }
927 os << "grestore\n";
929 fprintf(_stream, "%s", os.str().c_str());
931 return 0;
932 }
936 /* PostScript helpers */
938 void
939 PrintPS::print_bpath(SVGOStringStream &os, NArtBpath const *bp)
940 {
941 os << "newpath\n";
942 bool closed = false;
943 while (bp->code != NR_END) {
944 switch (bp->code) {
945 case NR_MOVETO:
946 if (closed) {
947 os << "closepath\n";
948 }
949 closed = true;
950 os << bp->x3 << " " << bp->y3 << " moveto\n";
951 break;
952 case NR_MOVETO_OPEN:
953 if (closed) {
954 os << "closepath\n";
955 }
956 closed = false;
957 os << bp->x3 << " " << bp->y3 << " moveto\n";
958 break;
959 case NR_LINETO:
960 os << bp->x3 << " " << bp->y3 << " lineto\n";
961 break;
962 case NR_CURVETO:
963 os << bp->x1 << " " << bp->y1 << " "
964 << bp->x2 << " " << bp->y2 << " "
965 << bp->x3 << " " << bp->y3 << " curveto\n";
966 break;
967 default:
968 break;
969 }
970 bp += 1;
971 }
972 if (closed) {
973 os << "closepath\n";
974 }
975 }
977 /* The following code is licensed under GNU GPL.
978 ** The packbits, ascii85 and imaging printing code
979 ** is from the gimp's postscript.c.
980 */
982 /**
983 * \param nin Number of bytes of source data.
984 * \param src Source data.
985 * \param nout Number of output bytes.
986 * \param dst Buffer for output.
987 */
988 void
989 PrintPS::compress_packbits(int nin,
990 guchar *src,
991 int *nout,
992 guchar *dst)
994 {
995 register guchar c;
996 int nrepeat, nliteral;
997 guchar *run_start;
998 guchar *start_dst = dst;
999 guchar *last_literal = NULL;
1001 for (;;) {
1002 if (nin <= 0) break;
1004 run_start = src;
1005 c = *run_start;
1007 /* Search repeat bytes */
1008 if ((nin > 1) && (c == src[1])) {
1009 nrepeat = 1;
1010 nin -= 2;
1011 src += 2;
1012 while ((nin > 0) && (c == *src)) {
1013 nrepeat++;
1014 src++;
1015 nin--;
1016 if (nrepeat == 127) break; /* Maximum repeat */
1017 }
1019 /* Add two-byte repeat to last literal run ? */
1020 if ( (nrepeat == 1)
1021 && (last_literal != NULL) && (((*last_literal)+1)+2 <= 128) )
1022 {
1023 *last_literal += 2;
1024 *(dst++) = c;
1025 *(dst++) = c;
1026 continue;
1027 }
1029 /* Add repeat run */
1030 *(dst++) = (guchar)((-nrepeat) & 0xff);
1031 *(dst++) = c;
1032 last_literal = NULL;
1033 continue;
1034 }
1035 /* Search literal bytes */
1036 nliteral = 1;
1037 nin--;
1038 src++;
1040 for (;;) {
1041 if (nin <= 0) break;
1043 if ((nin >= 2) && (src[0] == src[1])) /* A two byte repeat ? */
1044 break;
1046 nliteral++;
1047 nin--;
1048 src++;
1049 if (nliteral == 128) break; /* Maximum literal run */
1050 }
1052 /* Could be added to last literal run ? */
1053 if ((last_literal != NULL) && (((*last_literal)+1)+nliteral <= 128)) {
1054 *last_literal += nliteral;
1055 } else {
1056 last_literal = dst;
1057 *(dst++) = (guchar)(nliteral-1);
1058 }
1059 while (nliteral-- > 0) *(dst++) = *(run_start++);
1060 }
1061 *nout = dst - start_dst;
1062 }
1064 void
1065 PrintPS::ascii85_init(void)
1066 {
1067 ascii85_len = 0;
1068 ascii85_linewidth = 0;
1069 }
1071 void
1072 PrintPS::ascii85_flush(SVGOStringStream &os)
1073 {
1074 char c[5];
1075 bool const zero_case = (ascii85_buf == 0);
1076 static int const max_linewidth = 75;
1078 for (int i = 4; i >= 0; i--) {
1079 c[i] = (ascii85_buf % 85) + '!';
1080 ascii85_buf /= 85;
1081 }
1082 /* check for special case: "!!!!!" becomes "z", but only if not
1083 * at end of data. */
1084 if (zero_case && (ascii85_len == 4)) {
1085 if (ascii85_linewidth >= max_linewidth) {
1086 os << '\n';
1087 ascii85_linewidth = 0;
1088 }
1089 os << 'z';
1090 ascii85_linewidth++;
1091 } else {
1092 for (int i = 0; i < ascii85_len+1; i++) {
1093 if ((ascii85_linewidth >= max_linewidth) && (c[i] != '%')) {
1094 os << '\n';
1095 ascii85_linewidth = 0;
1096 }
1097 os << c[i];
1098 ascii85_linewidth++;
1099 }
1100 }
1102 ascii85_len = 0;
1103 ascii85_buf = 0;
1104 }
1106 inline void
1107 PrintPS::ascii85_out(guchar byte, SVGOStringStream &os)
1108 {
1109 if (ascii85_len == 4)
1110 ascii85_flush(os);
1112 ascii85_buf <<= 8;
1113 ascii85_buf |= byte;
1114 ascii85_len++;
1115 }
1117 void
1118 PrintPS::ascii85_nout(int n, guchar *uptr, SVGOStringStream &os)
1119 {
1120 while (n-- > 0) {
1121 ascii85_out(*uptr, os);
1122 uptr++;
1123 }
1124 }
1126 void
1127 PrintPS::ascii85_done(SVGOStringStream &os)
1128 {
1129 if (ascii85_len) {
1130 /* zero any unfilled buffer portion, then flush */
1131 ascii85_buf <<= (8 * (4-ascii85_len));
1132 ascii85_flush(os);
1133 }
1135 os << "~>\n";
1136 }
1138 unsigned int
1139 PrintPS::print_image(FILE *ofp, guchar *px, unsigned int width, unsigned int height, unsigned int rs,
1140 NRMatrix const *transform)
1141 {
1142 Inkscape::SVGOStringStream os;
1144 os << "gsave\n";
1145 os << "[" << transform->c[0] << " "
1146 << transform->c[1] << " "
1147 << transform->c[2] << " "
1148 << transform->c[3] << " "
1149 << transform->c[4] << " "
1150 << transform->c[5] << "] concat\n";
1151 os << width << " " << height << " 8 ["
1152 << width << " 0 0 -" << height << " 0 " << height << "]\n";
1155 /* Write read image procedure */
1156 os << "% Strings to hold RGB-samples per scanline\n";
1157 os << "/rstr " << width << " string def\n";
1158 os << "/gstr " << width << " string def\n";
1159 os << "/bstr " << width << " string def\n";
1160 os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter rstr readstring pop}\n";
1161 os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter gstr readstring pop}\n";
1162 os << "{currentfile /ASCII85Decode filter /RunLengthDecode filter bstr readstring pop}\n";
1163 os << "true 3\n";
1165 /* Allocate buffer for packbits data. Worst case: Less than 1% increase */
1166 guchar *const packb = (guchar *)g_malloc((width * 105)/100+2);
1167 guchar *const plane = (guchar *)g_malloc(width);
1169 /* ps_begin_data(ofp); */
1170 os << "colorimage\n";
1172 /*#define GET_RGB_TILE(begin) \
1173 * {int scan_lines; \
1174 * scan_lines = (i+tile_height-1 < height) ? tile_height : (height-i); \
1175 * gimp_pixel_rgn_get_rect(&pixel_rgn, begin, 0, i, width, scan_lines); \
1176 * src = begin; }
1177 */
1179 for (unsigned i = 0; i < height; i++) {
1180 /* if ((i % tile_height) == 0) GET_RGB_TILE(data); */ /* Get more data */
1181 guchar const *const src = px + i * rs;
1183 /* Iterate over RGB */
1184 for (int rgb = 0; rgb < 3; rgb++) {
1185 guchar const *src_ptr = src + rgb;
1186 guchar *plane_ptr = plane;
1187 for (unsigned j = 0; j < width; j++) {
1188 *(plane_ptr++) = *src_ptr;
1189 src_ptr += 4;
1190 }
1192 int nout;
1193 compress_packbits(width, plane, &nout, packb);
1195 ascii85_init();
1196 ascii85_nout(nout, packb, os);
1197 ascii85_out(128, os); /* Write EOD of RunLengthDecode filter */
1198 ascii85_done(os);
1199 }
1200 }
1201 /* ps_end_data(ofp); */
1203 #if 0
1204 fprintf(ofp, "showpage\n");
1205 g_free(data);
1206 #endif
1208 g_free(packb);
1209 g_free(plane);
1211 #if 0
1212 if (ferror(ofp)) {
1213 g_message(_("write error occurred"));
1214 return (FALSE);
1215 }
1216 #endif
1218 os << "grestore\n";
1220 fprintf(ofp, "%s", os.str().c_str());
1222 return 0;
1223 //#undef GET_RGB_TILE
1224 }
1226 bool
1227 PrintPS::textToPath(Inkscape::Extension::Print * ext)
1228 {
1229 return ext->get_param_bool("textToPath");
1230 }
1232 #include "clear-n_.h"
1234 void
1235 PrintPS::init(void)
1236 {
1237 /* SVG in */
1238 (void) Inkscape::Extension::build_from_mem(
1239 "<inkscape-extension>\n"
1240 "<name>" N_("Postscript Print") "</name>\n"
1241 "<id>" SP_MODULE_KEY_PRINT_PS "</id>\n"
1242 "<param name=\"bitmap\" type=\"boolean\">FALSE</param>\n"
1243 "<param name=\"resolution\" type=\"string\">72</param>\n"
1244 "<param name=\"destination\" type=\"string\">| lp</param>\n"
1245 "<param name=\"pageBoundingBox\" type=\"boolean\">TRUE</param>\n"
1246 "<param name=\"textToPath\" type=\"boolean\">TRUE</param>\n"
1247 "<print/>\n"
1248 "</inkscape-extension>", new PrintPS());
1249 }
1252 } /* namespace Internal */
1253 } /* namespace Extension */
1254 } /* namespace Inkscape */
1256 /* End of GNU GPL code */
1259 /*
1260 Local Variables:
1261 mode:c++
1262 c-file-style:"stroustrup"
1263 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
1264 indent-tabs-mode:nil
1265 fill-column:99
1266 End:
1267 */
1268 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :