1 /** \file
2 * Native PDF import using libpoppler.
3 *
4 * Authors:
5 * miklos erdelyi
6 *
7 * Copyright (C) 2007 Authors
8 *
9 * Released under GNU GPL, read the file 'COPYING' for more information
10 *
11 */
13 #ifdef HAVE_CONFIG_H
14 # include <config.h>
15 #endif
17 #ifdef HAVE_POPPLER
19 #include "svg-builder.h"
20 #include "pdf-parser.h"
22 #include <png.h>
24 #include "document-private.h"
25 #include "xml/document.h"
26 #include "xml/node.h"
27 #include "xml/repr.h"
28 #include "svg/svg.h"
29 #include "svg/path-string.h"
30 #include "svg/css-ostringstream.h"
31 #include "svg/svg-color.h"
32 #include "color.h"
33 #include "unit-constants.h"
34 #include "io/stringstream.h"
35 #include "io/base64stream.h"
36 #include "display/nr-filter-utils.h"
37 #include "libnr/nr-matrix-ops.h"
38 #include "libnr/nr-macros.h"
39 #include "libnrtype/font-instance.h"
41 #include "Function.h"
42 #include "GfxState.h"
43 #include "GfxFont.h"
44 #include "Stream.h"
45 #include "Page.h"
46 #include "UnicodeMap.h"
47 #include "GlobalParams.h"
49 namespace Inkscape {
50 namespace Extension {
51 namespace Internal {
53 //#define IFTRACE(_code) _code
54 #define IFTRACE(_code)
56 #define TRACE(_args) IFTRACE(g_print _args)
59 /**
60 * \struct SvgTransparencyGroup
61 * \brief Holds information about a PDF transparency group
62 */
63 struct SvgTransparencyGroup {
64 double bbox[6];
65 Inkscape::XML::Node *container;
67 bool isolated;
68 bool knockout;
69 bool for_softmask;
71 SvgTransparencyGroup *next;
72 };
74 /**
75 * \class SvgBuilder
76 *
77 */
79 SvgBuilder::SvgBuilder(SPDocument *document, gchar *docname, XRef *xref) {
80 _is_top_level = true;
81 _doc = document;
82 _docname = docname;
83 _xref = xref;
84 _xml_doc = sp_document_repr_doc(_doc);
85 _container = _root = _doc->rroot;
86 _root->setAttribute("xml:space", "preserve");
87 _init();
89 // Set default preference settings
90 _preferences = _xml_doc->createElement("svgbuilder:prefs");
91 _preferences->setAttribute("embedImages", "1");
92 }
94 SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) {
95 _is_top_level = false;
96 _doc = parent->_doc;
97 _docname = parent->_docname;
98 _xref = parent->_xref;
99 _xml_doc = parent->_xml_doc;
100 _preferences = parent->_preferences;
101 _container = this->_root = root;
102 _init();
103 }
105 SvgBuilder::~SvgBuilder() {
106 }
108 void SvgBuilder::_init() {
109 _in_text_object = false;
110 _need_font_update = true;
111 _invalidated_style = true;
112 _font_style = NULL;
113 _current_font = NULL;
114 _current_state = NULL;
116 _transp_group_stack = NULL;
117 SvgGraphicsState initial_state;
118 initial_state.softmask = NULL;
119 initial_state.group_depth = 0;
120 _state_stack.push_back(initial_state);
121 _node_stack.push_back(_container);
122 }
124 void SvgBuilder::setDocumentSize(double width, double height) {
125 sp_repr_set_svg_double(_root, "width", width);
126 sp_repr_set_svg_double(_root, "height", height);
127 this->_width = width;
128 this->_height = height;
129 }
131 /**
132 * \brief Sets groupmode of the current container to 'layer' and sets its label if given
133 */
134 void SvgBuilder::setAsLayer(char *layer_name) {
135 _container->setAttribute("inkscape:groupmode", "layer");
136 if (layer_name) {
137 _container->setAttribute("inkscape:label", layer_name);
138 }
139 }
141 /**
142 * \brief Sets the current container's opacity
143 */
144 void SvgBuilder::setGroupOpacity(double opacity) {
145 sp_repr_set_svg_double(_container, "opacity", CLAMP(opacity, 0.0, 1.0));
146 }
148 void SvgBuilder::saveState() {
149 SvgGraphicsState new_state;
150 new_state.group_depth = 0;
151 new_state.softmask = _state_stack.back().softmask;
152 _state_stack.push_back(new_state);
153 pushGroup();
154 }
156 void SvgBuilder::restoreState() {
157 while( _state_stack.back().group_depth > 0 ) {
158 popGroup();
159 }
160 _state_stack.pop_back();
161 }
163 Inkscape::XML::Node *SvgBuilder::pushNode(const char *name) {
164 Inkscape::XML::Node *node = _xml_doc->createElement(name);
165 _node_stack.push_back(node);
166 _container = node;
167 return node;
168 }
170 Inkscape::XML::Node *SvgBuilder::popNode() {
171 Inkscape::XML::Node *node = NULL;
172 if ( _node_stack.size() > 1 ) {
173 node = _node_stack.back();
174 _node_stack.pop_back();
175 _container = _node_stack.back(); // Re-set container
176 } else {
177 TRACE(("popNode() called when stack is empty\n"));
178 node = _root;
179 }
180 return node;
181 }
183 Inkscape::XML::Node *SvgBuilder::pushGroup() {
184 Inkscape::XML::Node *saved_container = _container;
185 Inkscape::XML::Node *node = pushNode("svg:g");
186 saved_container->appendChild(node);
187 Inkscape::GC::release(node);
188 _state_stack.back().group_depth++;
189 // Set as a layer if this is a top-level group
190 if ( _container->parent() == _root && _is_top_level ) {
191 static int layer_count = 1;
192 if ( layer_count > 1 ) {
193 gchar *layer_name = g_strdup_printf("%s%d", _docname, layer_count);
194 setAsLayer(layer_name);
195 g_free(layer_name);
196 } else {
197 setAsLayer(_docname);
198 }
199 }
201 return _container;
202 }
204 Inkscape::XML::Node *SvgBuilder::popGroup() {
205 if (_container != _root) { // Pop if the current container isn't root
206 popNode();
207 _state_stack.back().group_depth--;
208 }
210 return _container;
211 }
213 Inkscape::XML::Node *SvgBuilder::getContainer() {
214 return _container;
215 }
217 static gchar *svgConvertRGBToText(double r, double g, double b) {
218 static gchar tmp[1023] = {0};
219 snprintf(tmp, 1023,
220 "#%02x%02x%02x",
221 NR::clamp(SP_COLOR_F_TO_U(r)),
222 NR::clamp(SP_COLOR_F_TO_U(g)),
223 NR::clamp(SP_COLOR_F_TO_U(b)));
224 return (gchar *)&tmp;
225 }
227 static gchar *svgConvertGfxRGB(GfxRGB *color) {
228 double r = (double)color->r / 65535.0;
229 double g = (double)color->g / 65535.0;
230 double b = (double)color->b / 65535.0;
231 return svgConvertRGBToText(r, g, b);
232 }
234 static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1,
235 double c2, double c3, double c4, double c5) {
236 NR::Matrix matrix(c0, c1, c2, c3, c4, c5);
237 gchar *transform_text = sp_svg_transform_write(matrix);
238 node->setAttribute("transform", transform_text);
239 g_free(transform_text);
240 }
242 /**
243 * \brief Generates a SVG path string from poppler's data structure
244 */
245 static gchar *svgInterpretPath(GfxPath *path) {
246 GfxSubpath *subpath;
247 Inkscape::SVG::PathString pathString;
248 int i, j;
249 for ( i = 0 ; i < path->getNumSubpaths() ; ++i ) {
250 subpath = path->getSubpath(i);
251 if (subpath->getNumPoints() > 0) {
252 pathString.moveTo(subpath->getX(0), subpath->getY(0));
253 j = 1;
254 while (j < subpath->getNumPoints()) {
255 if (subpath->getCurve(j)) {
256 pathString.curveTo(subpath->getX(j), subpath->getY(j),
257 subpath->getX(j+1), subpath->getY(j+1),
258 subpath->getX(j+2), subpath->getY(j+2));
260 j += 3;
261 } else {
262 pathString.lineTo(subpath->getX(j), subpath->getY(j));
263 ++j;
264 }
265 }
266 if (subpath->isClosed()) {
267 pathString.closePath();
268 }
269 }
270 }
272 return g_strdup(pathString.c_str());
273 }
275 /**
276 * \brief Sets stroke style from poppler's GfxState data structure
277 * Uses the given SPCSSAttr for storing the style properties
278 */
279 void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) {
281 // Check line width
282 if ( state->getLineWidth() <= 0.0 ) {
283 // Ignore stroke
284 sp_repr_css_set_property(css, "stroke", "none");
285 return;
286 }
288 // Stroke color/pattern
289 if ( state->getStrokeColorSpace()->getMode() == csPattern ) {
290 gchar *urltext = _createPattern(state->getStrokePattern(), state, true);
291 sp_repr_css_set_property(css, "stroke", urltext);
292 if (urltext) {
293 g_free(urltext);
294 }
295 } else {
296 GfxRGB stroke_color;
297 state->getStrokeRGB(&stroke_color);
298 sp_repr_css_set_property(css, "stroke", svgConvertGfxRGB(&stroke_color));
299 }
301 // Opacity
302 Inkscape::CSSOStringStream os_opacity;
303 os_opacity << state->getStrokeOpacity();
304 sp_repr_css_set_property(css, "stroke-opacity", os_opacity.str().c_str());
306 // Line width
307 Inkscape::CSSOStringStream os_width;
308 os_width << state->getLineWidth();
309 sp_repr_css_set_property(css, "stroke-width", os_width.str().c_str());
311 // Line cap
312 switch (state->getLineCap()) {
313 case 0:
314 sp_repr_css_set_property(css, "stroke-linecap", "butt");
315 break;
316 case 1:
317 sp_repr_css_set_property(css, "stroke-linecap", "round");
318 break;
319 case 2:
320 sp_repr_css_set_property(css, "stroke-linecap", "square");
321 break;
322 }
324 // Line join
325 switch (state->getLineJoin()) {
326 case 0:
327 sp_repr_css_set_property(css, "stroke-linejoin", "miter");
328 break;
329 case 1:
330 sp_repr_css_set_property(css, "stroke-linejoin", "round");
331 break;
332 case 2:
333 sp_repr_css_set_property(css, "stroke-linejoin", "bevel");
334 break;
335 }
337 // Miterlimit
338 Inkscape::CSSOStringStream os_ml;
339 os_ml << state->getMiterLimit();
340 sp_repr_css_set_property(css, "stroke-miterlimit", os_ml.str().c_str());
342 // Line dash
343 double *dash_pattern;
344 int dash_length;
345 double dash_start;
346 state->getLineDash(&dash_pattern, &dash_length, &dash_start);
347 if ( dash_length > 0 ) {
348 Inkscape::CSSOStringStream os_array;
349 for ( int i = 0 ; i < dash_length ; i++ ) {
350 os_array << dash_pattern[i];
351 if (i < (dash_length - 1)) {
352 os_array << ",";
353 }
354 }
355 sp_repr_css_set_property(css, "stroke-dasharray", os_array.str().c_str());
357 Inkscape::CSSOStringStream os_offset;
358 os_offset << dash_start;
359 sp_repr_css_set_property(css, "stroke-dashoffset", os_offset.str().c_str());
360 } else {
361 sp_repr_css_set_property(css, "stroke-dasharray", "none");
362 sp_repr_css_set_property(css, "stroke-dashoffset", NULL);
363 }
364 }
366 /**
367 * \brief Sets fill style from poppler's GfxState data structure
368 * Uses the given SPCSSAttr for storing the style properties.
369 */
370 void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) {
372 // Fill color/pattern
373 if ( state->getFillColorSpace()->getMode() == csPattern ) {
374 gchar *urltext = _createPattern(state->getFillPattern(), state);
375 sp_repr_css_set_property(css, "fill", urltext);
376 if (urltext) {
377 g_free(urltext);
378 }
379 } else {
380 GfxRGB fill_color;
381 state->getFillRGB(&fill_color);
382 sp_repr_css_set_property(css, "fill", svgConvertGfxRGB(&fill_color));
383 }
385 // Opacity
386 Inkscape::CSSOStringStream os_opacity;
387 os_opacity << state->getFillOpacity();
388 sp_repr_css_set_property(css, "fill-opacity", os_opacity.str().c_str());
390 // Fill rule
391 sp_repr_css_set_property(css, "fill-rule", even_odd ? "evenodd" : "nonzero");
392 }
394 /**
395 * \brief Sets style properties from poppler's GfxState data structure
396 * \return SPCSSAttr with all the relevant properties set
397 */
398 SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) {
399 SPCSSAttr *css = sp_repr_css_attr_new();
400 if (fill) {
401 _setFillStyle(css, state, even_odd);
402 } else {
403 sp_repr_css_set_property(css, "fill", "none");
404 }
406 if (stroke) {
407 _setStrokeStyle(css, state);
408 } else {
409 sp_repr_css_set_property(css, "stroke", "none");
410 }
412 return css;
413 }
415 /**
416 * \brief Emits the current path in poppler's GfxState data structure
417 * Can be used to do filling and stroking at once.
418 *
419 * \param fill whether the path should be filled
420 * \param stroke whether the path should be stroked
421 * \param even_odd whether the even-odd rule should be used when filling the path
422 */
423 void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) {
424 Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
425 gchar *pathtext = svgInterpretPath(state->getPath());
426 path->setAttribute("d", pathtext);
427 g_free(pathtext);
429 // Set style
430 SPCSSAttr *css = _setStyle(state, fill, stroke, even_odd);
431 sp_repr_css_change(path, css, "style");
432 sp_repr_css_attr_unref(css);
434 _container->appendChild(path);
435 Inkscape::GC::release(path);
436 }
438 /**
439 * \brief Emits the current path in poppler's GfxState data structure
440 * The path is set to be filled with the given shading.
441 */
442 void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *path,
443 bool even_odd) {
445 Inkscape::XML::Node *path_node = _xml_doc->createElement("svg:path");
446 gchar *pathtext = svgInterpretPath(path);
447 path_node->setAttribute("d", pathtext);
448 g_free(pathtext);
450 // Set style
451 SPCSSAttr *css = sp_repr_css_attr_new();
452 gchar *id = _createGradient(shading, matrix, true);
453 if (id) {
454 gchar *urltext = g_strdup_printf ("url(#%s)", id);
455 sp_repr_css_set_property(css, "fill", urltext);
456 g_free(urltext);
457 g_free(id);
458 } else {
459 sp_repr_css_attr_unref(css);
460 Inkscape::GC::release(path_node);
461 return;
462 }
463 if (even_odd) {
464 sp_repr_css_set_property(css, "fill-rule", "evenodd");
465 }
466 sp_repr_css_set_property(css, "stroke", "none");
467 sp_repr_css_change(path_node, css, "style");
468 sp_repr_css_attr_unref(css);
470 _container->appendChild(path_node);
471 Inkscape::GC::release(path_node);
473 // Remove the clipping path emitted before the 'sh' operator
474 int up_walk = 0;
475 Inkscape::XML::Node *node = _container->parent();
476 while( node && node->childCount() == 1 && up_walk < 3 ) {
477 gchar const *clip_path_url = node->attribute("clip-path");
478 if (clip_path_url) {
479 // Obtain clipping path's id from the URL
480 gchar clip_path_id[32];
481 strncpy(clip_path_id, clip_path_url + 5, strlen(clip_path_url) - 6);
482 SPObject *clip_obj = _doc->getObjectById(clip_path_id);
483 if (clip_obj) {
484 clip_obj->deleteObject();
485 node->setAttribute("clip-path", NULL);
486 TRACE(("removed clipping path: %s\n", clip_path_id));
487 }
488 break;
489 }
490 node = node->parent();
491 up_walk++;
492 }
493 }
495 /**
496 * \brief Clips to the current path set in GfxState
497 * \param state poppler's data structure
498 * \param even_odd whether the even-odd rule should be applied
499 */
500 void SvgBuilder::clip(GfxState *state, bool even_odd) {
501 pushGroup();
502 setClipPath(state, even_odd);
503 }
505 void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
506 // Create the clipPath repr
507 Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath");
508 clip_path->setAttribute("clipPathUnits", "userSpaceOnUse");
509 // Create the path
510 Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
511 gchar *pathtext = svgInterpretPath(state->getPath());
512 path->setAttribute("d", pathtext);
513 g_free(pathtext);
514 if (even_odd) {
515 path->setAttribute("clip-rule", "evenodd");
516 }
517 clip_path->appendChild(path);
518 Inkscape::GC::release(path);
519 // Append clipPath to defs and get id
520 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(clip_path);
521 gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id"));
522 Inkscape::GC::release(clip_path);
523 _container->setAttribute("clip-path", urltext);
524 g_free(urltext);
525 }
527 /**
528 * \brief Fills the given array with the current container's transform, if set
529 * \param transform array of doubles to be filled
530 * \return true on success; false on invalid transformation
531 */
532 bool SvgBuilder::getTransform(double *transform) {
533 NR::Matrix svd;
534 gchar const *tr = _container->attribute("transform");
535 bool valid = sp_svg_transform_read(tr, &svd);
536 if (valid) {
537 for ( int i = 0 ; i < 6 ; i++ ) {
538 transform[i] = svd[i];
539 }
540 return true;
541 } else {
542 return false;
543 }
544 }
546 /**
547 * \brief Sets the transformation matrix of the current container
548 */
549 void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
550 double c4, double c5) {
552 TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
553 svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
554 }
556 void SvgBuilder::setTransform(double *transform) {
557 setTransform(transform[0], transform[1], transform[2], transform[3],
558 transform[4], transform[5]);
559 }
561 /**
562 * \brief Checks whether the given pattern type can be represented in SVG
563 * Used by PdfParser to decide when to do fallback operations.
564 */
565 bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) {
566 if ( pattern != NULL ) {
567 if ( pattern->getType() == 2 ) { // shading pattern
568 GfxShading *shading = ((GfxShadingPattern *)pattern)->getShading();
569 int shadingType = shading->getType();
570 if ( shadingType == 2 || // axial shading
571 shadingType == 3 ) { // radial shading
572 return true;
573 }
574 return false;
575 } else if ( pattern->getType() == 1 ) { // tiling pattern
576 return true;
577 }
578 }
580 return false;
581 }
583 /**
584 * \brief Creates a pattern from poppler's data structure
585 * Handles linear and radial gradients. Creates a new PdfParser and uses it to
586 * build a tiling pattern.
587 * \return an url pointing to the created pattern
588 */
589 gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) {
590 gchar *id = NULL;
591 if ( pattern != NULL ) {
592 if ( pattern->getType() == 2 ) { // Shading pattern
593 GfxShadingPattern *shading_pattern = (GfxShadingPattern*)pattern;
594 id = _createGradient(shading_pattern->getShading(),
595 shading_pattern->getMatrix());
596 } else if ( pattern->getType() == 1 ) { // Tiling pattern
597 id = _createTilingPattern((GfxTilingPattern*)pattern, state, is_stroke);
598 }
599 } else {
600 return NULL;
601 }
602 gchar *urltext = g_strdup_printf ("url(#%s)", id);
603 g_free(id);
604 return urltext;
605 }
607 /**
608 * \brief Creates a tiling pattern from poppler's data structure
609 * Creates a sub-page PdfParser and uses it to parse the pattern's content stream.
610 * \return id of the created pattern
611 */
612 gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
613 GfxState *state, bool is_stroke) {
615 Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
616 // Set pattern transform matrix
617 double *p2u = tiling_pattern->getMatrix();
618 NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
619 gchar *transform_text = sp_svg_transform_write(pat_matrix);
620 pattern_node->setAttribute("patternTransform", transform_text);
621 g_free(transform_text);
622 pattern_node->setAttribute("patternUnits", "userSpaceOnUse");
623 // Set pattern tiling
624 // FIXME: don't ignore XStep and YStep
625 double *bbox = tiling_pattern->getBBox();
626 sp_repr_set_svg_double(pattern_node, "x", 0.0);
627 sp_repr_set_svg_double(pattern_node, "y", 0.0);
628 sp_repr_set_svg_double(pattern_node, "width", bbox[2] - bbox[0]);
629 sp_repr_set_svg_double(pattern_node, "height", bbox[3] - bbox[1]);
631 // Convert BBox for PdfParser
632 PDFRectangle box;
633 box.x1 = bbox[0];
634 box.y1 = bbox[1];
635 box.x2 = bbox[2];
636 box.y2 = bbox[3];
637 // Create new SvgBuilder and sub-page PdfParser
638 SvgBuilder *pattern_builder = new SvgBuilder(this, pattern_node);
639 PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(),
640 &box);
641 // Get pattern color space
642 GfxPatternColorSpace *pat_cs = (GfxPatternColorSpace *)( is_stroke ? state->getStrokeColorSpace()
643 : state->getFillColorSpace() );
644 // Set fill/stroke colors if this is an uncolored tiling pattern
645 GfxColorSpace *cs = NULL;
646 if ( tiling_pattern->getPaintType() == 2 && ( cs = pat_cs->getUnder() ) ) {
647 GfxState *pattern_state = pdf_parser->getState();
648 pattern_state->setFillColorSpace(cs->copy());
649 pattern_state->setFillColor(state->getFillColor());
650 pattern_state->setStrokeColorSpace(cs->copy());
651 pattern_state->setStrokeColor(state->getFillColor());
652 }
654 // Generate the SVG pattern
655 pdf_parser->parse(tiling_pattern->getContentStream());
657 // Cleanup
658 delete pdf_parser;
659 delete pattern_builder;
661 // Append the pattern to defs
662 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(pattern_node);
663 gchar *id = g_strdup(pattern_node->attribute("id"));
664 Inkscape::GC::release(pattern_node);
666 return id;
667 }
669 /**
670 * \brief Creates a linear or radial gradient from poppler's data structure
671 * \param shading poppler's data structure for the shading
672 * \param matrix gradient transformation, can be null
673 * \param for_shading true if we're creating this for a shading operator; false otherwise
674 * \return id of the created object
675 */
676 gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for_shading) {
677 Inkscape::XML::Node *gradient;
678 Function *func;
679 int num_funcs;
680 bool extend0, extend1;
682 if ( shading->getType() == 2 ) { // Axial shading
683 gradient = _xml_doc->createElement("svg:linearGradient");
684 GfxAxialShading *axial_shading = (GfxAxialShading*)shading;
685 double x1, y1, x2, y2;
686 axial_shading->getCoords(&x1, &y1, &x2, &y2);
687 sp_repr_set_svg_double(gradient, "x1", x1);
688 sp_repr_set_svg_double(gradient, "y1", y1);
689 sp_repr_set_svg_double(gradient, "x2", x2);
690 sp_repr_set_svg_double(gradient, "y2", y2);
691 extend0 = axial_shading->getExtend0();
692 extend1 = axial_shading->getExtend1();
693 num_funcs = axial_shading->getNFuncs();
694 func = axial_shading->getFunc(0);
695 } else if (shading->getType() == 3) { // Radial shading
696 gradient = _xml_doc->createElement("svg:radialGradient");
697 GfxRadialShading *radial_shading = (GfxRadialShading*)shading;
698 double x1, y1, r1, x2, y2, r2;
699 radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2);
700 // FIXME: the inner circle's radius is ignored here
701 sp_repr_set_svg_double(gradient, "fx", x1);
702 sp_repr_set_svg_double(gradient, "fy", y1);
703 sp_repr_set_svg_double(gradient, "cx", x2);
704 sp_repr_set_svg_double(gradient, "cy", y2);
705 sp_repr_set_svg_double(gradient, "r", r2);
706 extend0 = radial_shading->getExtend0();
707 extend1 = radial_shading->getExtend1();
708 num_funcs = radial_shading->getNFuncs();
709 func = radial_shading->getFunc(0);
710 } else { // Unsupported shading type
711 return NULL;
712 }
713 gradient->setAttribute("gradientUnits", "userSpaceOnUse");
714 // If needed, flip the gradient transform around the y axis
715 if (matrix) {
716 NR::Matrix pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3],
717 matrix[4], matrix[5]);
718 if ( !for_shading && _is_top_level ) {
719 NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
720 pat_matrix *= flip;
721 }
722 gchar *transform_text = sp_svg_transform_write(pat_matrix);
723 gradient->setAttribute("gradientTransform", transform_text);
724 g_free(transform_text);
725 }
727 if ( extend0 && extend1 ) {
728 gradient->setAttribute("spreadMethod", "pad");
729 }
731 if ( num_funcs > 1 || !_addGradientStops(gradient, shading, func) ) {
732 Inkscape::GC::release(gradient);
733 return NULL;
734 }
736 Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc));
737 defs->appendChild(gradient);
738 gchar *id = g_strdup(gradient->attribute("id"));
739 Inkscape::GC::release(gradient);
741 return id;
742 }
744 #define EPSILON 0.0001
745 /**
746 * \brief Adds a stop with the given properties to the gradient's representation
747 */
748 void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset,
749 GfxRGB *color, double opacity) {
750 Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
751 SPCSSAttr *css = sp_repr_css_attr_new();
752 Inkscape::CSSOStringStream os_opacity;
753 gchar *color_text = NULL;
754 if ( _transp_group_stack != NULL && _transp_group_stack->for_softmask ) {
755 double gray = (double)color->r / 65535.0;
756 gray = CLAMP(gray, 0.0, 1.0);
757 os_opacity << gray;
758 color_text = "#ffffff";
759 } else {
760 os_opacity << opacity;
761 color_text = svgConvertGfxRGB(color);
762 }
763 sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
764 sp_repr_css_set_property(css, "stop-color", color_text);
766 sp_repr_css_change(stop, css, "style");
767 sp_repr_css_attr_unref(css);
768 sp_repr_set_css_double(stop, "offset", offset);
770 gradient->appendChild(stop);
771 Inkscape::GC::release(stop);
772 }
774 static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *result) {
775 GfxColorSpace *color_space = shading->getColorSpace();
776 GfxColor temp;
777 if ( shading->getType() == 2 ) { // Axial shading
778 ((GfxAxialShading*)shading)->getColor(offset, &temp);
779 } else if ( shading->getType() == 3 ) { // Radial shading
780 ((GfxRadialShading*)shading)->getColor(offset, &temp);
781 } else {
782 return false;
783 }
784 // Convert it to RGB
785 color_space->getRGB(&temp, result);
787 return true;
788 }
790 #define INT_EPSILON 8
791 bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading,
792 Function *func) {
793 int type = func->getType();
794 if ( type == 0 || type == 2 ) { // Sampled or exponential function
795 GfxRGB stop1, stop2;
796 if ( !svgGetShadingColorRGB(shading, 0.0, &stop1) ||
797 !svgGetShadingColorRGB(shading, 1.0, &stop2) ) {
798 return false;
799 } else {
800 _addStopToGradient(gradient, 0.0, &stop1, 1.0);
801 _addStopToGradient(gradient, 1.0, &stop2, 1.0);
802 }
803 } else if ( type == 3 ) { // Stitching
804 StitchingFunction *stitchingFunc = (StitchingFunction*)func;
805 double *bounds = stitchingFunc->getBounds();
806 int num_funcs = stitchingFunc->getNumFuncs();
807 // Add stops from all the stitched functions
808 for ( int i = 0 ; i < num_funcs ; i++ ) {
809 GfxRGB color;
810 svgGetShadingColorRGB(shading, bounds[i], &color);
811 bool is_continuation = false;
812 if ( i > 0 ) { // Compare to previous stop
813 GfxRGB prev_color;
814 svgGetShadingColorRGB(shading, bounds[i-1], &prev_color);
815 if ( abs(color.r - prev_color.r) < INT_EPSILON &&
816 abs(color.g - prev_color.g) < INT_EPSILON &&
817 abs(color.b - prev_color.b) < INT_EPSILON ) {
818 is_continuation = true;
819 }
820 }
821 // Add stops
822 if ( !is_continuation ) {
823 _addStopToGradient(gradient, bounds[i], &color, 1.0);
824 }
825 if ( is_continuation || ( i == num_funcs - 1 ) ) {
826 GfxRGB next_color;
827 svgGetShadingColorRGB(shading, bounds[i+1], &next_color);
828 _addStopToGradient(gradient, bounds[i+1], &next_color, 1.0);
829 }
830 }
831 } else { // Unsupported function type
832 return false;
833 }
835 return true;
836 }
838 /**
839 * \brief Sets _invalidated_style to true to indicate that styles have to be updated
840 * Used for text output when glyphs are buffered till a font change
841 */
842 void SvgBuilder::updateStyle(GfxState *state) {
843 if (_in_text_object) {
844 _invalidated_style = true;
845 _current_state = state;
846 }
847 }
849 /**
850 * This array holds info about translating font weight names to more or less CSS equivalents
851 */
852 static char *font_weight_translator[][2] = {
853 {"bold", "bold"},
854 {"light", "300"},
855 {"black", "900"},
856 {"heavy", "900"},
857 {"ultrabold", "800"},
858 {"extrabold", "800"},
859 {"demibold", "600"},
860 {"semibold", "600"},
861 {"medium", "500"},
862 {"book", "normal"},
863 {"regular", "normal"},
864 {"roman", "normal"},
865 {"normal", "normal"},
866 {"ultralight", "200"},
867 {"extralight", "200"},
868 {"thin", "100"}
869 };
871 /**
872 * \brief Updates _font_style according to the font set in parameter state
873 */
874 void SvgBuilder::updateFont(GfxState *state) {
876 TRACE(("updateFont()\n"));
877 _need_font_update = false;
878 updateTextMatrix(state); // Ensure that we have a text matrix built
880 if (_font_style) {
881 //sp_repr_css_attr_unref(_font_style);
882 }
883 _font_style = sp_repr_css_attr_new();
884 GfxFont *font = state->getFont();
885 // Store original name
886 if (font->getOrigName()) {
887 _font_specification = font->getOrigName()->getCString();
888 } else if (font->getName()) {
889 _font_specification = font->getName()->getCString();
890 } else {
891 _font_specification = "Arial";
892 }
894 // Prune the font name to get the correct font family name
895 // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic
896 char *font_family = NULL;
897 char *font_style = NULL;
898 char *font_style_lowercase = NULL;
899 char *plus_sign = strstr(_font_specification, "+");
900 if (plus_sign) {
901 font_family = g_strdup(plus_sign + 1);
902 _font_specification = plus_sign + 1;
903 } else {
904 font_family = g_strdup(_font_specification);
905 }
906 char *style_delim = NULL;
907 if ( ( style_delim = g_strrstr(font_family, "-") ) ||
908 ( style_delim = g_strrstr(font_family, ",") ) ) {
909 font_style = style_delim + 1;
910 font_style_lowercase = g_ascii_strdown(font_style, -1);
911 style_delim[0] = 0;
912 }
914 // Font family
915 if (font->getFamily()) {
916 sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
917 } else {
918 sp_repr_css_set_property(_font_style, "font-family", font_family);
919 }
921 // Font style
922 if (font->isItalic()) {
923 sp_repr_css_set_property(_font_style, "font-style", "italic");
924 } else if (font_style) {
925 if ( strstr(font_style_lowercase, "italic") ||
926 strstr(font_style_lowercase, "slanted") ) {
927 sp_repr_css_set_property(_font_style, "font-style", "italic");
928 } else if (strstr(font_style_lowercase, "oblique")) {
929 sp_repr_css_set_property(_font_style, "font-style", "oblique");
930 }
931 }
933 // Font variant -- default 'normal' value
934 sp_repr_css_set_property(_font_style, "font-variant", "normal");
936 // Font weight
937 GfxFont::Weight font_weight = font->getWeight();
938 char *css_font_weight = NULL;
939 if ( font_weight != GfxFont::WeightNotDefined ) {
940 if ( font_weight == GfxFont::W400 ) {
941 css_font_weight = "normal";
942 } else if ( font_weight == GfxFont::W700 ) {
943 css_font_weight = "bold";
944 } else {
945 gchar weight_num[4] = "100";
946 weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
947 sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num);
948 }
949 } else if (font_style) {
950 // Apply the font weight translations
951 int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) );
952 for ( int i = 0 ; i < num_translations ; i++ ) {
953 if (strstr(font_style_lowercase, font_weight_translator[i][0])) {
954 css_font_weight = font_weight_translator[i][1];
955 }
956 }
957 } else {
958 css_font_weight = "normal";
959 }
960 if (css_font_weight) {
961 sp_repr_css_set_property(_font_style, "font-weight", css_font_weight);
962 }
963 g_free(font_family);
964 if (font_style_lowercase) {
965 g_free(font_style_lowercase);
966 }
968 // Font stretch
969 GfxFont::Stretch font_stretch = font->getStretch();
970 gchar *stretch_value = NULL;
971 switch (font_stretch) {
972 case GfxFont::UltraCondensed:
973 stretch_value = "ultra-condensed";
974 break;
975 case GfxFont::ExtraCondensed:
976 stretch_value = "extra-condensed";
977 break;
978 case GfxFont::Condensed:
979 stretch_value = "condensed";
980 break;
981 case GfxFont::SemiCondensed:
982 stretch_value = "semi-condensed";
983 break;
984 case GfxFont::Normal:
985 stretch_value = "normal";
986 break;
987 case GfxFont::SemiExpanded:
988 stretch_value = "semi-expanded";
989 break;
990 case GfxFont::Expanded:
991 stretch_value = "expanded";
992 break;
993 case GfxFont::ExtraExpanded:
994 stretch_value = "extra-expanded";
995 break;
996 case GfxFont::UltraExpanded:
997 stretch_value = "ultra-expanded";
998 break;
999 default:
1000 break;
1001 }
1002 if ( stretch_value != NULL ) {
1003 sp_repr_css_set_property(_font_style, "font-stretch", stretch_value);
1004 }
1006 // Font size
1007 Inkscape::CSSOStringStream os_font_size;
1008 double css_font_size = _font_scaling * state->getFontSize();
1009 if ( font->getType() == fontType3 ) {
1010 double *font_matrix = font->getFontMatrix();
1011 if ( font_matrix[0] != 0.0 ) {
1012 css_font_size *= font_matrix[3] / font_matrix[0];
1013 }
1014 }
1015 os_font_size << css_font_size;
1016 sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
1018 // Writing mode
1019 if ( font->getWMode() == 0 ) {
1020 sp_repr_css_set_property(_font_style, "writing-mode", "lr");
1021 } else {
1022 sp_repr_css_set_property(_font_style, "writing-mode", "tb");
1023 }
1025 _current_font = font;
1026 _invalidated_style = true;
1027 }
1029 /**
1030 * \brief Shifts the current text position by the given amount (specified in text space)
1031 */
1032 void SvgBuilder::updateTextShift(GfxState *state, double shift) {
1033 double shift_value = -shift * 0.001 * fabs(state->getFontSize());
1034 if (state->getFont()->getWMode()) {
1035 _text_position[1] += shift_value;
1036 } else {
1037 _text_position[0] += shift_value;
1038 }
1039 }
1041 /**
1042 * \brief Updates current text position
1043 */
1044 void SvgBuilder::updateTextPosition(double tx, double ty) {
1045 NR::Point new_position(tx, ty);
1046 _text_position = new_position;
1047 }
1049 /**
1050 * \brief Flushes the buffered characters
1051 */
1052 void SvgBuilder::updateTextMatrix(GfxState *state) {
1053 _flushText();
1054 // Update text matrix
1055 double *text_matrix = state->getTextMat();
1056 double w_scale = sqrt( text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2] );
1057 double h_scale = sqrt( text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3] );
1058 double max_scale;
1059 if ( w_scale > h_scale ) {
1060 max_scale = w_scale;
1061 } else {
1062 max_scale = h_scale;
1063 }
1064 // Calculate new text matrix
1065 NR::Matrix new_text_matrix(text_matrix[0] * state->getHorizScaling(),
1066 text_matrix[1] * state->getHorizScaling(),
1067 -text_matrix[2], -text_matrix[3],
1068 0.0, 0.0);
1070 if ( fabs( max_scale - 1.0 ) > EPSILON ) {
1071 // Cancel out scaling by font size in text matrix
1072 for ( int i = 0 ; i < 4 ; i++ ) {
1073 new_text_matrix[i] /= max_scale;
1074 }
1075 }
1076 _text_matrix = new_text_matrix;
1077 _font_scaling = max_scale;
1078 }
1080 /**
1081 * \brief Writes the buffered characters to the SVG document
1082 */
1083 void SvgBuilder::_flushText() {
1084 // Ignore empty strings
1085 if ( _glyphs.size() < 1 ) {
1086 _glyphs.clear();
1087 return;
1088 }
1089 std::vector<SvgGlyph>::iterator i = _glyphs.begin();
1090 const SvgGlyph& first_glyph = (*i);
1091 int render_mode = first_glyph.render_mode;
1092 // Ignore invisible characters
1093 if ( render_mode == 3 ) {
1094 _glyphs.clear();
1095 return;
1096 }
1098 Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
1099 // Set text matrix
1100 NR::Matrix text_transform(_text_matrix);
1101 text_transform[4] = first_glyph.position[0];
1102 text_transform[5] = first_glyph.position[1];
1103 gchar *transform = sp_svg_transform_write(text_transform);
1104 text_node->setAttribute("transform", transform);
1105 g_free(transform);
1107 bool new_tspan = true;
1108 bool same_coords[2] = {true, true};
1109 NR::Point last_delta_pos;
1110 unsigned int glyphs_in_a_row = 0;
1111 Inkscape::XML::Node *tspan_node = NULL;
1112 Glib::ustring x_coords;
1113 Glib::ustring y_coords;
1114 Glib::ustring text_buffer;
1116 // Output all buffered glyphs
1117 while (1) {
1118 const SvgGlyph& glyph = (*i);
1119 std::vector<SvgGlyph>::iterator prev_iterator = i - 1;
1120 // Check if we need to make a new tspan
1121 if (glyph.style_changed) {
1122 new_tspan = true;
1123 } else if ( i != _glyphs.begin() ) {
1124 const SvgGlyph& prev_glyph = (*prev_iterator);
1125 if ( !( ( glyph.dy == 0.0 && prev_glyph.dy == 0.0 &&
1126 glyph.text_position[1] == prev_glyph.text_position[1] ) ||
1127 ( glyph.dx == 0.0 && prev_glyph.dx == 0.0 &&
1128 glyph.text_position[0] == prev_glyph.text_position[0] ) ) ) {
1129 new_tspan = true;
1130 }
1131 }
1133 // Create tspan node if needed
1134 if ( new_tspan || i == _glyphs.end() ) {
1135 if (tspan_node) {
1136 // Set the x and y coordinate arrays
1137 if ( same_coords[0] ) {
1138 sp_repr_set_svg_double(tspan_node, "x", last_delta_pos[0]);
1139 } else {
1140 tspan_node->setAttribute("x", x_coords.c_str());
1141 }
1142 if ( same_coords[1] ) {
1143 sp_repr_set_svg_double(tspan_node, "y", last_delta_pos[1]);
1144 } else {
1145 tspan_node->setAttribute("y", y_coords.c_str());
1146 }
1147 TRACE(("tspan content: %s\n", text_buffer.c_str()));
1148 if ( glyphs_in_a_row > 1 ) {
1149 tspan_node->setAttribute("sodipodi:role", "line");
1150 }
1151 // Add text content node to tspan
1152 Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str());
1153 tspan_node->appendChild(text_content);
1154 Inkscape::GC::release(text_content);
1155 text_node->appendChild(tspan_node);
1156 // Clear temporary buffers
1157 x_coords.clear();
1158 y_coords.clear();
1159 text_buffer.clear();
1160 Inkscape::GC::release(tspan_node);
1161 glyphs_in_a_row = 0;
1162 }
1163 if ( i == _glyphs.end() ) {
1164 sp_repr_css_attr_unref((*prev_iterator).style);
1165 break;
1166 } else {
1167 tspan_node = _xml_doc->createElement("svg:tspan");
1168 tspan_node->setAttribute("inkscape:font-specification", glyph.font_specification);
1169 // Set style and unref SPCSSAttr if it won't be needed anymore
1170 sp_repr_css_change(tspan_node, glyph.style, "style");
1171 if ( glyph.style_changed && i != _glyphs.begin() ) { // Free previous style
1172 sp_repr_css_attr_unref((*prev_iterator).style);
1173 }
1174 }
1175 new_tspan = false;
1176 }
1177 if ( glyphs_in_a_row > 0 ) {
1178 x_coords.append(" ");
1179 y_coords.append(" ");
1180 // Check if we have the same coordinates
1181 const SvgGlyph& prev_glyph = (*prev_iterator);
1182 for ( int p = 0 ; p < 2 ; p++ ) {
1183 if ( glyph.text_position[p] != prev_glyph.text_position[p] ) {
1184 same_coords[p] = false;
1185 }
1186 }
1187 }
1188 // Append the coordinates to their respective strings
1189 NR::Point delta_pos( glyph.text_position - first_glyph.text_position );
1190 delta_pos[1] += glyph.rise;
1191 delta_pos[1] *= -1.0; // flip it
1192 delta_pos *= _font_scaling;
1193 Inkscape::CSSOStringStream os_x;
1194 os_x << delta_pos[0];
1195 x_coords.append(os_x.str());
1196 Inkscape::CSSOStringStream os_y;
1197 os_y << delta_pos[1];
1198 y_coords.append(os_y.str());
1199 last_delta_pos = delta_pos;
1201 // Append the character to the text buffer
1202 text_buffer.append((char *)&glyph.code, 1);
1204 glyphs_in_a_row++;
1205 i++;
1206 }
1207 _container->appendChild(text_node);
1208 Inkscape::GC::release(text_node);
1210 _glyphs.clear();
1211 }
1213 void SvgBuilder::beginString(GfxState *state, GooString *s) {
1214 if (_need_font_update) {
1215 updateFont(state);
1216 }
1217 IFTRACE(double *m = state->getTextMat());
1218 TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1219 IFTRACE(m = state->getCTM());
1220 TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1221 }
1223 /**
1224 * \brief Adds the specified character to the text buffer
1225 * Takes care of converting it to UTF-8 and generates a new style repr if style
1226 * has changed since the last call.
1227 */
1228 void SvgBuilder::addChar(GfxState *state, double x, double y,
1229 double dx, double dy,
1230 double originX, double originY,
1231 CharCode code, int nBytes, Unicode *u, int uLen) {
1234 bool is_space = ( uLen == 1 && u[0] == 32 );
1235 // Skip beginning space
1236 if ( is_space && _glyphs.size() < 1 ) {
1237 NR::Point delta(dx, dy);
1238 _text_position += delta;
1239 return;
1240 }
1241 // Allow only one space in a row
1242 if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 &&
1243 _glyphs[_glyphs.size() - 1].code[0] == 32 ) {
1244 NR::Point delta(dx, dy);
1245 _text_position += delta;
1246 return;
1247 }
1249 SvgGlyph new_glyph;
1250 new_glyph.is_space = is_space;
1251 new_glyph.position = NR::Point( x - originX, y - originY );
1252 new_glyph.text_position = _text_position;
1253 new_glyph.dx = dx;
1254 new_glyph.dy = dy;
1255 NR::Point delta(dx, dy);
1256 _text_position += delta;
1258 // Convert the character to UTF-8 since that's our SVG document's encoding
1259 static UnicodeMap *u_map = NULL;
1260 if ( u_map == NULL ) {
1261 GooString *enc = new GooString("UTF-8");
1262 u_map = globalParams->getUnicodeMap(enc);
1263 u_map->incRefCnt();
1264 delete enc;
1265 }
1266 int code_size = 0;
1267 for ( int i = 0 ; i < uLen ; i++ ) {
1268 code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size);
1269 }
1270 new_glyph.code_size = code_size;
1272 // Copy current style if it has changed since the previous glyph
1273 if (_invalidated_style || _glyphs.size() == 0 ) {
1274 new_glyph.style_changed = true;
1275 int render_mode = state->getRender();
1276 // Set style
1277 bool has_fill = !( render_mode & 1 );
1278 bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2;
1279 new_glyph.style = _setStyle(state, has_fill, has_stroke);
1280 new_glyph.render_mode = render_mode;
1281 sp_repr_css_merge(new_glyph.style, _font_style); // Merge with font style
1282 _invalidated_style = false;
1283 } else {
1284 new_glyph.style_changed = false;
1285 // Point to previous glyph's style information
1286 const SvgGlyph& prev_glyph = _glyphs.back();
1287 new_glyph.style = prev_glyph.style;
1288 new_glyph.render_mode = prev_glyph.render_mode;
1289 }
1290 new_glyph.font_specification = _font_specification;
1291 new_glyph.rise = state->getRise();
1293 _glyphs.push_back(new_glyph);
1294 }
1296 void SvgBuilder::endString(GfxState *state) {
1297 }
1299 void SvgBuilder::beginTextObject(GfxState *state) {
1300 _in_text_object = true;
1301 _invalidated_style = true; // Force copying of current state
1302 _current_state = state;
1303 }
1305 void SvgBuilder::endTextObject(GfxState *state) {
1306 _flushText();
1307 // TODO: clip if render_mode >= 4
1308 _in_text_object = false;
1309 }
1311 /**
1312 * Helper functions for supporting direct PNG output into a base64 encoded stream
1313 */
1314 void png_write_base64stream(png_structp png_ptr, png_bytep data, png_size_t length)
1315 {
1316 Inkscape::IO::Base64OutputStream *stream =
1317 (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1318 for ( unsigned i = 0 ; i < length ; i++ ) {
1319 stream->put((int)data[i]);
1320 }
1321 }
1323 void png_flush_base64stream(png_structp png_ptr)
1324 {
1325 Inkscape::IO::Base64OutputStream *stream =
1326 (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1327 stream->flush();
1328 }
1330 /**
1331 * \brief Creates an <image> element containing the given ImageStream as a PNG
1332 *
1333 */
1334 Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height,
1335 GfxImageColorMap *color_map, int *mask_colors, bool alpha_only, bool invert_alpha) {
1337 // Create PNG write struct
1338 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1339 if ( png_ptr == NULL ) {
1340 return NULL;
1341 }
1342 // Create PNG info struct
1343 png_infop info_ptr = png_create_info_struct(png_ptr);
1344 if ( info_ptr == NULL ) {
1345 png_destroy_write_struct(&png_ptr, NULL);
1346 return NULL;
1347 }
1348 // Set error handler
1349 if (setjmp(png_ptr->jmpbuf)) {
1350 png_destroy_write_struct(&png_ptr, &info_ptr);
1351 return NULL;
1352 }
1353 // Decide whether we should embed this image
1354 double attr_value = 1.0;
1355 sp_repr_get_double(_preferences, "embedImages", &attr_value);
1356 bool embed_image = ( attr_value != 0.0 );
1357 // Set read/write functions
1358 Inkscape::IO::StringOutputStream base64_string;
1359 Inkscape::IO::Base64OutputStream base64_stream(base64_string);
1360 FILE *fp = NULL;
1361 gchar *file_name = NULL;
1362 if (embed_image) {
1363 base64_stream.setColumnWidth(0); // Disable line breaks
1364 png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream);
1365 } else {
1366 static int counter = 0;
1367 file_name = g_strdup_printf("%s_img%d.png", _docname, counter++);
1368 fp = fopen(file_name, "wb");
1369 if ( fp == NULL ) {
1370 png_destroy_write_struct(&png_ptr, &info_ptr);
1371 g_free(file_name);
1372 return NULL;
1373 }
1374 png_init_io(png_ptr, fp);
1375 }
1377 // Set header data
1378 if ( !invert_alpha && !alpha_only ) {
1379 png_set_invert_alpha(png_ptr);
1380 }
1381 png_color_8 sig_bit;
1382 if (alpha_only) {
1383 png_set_IHDR(png_ptr, info_ptr,
1384 width,
1385 height,
1386 8, /* bit_depth */
1387 PNG_COLOR_TYPE_GRAY,
1388 PNG_INTERLACE_NONE,
1389 PNG_COMPRESSION_TYPE_BASE,
1390 PNG_FILTER_TYPE_BASE);
1391 sig_bit.red = 0;
1392 sig_bit.green = 0;
1393 sig_bit.blue = 0;
1394 sig_bit.gray = 8;
1395 sig_bit.alpha = 0;
1396 } else {
1397 png_set_IHDR(png_ptr, info_ptr,
1398 width,
1399 height,
1400 8, /* bit_depth */
1401 PNG_COLOR_TYPE_RGB_ALPHA,
1402 PNG_INTERLACE_NONE,
1403 PNG_COMPRESSION_TYPE_BASE,
1404 PNG_FILTER_TYPE_BASE);
1405 sig_bit.red = 8;
1406 sig_bit.green = 8;
1407 sig_bit.blue = 8;
1408 sig_bit.alpha = 8;
1409 }
1410 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
1411 png_set_bgr(png_ptr);
1412 // Write the file header
1413 png_write_info(png_ptr, info_ptr);
1415 // Convert pixels
1416 ImageStream *image_stream;
1417 if (alpha_only) {
1418 if (color_map) {
1419 image_stream = new ImageStream(str, width, color_map->getNumPixelComps(),
1420 color_map->getBits());
1421 } else {
1422 image_stream = new ImageStream(str, width, 1, 1);
1423 }
1424 image_stream->reset();
1426 // Convert grayscale values
1427 unsigned char *buffer = new unsigned char[width];
1428 int invert_bit = invert_alpha ? 1 : 0;
1429 for ( int y = 0 ; y < height ; y++ ) {
1430 unsigned char *row = image_stream->getLine();
1431 if (color_map) {
1432 color_map->getGrayLine(row, buffer, width);
1433 } else {
1434 unsigned char *buf_ptr = buffer;
1435 for ( int x = 0 ; x < width ; x++ ) {
1436 if ( row[x] ^ invert_bit ) {
1437 *buf_ptr++ = 0;
1438 } else {
1439 *buf_ptr++ = 255;
1440 }
1441 }
1442 }
1443 png_write_row(png_ptr, (png_bytep)buffer);
1444 }
1445 delete buffer;
1446 } else if (color_map) {
1447 image_stream = new ImageStream(str, width,
1448 color_map->getNumPixelComps(),
1449 color_map->getBits());
1450 image_stream->reset();
1452 // Convert RGB values
1453 unsigned int *buffer = new unsigned int[width];
1454 if (mask_colors) {
1455 for ( int y = 0 ; y < height ; y++ ) {
1456 unsigned char *row = image_stream->getLine();
1457 color_map->getRGBLine(row, buffer, width);
1459 unsigned int *dest = buffer;
1460 for ( int x = 0 ; x < width ; x++ ) {
1461 // Check each color component against the mask
1462 for ( int i = 0; i < color_map->getNumPixelComps() ; i++) {
1463 if ( row[i] < mask_colors[2*i] * 255 ||
1464 row[i] > mask_colors[2*i + 1] * 255 ) {
1465 *dest = *dest | 0xff000000;
1466 break;
1467 }
1468 }
1469 // Advance to the next pixel
1470 row += color_map->getNumPixelComps();
1471 dest++;
1472 }
1473 // Write it to the PNG
1474 png_write_row(png_ptr, (png_bytep)buffer);
1475 }
1476 } else {
1477 for ( int i = 0 ; i < height ; i++ ) {
1478 unsigned char *row = image_stream->getLine();
1479 memset((void*)buffer, 0xff, sizeof(int) * width);
1480 color_map->getRGBLine(row, buffer, width);
1481 png_write_row(png_ptr, (png_bytep)buffer);
1482 }
1483 }
1484 delete buffer;
1486 } else { // A colormap must be provided, so quit
1487 png_destroy_write_struct(&png_ptr, &info_ptr);
1488 if (!embed_image) {
1489 fclose(fp);
1490 g_free(file_name);
1491 }
1492 return NULL;
1493 }
1494 delete image_stream;
1495 str->close();
1496 // Close PNG
1497 png_write_end(png_ptr, info_ptr);
1498 png_destroy_write_struct(&png_ptr, &info_ptr);
1499 base64_stream.close();
1501 // Create repr
1502 Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image");
1503 sp_repr_set_svg_double(image_node, "width", 1);
1504 sp_repr_set_svg_double(image_node, "height", 1);
1505 // Set transformation
1506 if (_is_top_level) {
1507 svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1508 }
1510 // Create href
1511 if (embed_image) {
1512 // Append format specification to the URI
1513 Glib::ustring& png_data = base64_string.getString();
1514 png_data.insert(0, "data:image/png;base64,");
1515 image_node->setAttribute("xlink:href", png_data.c_str());
1516 } else {
1517 fclose(fp);
1518 image_node->setAttribute("xlink:href", file_name);
1519 g_free(file_name);
1520 }
1522 return image_node;
1523 }
1525 /**
1526 * \brief Creates a <mask> with the specified width and height and adds to <defs>
1527 * If we're not the top-level SvgBuilder, creates a <defs> too and adds the mask to it.
1528 * \return the created XML node
1529 */
1530 Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) {
1531 Inkscape::XML::Node *mask_node = _xml_doc->createElement("svg:mask");
1532 mask_node->setAttribute("maskUnits", "userSpaceOnUse");
1533 sp_repr_set_svg_double(mask_node, "x", 0.0);
1534 sp_repr_set_svg_double(mask_node, "y", 0.0);
1535 sp_repr_set_svg_double(mask_node, "width", width);
1536 sp_repr_set_svg_double(mask_node, "height", height);
1537 // Append mask to defs
1538 if (_is_top_level) {
1539 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(mask_node);
1540 Inkscape::GC::release(mask_node);
1541 return SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->lastChild();
1542 } else { // Work around for renderer bug when mask isn't defined in pattern
1543 static int mask_count = 0;
1544 Inkscape::XML::Node *defs = _root->firstChild();
1545 if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) {
1546 // Create <defs> node
1547 defs = _xml_doc->createElement("svg:defs");
1548 _root->addChild(defs, NULL);
1549 Inkscape::GC::release(defs);
1550 defs = _root->firstChild();
1551 }
1552 gchar *mask_id = g_strdup_printf("_mask%d", mask_count++);
1553 mask_node->setAttribute("id", mask_id);
1554 g_free(mask_id);
1555 defs->appendChild(mask_node);
1556 Inkscape::GC::release(mask_node);
1557 return defs->lastChild();
1558 }
1559 }
1561 void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height,
1562 GfxImageColorMap *color_map, int *mask_colors) {
1564 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, mask_colors);
1565 if (image_node) {
1566 _container->appendChild(image_node);
1567 Inkscape::GC::release(image_node);
1568 }
1569 }
1571 void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height,
1572 bool invert) {
1574 // Create a rectangle
1575 Inkscape::XML::Node *rect = _xml_doc->createElement("svg:rect");
1576 sp_repr_set_svg_double(rect, "x", 0.0);
1577 sp_repr_set_svg_double(rect, "y", 0.0);
1578 sp_repr_set_svg_double(rect, "width", 1.0);
1579 sp_repr_set_svg_double(rect, "height", 1.0);
1580 svgSetTransform(rect, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1581 // Get current fill style and set it on the rectangle
1582 SPCSSAttr *css = sp_repr_css_attr_new();
1583 _setFillStyle(css, state, false);
1584 sp_repr_css_change(rect, css, "style");
1585 sp_repr_css_attr_unref(css);
1587 // Scaling 1x1 surfaces might not work so skip setting a mask with this size
1588 if ( width > 1 || height > 1 ) {
1589 Inkscape::XML::Node *mask_image_node = _createImage(str, width, height, NULL, NULL, true, invert);
1590 if (mask_image_node) {
1591 // Create the mask
1592 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1593 // Remove unnecessary transformation from the mask image
1594 mask_image_node->setAttribute("transform", NULL);
1595 mask_node->appendChild(mask_image_node);
1596 Inkscape::GC::release(mask_image_node);
1597 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1598 rect->setAttribute("mask", mask_url);
1599 g_free(mask_url);
1600 }
1601 }
1603 // Add the rectangle to the container
1604 _container->appendChild(rect);
1605 Inkscape::GC::release(rect);
1606 }
1608 void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int height,
1609 GfxImageColorMap *color_map,
1610 Stream *mask_str, int mask_width, int mask_height,
1611 bool invert_mask) {
1613 Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1614 NULL, NULL, true, invert_mask);
1615 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1616 if ( mask_image_node && image_node ) {
1617 // Create mask for the image
1618 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1619 // Remove unnecessary transformation from the mask image
1620 mask_image_node->setAttribute("transform", NULL);
1621 mask_node->appendChild(mask_image_node);
1622 // Scale the mask to the size of the image
1623 NR::Matrix mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
1624 gchar *transform_text = sp_svg_transform_write(mask_transform);
1625 mask_node->setAttribute("maskTransform", transform_text);
1626 g_free(transform_text);
1627 // Set mask and add image
1628 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1629 image_node->setAttribute("mask", mask_url);
1630 g_free(mask_url);
1631 _container->appendChild(image_node);
1632 }
1633 if (mask_image_node) {
1634 Inkscape::GC::release(mask_image_node);
1635 }
1636 if (image_node) {
1637 Inkscape::GC::release(image_node);
1638 }
1639 }
1641 void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int height,
1642 GfxImageColorMap *color_map,
1643 Stream *mask_str, int mask_width, int mask_height,
1644 GfxImageColorMap *mask_color_map) {
1646 Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1647 mask_color_map, NULL, true);
1648 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1649 if ( mask_image_node && image_node ) {
1650 // Create mask for the image
1651 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1652 // Remove unnecessary transformation from the mask image
1653 mask_image_node->setAttribute("transform", NULL);
1654 mask_node->appendChild(mask_image_node);
1655 // Set mask and add image
1656 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1657 image_node->setAttribute("mask", mask_url);
1658 g_free(mask_url);
1659 _container->appendChild(image_node);
1660 }
1661 if (mask_image_node) {
1662 Inkscape::GC::release(mask_image_node);
1663 }
1664 if (image_node) {
1665 Inkscape::GC::release(image_node);
1666 }
1667 }
1669 /**
1670 * \brief Starts building a new transparency group
1671 */
1672 void SvgBuilder::pushTransparencyGroup(GfxState *state, double *bbox,
1673 GfxColorSpace *blending_color_space,
1674 bool isolated, bool knockout,
1675 bool for_softmask) {
1677 // Push node stack
1678 pushNode("svg:g");
1680 // Setup new transparency group
1681 SvgTransparencyGroup *transpGroup = new SvgTransparencyGroup;
1682 memcpy(&transpGroup->bbox, bbox, sizeof(bbox));
1683 transpGroup->isolated = isolated;
1684 transpGroup->knockout = knockout;
1685 transpGroup->for_softmask = for_softmask;
1686 transpGroup->container = _container;
1688 // Push onto the stack
1689 transpGroup->next = _transp_group_stack;
1690 _transp_group_stack = transpGroup;
1691 }
1693 void SvgBuilder::popTransparencyGroup(GfxState *state) {
1694 // Restore node stack
1695 popNode();
1696 }
1698 /**
1699 * \brief Places the current transparency group into the current container
1700 */
1701 void SvgBuilder::paintTransparencyGroup(GfxState *state, double *bbox) {
1702 SvgTransparencyGroup *transpGroup = _transp_group_stack;
1703 _container->appendChild(transpGroup->container);
1704 Inkscape::GC::release(transpGroup->container);
1705 // Pop the stack
1706 _transp_group_stack = transpGroup->next;
1707 delete transpGroup;
1708 }
1710 /**
1711 * \brief Creates a mask using the current transparency group as its content
1712 */
1713 void SvgBuilder::setSoftMask(GfxState *state, double *bbox, bool alpha,
1714 Function *transfer_func, GfxColor *backdrop_color) {
1716 // Create mask
1717 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1718 // Add the softmask content to it
1719 SvgTransparencyGroup *transpGroup = _transp_group_stack;
1720 mask_node->appendChild(transpGroup->container);
1721 Inkscape::GC::release(transpGroup->container);
1722 // Apply the mask
1723 _state_stack.back().softmask = mask_node;
1724 pushGroup();
1725 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1726 _container->setAttribute("mask", mask_url);
1727 g_free(mask_url);
1728 // Pop the stack
1729 _transp_group_stack = transpGroup->next;
1730 delete transpGroup;
1731 }
1733 void SvgBuilder::clearSoftMask(GfxState *state) {
1734 if (_state_stack.back().softmask) {
1735 _state_stack.back().softmask = NULL;
1736 popGroup();
1737 }
1738 }
1740 } } } /* namespace Inkscape, Extension, Internal */
1742 #endif /* HAVE_POPPLER */
1744 /*
1745 Local Variables:
1746 mode:c++
1747 c-file-style:"stroustrup"
1748 c-file-offsets:((innamespace . 0)(inline-open . 0))
1749 indent-tabs-mode:nil
1750 fill-column:99
1751 End:
1752 */
1753 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :