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 // Avoid transforming a group with an already set clip-path
553 if ( _container->attribute("clip-path") != NULL ) {
554 pushGroup();
555 }
556 TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
557 svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
558 }
560 void SvgBuilder::setTransform(double const *transform) {
561 setTransform(transform[0], transform[1], transform[2], transform[3],
562 transform[4], transform[5]);
563 }
565 /**
566 * \brief Checks whether the given pattern type can be represented in SVG
567 * Used by PdfParser to decide when to do fallback operations.
568 */
569 bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) {
570 if ( pattern != NULL ) {
571 if ( pattern->getType() == 2 ) { // shading pattern
572 GfxShading *shading = ((GfxShadingPattern *)pattern)->getShading();
573 int shadingType = shading->getType();
574 if ( shadingType == 2 || // axial shading
575 shadingType == 3 ) { // radial shading
576 return true;
577 }
578 return false;
579 } else if ( pattern->getType() == 1 ) { // tiling pattern
580 return true;
581 }
582 }
584 return false;
585 }
587 /**
588 * \brief Creates a pattern from poppler's data structure
589 * Handles linear and radial gradients. Creates a new PdfParser and uses it to
590 * build a tiling pattern.
591 * \return an url pointing to the created pattern
592 */
593 gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) {
594 gchar *id = NULL;
595 if ( pattern != NULL ) {
596 if ( pattern->getType() == 2 ) { // Shading pattern
597 GfxShadingPattern *shading_pattern = (GfxShadingPattern*)pattern;
598 id = _createGradient(shading_pattern->getShading(),
599 shading_pattern->getMatrix());
600 } else if ( pattern->getType() == 1 ) { // Tiling pattern
601 id = _createTilingPattern((GfxTilingPattern*)pattern, state, is_stroke);
602 }
603 } else {
604 return NULL;
605 }
606 gchar *urltext = g_strdup_printf ("url(#%s)", id);
607 g_free(id);
608 return urltext;
609 }
611 /**
612 * \brief Creates a tiling pattern from poppler's data structure
613 * Creates a sub-page PdfParser and uses it to parse the pattern's content stream.
614 * \return id of the created pattern
615 */
616 gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
617 GfxState *state, bool is_stroke) {
619 Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
620 // Set pattern transform matrix
621 double *p2u = tiling_pattern->getMatrix();
622 NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
623 gchar *transform_text = sp_svg_transform_write(pat_matrix);
624 pattern_node->setAttribute("patternTransform", transform_text);
625 g_free(transform_text);
626 pattern_node->setAttribute("patternUnits", "userSpaceOnUse");
627 // Set pattern tiling
628 // FIXME: don't ignore XStep and YStep
629 double *bbox = tiling_pattern->getBBox();
630 sp_repr_set_svg_double(pattern_node, "x", 0.0);
631 sp_repr_set_svg_double(pattern_node, "y", 0.0);
632 sp_repr_set_svg_double(pattern_node, "width", bbox[2] - bbox[0]);
633 sp_repr_set_svg_double(pattern_node, "height", bbox[3] - bbox[1]);
635 // Convert BBox for PdfParser
636 PDFRectangle box;
637 box.x1 = bbox[0];
638 box.y1 = bbox[1];
639 box.x2 = bbox[2];
640 box.y2 = bbox[3];
641 // Create new SvgBuilder and sub-page PdfParser
642 SvgBuilder *pattern_builder = new SvgBuilder(this, pattern_node);
643 PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(),
644 &box);
645 // Get pattern color space
646 GfxPatternColorSpace *pat_cs = (GfxPatternColorSpace *)( is_stroke ? state->getStrokeColorSpace()
647 : state->getFillColorSpace() );
648 // Set fill/stroke colors if this is an uncolored tiling pattern
649 GfxColorSpace *cs = NULL;
650 if ( tiling_pattern->getPaintType() == 2 && ( cs = pat_cs->getUnder() ) ) {
651 GfxState *pattern_state = pdf_parser->getState();
652 pattern_state->setFillColorSpace(cs->copy());
653 pattern_state->setFillColor(state->getFillColor());
654 pattern_state->setStrokeColorSpace(cs->copy());
655 pattern_state->setStrokeColor(state->getFillColor());
656 }
658 // Generate the SVG pattern
659 pdf_parser->parse(tiling_pattern->getContentStream());
661 // Cleanup
662 delete pdf_parser;
663 delete pattern_builder;
665 // Append the pattern to defs
666 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(pattern_node);
667 gchar *id = g_strdup(pattern_node->attribute("id"));
668 Inkscape::GC::release(pattern_node);
670 return id;
671 }
673 /**
674 * \brief Creates a linear or radial gradient from poppler's data structure
675 * \param shading poppler's data structure for the shading
676 * \param matrix gradient transformation, can be null
677 * \param for_shading true if we're creating this for a shading operator; false otherwise
678 * \return id of the created object
679 */
680 gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for_shading) {
681 Inkscape::XML::Node *gradient;
682 Function *func;
683 int num_funcs;
684 bool extend0, extend1;
686 if ( shading->getType() == 2 ) { // Axial shading
687 gradient = _xml_doc->createElement("svg:linearGradient");
688 GfxAxialShading *axial_shading = (GfxAxialShading*)shading;
689 double x1, y1, x2, y2;
690 axial_shading->getCoords(&x1, &y1, &x2, &y2);
691 sp_repr_set_svg_double(gradient, "x1", x1);
692 sp_repr_set_svg_double(gradient, "y1", y1);
693 sp_repr_set_svg_double(gradient, "x2", x2);
694 sp_repr_set_svg_double(gradient, "y2", y2);
695 extend0 = axial_shading->getExtend0();
696 extend1 = axial_shading->getExtend1();
697 num_funcs = axial_shading->getNFuncs();
698 func = axial_shading->getFunc(0);
699 } else if (shading->getType() == 3) { // Radial shading
700 gradient = _xml_doc->createElement("svg:radialGradient");
701 GfxRadialShading *radial_shading = (GfxRadialShading*)shading;
702 double x1, y1, r1, x2, y2, r2;
703 radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2);
704 // FIXME: the inner circle's radius is ignored here
705 sp_repr_set_svg_double(gradient, "fx", x1);
706 sp_repr_set_svg_double(gradient, "fy", y1);
707 sp_repr_set_svg_double(gradient, "cx", x2);
708 sp_repr_set_svg_double(gradient, "cy", y2);
709 sp_repr_set_svg_double(gradient, "r", r2);
710 extend0 = radial_shading->getExtend0();
711 extend1 = radial_shading->getExtend1();
712 num_funcs = radial_shading->getNFuncs();
713 func = radial_shading->getFunc(0);
714 } else { // Unsupported shading type
715 return NULL;
716 }
717 gradient->setAttribute("gradientUnits", "userSpaceOnUse");
718 // If needed, flip the gradient transform around the y axis
719 if (matrix) {
720 NR::Matrix pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3],
721 matrix[4], matrix[5]);
722 if ( !for_shading && _is_top_level ) {
723 NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
724 pat_matrix *= flip;
725 }
726 gchar *transform_text = sp_svg_transform_write(pat_matrix);
727 gradient->setAttribute("gradientTransform", transform_text);
728 g_free(transform_text);
729 }
731 if ( extend0 && extend1 ) {
732 gradient->setAttribute("spreadMethod", "pad");
733 }
735 if ( num_funcs > 1 || !_addGradientStops(gradient, shading, func) ) {
736 Inkscape::GC::release(gradient);
737 return NULL;
738 }
740 Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc));
741 defs->appendChild(gradient);
742 gchar *id = g_strdup(gradient->attribute("id"));
743 Inkscape::GC::release(gradient);
745 return id;
746 }
748 #define EPSILON 0.0001
749 /**
750 * \brief Adds a stop with the given properties to the gradient's representation
751 */
752 void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset,
753 GfxRGB *color, double opacity) {
754 Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
755 SPCSSAttr *css = sp_repr_css_attr_new();
756 Inkscape::CSSOStringStream os_opacity;
757 gchar *color_text = NULL;
758 if ( _transp_group_stack != NULL && _transp_group_stack->for_softmask ) {
759 double gray = (double)color->r / 65535.0;
760 gray = CLAMP(gray, 0.0, 1.0);
761 os_opacity << gray;
762 color_text = "#ffffff";
763 } else {
764 os_opacity << opacity;
765 color_text = svgConvertGfxRGB(color);
766 }
767 sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
768 sp_repr_css_set_property(css, "stop-color", color_text);
770 sp_repr_css_change(stop, css, "style");
771 sp_repr_css_attr_unref(css);
772 sp_repr_set_css_double(stop, "offset", offset);
774 gradient->appendChild(stop);
775 Inkscape::GC::release(stop);
776 }
778 static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *result) {
779 GfxColorSpace *color_space = shading->getColorSpace();
780 GfxColor temp;
781 if ( shading->getType() == 2 ) { // Axial shading
782 ((GfxAxialShading*)shading)->getColor(offset, &temp);
783 } else if ( shading->getType() == 3 ) { // Radial shading
784 ((GfxRadialShading*)shading)->getColor(offset, &temp);
785 } else {
786 return false;
787 }
788 // Convert it to RGB
789 color_space->getRGB(&temp, result);
791 return true;
792 }
794 #define INT_EPSILON 8
795 bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading,
796 Function *func) {
797 int type = func->getType();
798 if ( type == 0 || type == 2 ) { // Sampled or exponential function
799 GfxRGB stop1, stop2;
800 if ( !svgGetShadingColorRGB(shading, 0.0, &stop1) ||
801 !svgGetShadingColorRGB(shading, 1.0, &stop2) ) {
802 return false;
803 } else {
804 _addStopToGradient(gradient, 0.0, &stop1, 1.0);
805 _addStopToGradient(gradient, 1.0, &stop2, 1.0);
806 }
807 } else if ( type == 3 ) { // Stitching
808 StitchingFunction *stitchingFunc = (StitchingFunction*)func;
809 double *bounds = stitchingFunc->getBounds();
810 int num_funcs = stitchingFunc->getNumFuncs();
811 // Add stops from all the stitched functions
812 for ( int i = 0 ; i < num_funcs ; i++ ) {
813 GfxRGB color;
814 svgGetShadingColorRGB(shading, bounds[i], &color);
815 bool is_continuation = false;
816 if ( i > 0 ) { // Compare to previous stop
817 GfxRGB prev_color;
818 svgGetShadingColorRGB(shading, bounds[i-1], &prev_color);
819 if ( abs(color.r - prev_color.r) < INT_EPSILON &&
820 abs(color.g - prev_color.g) < INT_EPSILON &&
821 abs(color.b - prev_color.b) < INT_EPSILON ) {
822 is_continuation = true;
823 }
824 }
825 // Add stops
826 if ( !is_continuation ) {
827 _addStopToGradient(gradient, bounds[i], &color, 1.0);
828 }
829 if ( is_continuation || ( i == num_funcs - 1 ) ) {
830 GfxRGB next_color;
831 svgGetShadingColorRGB(shading, bounds[i+1], &next_color);
832 _addStopToGradient(gradient, bounds[i+1], &next_color, 1.0);
833 }
834 }
835 } else { // Unsupported function type
836 return false;
837 }
839 return true;
840 }
842 /**
843 * \brief Sets _invalidated_style to true to indicate that styles have to be updated
844 * Used for text output when glyphs are buffered till a font change
845 */
846 void SvgBuilder::updateStyle(GfxState *state) {
847 if (_in_text_object) {
848 _invalidated_style = true;
849 _current_state = state;
850 }
851 }
853 /**
854 * This array holds info about translating font weight names to more or less CSS equivalents
855 */
856 static char *font_weight_translator[][2] = {
857 {"bold", "bold"},
858 {"light", "300"},
859 {"black", "900"},
860 {"heavy", "900"},
861 {"ultrabold", "800"},
862 {"extrabold", "800"},
863 {"demibold", "600"},
864 {"semibold", "600"},
865 {"medium", "500"},
866 {"book", "normal"},
867 {"regular", "normal"},
868 {"roman", "normal"},
869 {"normal", "normal"},
870 {"ultralight", "200"},
871 {"extralight", "200"},
872 {"thin", "100"}
873 };
875 /**
876 * \brief Updates _font_style according to the font set in parameter state
877 */
878 void SvgBuilder::updateFont(GfxState *state) {
880 TRACE(("updateFont()\n"));
881 _need_font_update = false;
882 updateTextMatrix(state); // Ensure that we have a text matrix built
884 if (_font_style) {
885 //sp_repr_css_attr_unref(_font_style);
886 }
887 _font_style = sp_repr_css_attr_new();
888 GfxFont *font = state->getFont();
889 // Store original name
890 if (font->getOrigName()) {
891 _font_specification = font->getOrigName()->getCString();
892 } else if (font->getName()) {
893 _font_specification = font->getName()->getCString();
894 } else {
895 _font_specification = "Arial";
896 }
898 // Prune the font name to get the correct font family name
899 // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic
900 char *font_family = NULL;
901 char *font_style = NULL;
902 char *font_style_lowercase = NULL;
903 char *plus_sign = strstr(_font_specification, "+");
904 if (plus_sign) {
905 font_family = g_strdup(plus_sign + 1);
906 _font_specification = plus_sign + 1;
907 } else {
908 font_family = g_strdup(_font_specification);
909 }
910 char *style_delim = NULL;
911 if ( ( style_delim = g_strrstr(font_family, "-") ) ||
912 ( style_delim = g_strrstr(font_family, ",") ) ) {
913 font_style = style_delim + 1;
914 font_style_lowercase = g_ascii_strdown(font_style, -1);
915 style_delim[0] = 0;
916 }
918 // Font family
919 if (font->getFamily()) {
920 sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
921 } else {
922 sp_repr_css_set_property(_font_style, "font-family", font_family);
923 }
925 // Font style
926 if (font->isItalic()) {
927 sp_repr_css_set_property(_font_style, "font-style", "italic");
928 } else if (font_style) {
929 if ( strstr(font_style_lowercase, "italic") ||
930 strstr(font_style_lowercase, "slanted") ) {
931 sp_repr_css_set_property(_font_style, "font-style", "italic");
932 } else if (strstr(font_style_lowercase, "oblique")) {
933 sp_repr_css_set_property(_font_style, "font-style", "oblique");
934 }
935 }
937 // Font variant -- default 'normal' value
938 sp_repr_css_set_property(_font_style, "font-variant", "normal");
940 // Font weight
941 GfxFont::Weight font_weight = font->getWeight();
942 char *css_font_weight = NULL;
943 if ( font_weight != GfxFont::WeightNotDefined ) {
944 if ( font_weight == GfxFont::W400 ) {
945 css_font_weight = "normal";
946 } else if ( font_weight == GfxFont::W700 ) {
947 css_font_weight = "bold";
948 } else {
949 gchar weight_num[4] = "100";
950 weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
951 sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num);
952 }
953 } else if (font_style) {
954 // Apply the font weight translations
955 int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) );
956 for ( int i = 0 ; i < num_translations ; i++ ) {
957 if (strstr(font_style_lowercase, font_weight_translator[i][0])) {
958 css_font_weight = font_weight_translator[i][1];
959 }
960 }
961 } else {
962 css_font_weight = "normal";
963 }
964 if (css_font_weight) {
965 sp_repr_css_set_property(_font_style, "font-weight", css_font_weight);
966 }
967 g_free(font_family);
968 if (font_style_lowercase) {
969 g_free(font_style_lowercase);
970 }
972 // Font stretch
973 GfxFont::Stretch font_stretch = font->getStretch();
974 gchar *stretch_value = NULL;
975 switch (font_stretch) {
976 case GfxFont::UltraCondensed:
977 stretch_value = "ultra-condensed";
978 break;
979 case GfxFont::ExtraCondensed:
980 stretch_value = "extra-condensed";
981 break;
982 case GfxFont::Condensed:
983 stretch_value = "condensed";
984 break;
985 case GfxFont::SemiCondensed:
986 stretch_value = "semi-condensed";
987 break;
988 case GfxFont::Normal:
989 stretch_value = "normal";
990 break;
991 case GfxFont::SemiExpanded:
992 stretch_value = "semi-expanded";
993 break;
994 case GfxFont::Expanded:
995 stretch_value = "expanded";
996 break;
997 case GfxFont::ExtraExpanded:
998 stretch_value = "extra-expanded";
999 break;
1000 case GfxFont::UltraExpanded:
1001 stretch_value = "ultra-expanded";
1002 break;
1003 default:
1004 break;
1005 }
1006 if ( stretch_value != NULL ) {
1007 sp_repr_css_set_property(_font_style, "font-stretch", stretch_value);
1008 }
1010 // Font size
1011 Inkscape::CSSOStringStream os_font_size;
1012 double css_font_size = _font_scaling * state->getFontSize();
1013 if ( font->getType() == fontType3 ) {
1014 double *font_matrix = font->getFontMatrix();
1015 if ( font_matrix[0] != 0.0 ) {
1016 css_font_size *= font_matrix[3] / font_matrix[0];
1017 }
1018 }
1019 os_font_size << css_font_size;
1020 sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
1022 // Writing mode
1023 if ( font->getWMode() == 0 ) {
1024 sp_repr_css_set_property(_font_style, "writing-mode", "lr");
1025 } else {
1026 sp_repr_css_set_property(_font_style, "writing-mode", "tb");
1027 }
1029 _current_font = font;
1030 _invalidated_style = true;
1031 }
1033 /**
1034 * \brief Shifts the current text position by the given amount (specified in text space)
1035 */
1036 void SvgBuilder::updateTextShift(GfxState *state, double shift) {
1037 double shift_value = -shift * 0.001 * fabs(state->getFontSize());
1038 if (state->getFont()->getWMode()) {
1039 _text_position[1] += shift_value;
1040 } else {
1041 _text_position[0] += shift_value;
1042 }
1043 }
1045 /**
1046 * \brief Updates current text position
1047 */
1048 void SvgBuilder::updateTextPosition(double tx, double ty) {
1049 NR::Point new_position(tx, ty);
1050 _text_position = new_position;
1051 }
1053 /**
1054 * \brief Flushes the buffered characters
1055 */
1056 void SvgBuilder::updateTextMatrix(GfxState *state) {
1057 _flushText();
1058 // Update text matrix
1059 double *text_matrix = state->getTextMat();
1060 double w_scale = sqrt( text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2] );
1061 double h_scale = sqrt( text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3] );
1062 double max_scale;
1063 if ( w_scale > h_scale ) {
1064 max_scale = w_scale;
1065 } else {
1066 max_scale = h_scale;
1067 }
1068 // Calculate new text matrix
1069 NR::Matrix new_text_matrix(text_matrix[0] * state->getHorizScaling(),
1070 text_matrix[1] * state->getHorizScaling(),
1071 -text_matrix[2], -text_matrix[3],
1072 0.0, 0.0);
1074 if ( fabs( max_scale - 1.0 ) > EPSILON ) {
1075 // Cancel out scaling by font size in text matrix
1076 for ( int i = 0 ; i < 4 ; i++ ) {
1077 new_text_matrix[i] /= max_scale;
1078 }
1079 }
1080 _text_matrix = new_text_matrix;
1081 _font_scaling = max_scale;
1082 }
1084 /**
1085 * \brief Writes the buffered characters to the SVG document
1086 */
1087 void SvgBuilder::_flushText() {
1088 // Ignore empty strings
1089 if ( _glyphs.size() < 1 ) {
1090 _glyphs.clear();
1091 return;
1092 }
1093 std::vector<SvgGlyph>::iterator i = _glyphs.begin();
1094 const SvgGlyph& first_glyph = (*i);
1095 int render_mode = first_glyph.render_mode;
1096 // Ignore invisible characters
1097 if ( render_mode == 3 ) {
1098 _glyphs.clear();
1099 return;
1100 }
1102 Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
1103 // Set text matrix
1104 NR::Matrix text_transform(_text_matrix);
1105 text_transform[4] = first_glyph.position[0];
1106 text_transform[5] = first_glyph.position[1];
1107 gchar *transform = sp_svg_transform_write(text_transform);
1108 text_node->setAttribute("transform", transform);
1109 g_free(transform);
1111 bool new_tspan = true;
1112 bool same_coords[2] = {true, true};
1113 NR::Point last_delta_pos;
1114 unsigned int glyphs_in_a_row = 0;
1115 Inkscape::XML::Node *tspan_node = NULL;
1116 Glib::ustring x_coords;
1117 Glib::ustring y_coords;
1118 Glib::ustring text_buffer;
1120 // Output all buffered glyphs
1121 while (1) {
1122 const SvgGlyph& glyph = (*i);
1123 std::vector<SvgGlyph>::iterator prev_iterator = i - 1;
1124 // Check if we need to make a new tspan
1125 if (glyph.style_changed) {
1126 new_tspan = true;
1127 } else if ( i != _glyphs.begin() ) {
1128 const SvgGlyph& prev_glyph = (*prev_iterator);
1129 if ( !( ( glyph.dy == 0.0 && prev_glyph.dy == 0.0 &&
1130 glyph.text_position[1] == prev_glyph.text_position[1] ) ||
1131 ( glyph.dx == 0.0 && prev_glyph.dx == 0.0 &&
1132 glyph.text_position[0] == prev_glyph.text_position[0] ) ) ) {
1133 new_tspan = true;
1134 }
1135 }
1137 // Create tspan node if needed
1138 if ( new_tspan || i == _glyphs.end() ) {
1139 if (tspan_node) {
1140 // Set the x and y coordinate arrays
1141 if ( same_coords[0] ) {
1142 sp_repr_set_svg_double(tspan_node, "x", last_delta_pos[0]);
1143 } else {
1144 tspan_node->setAttribute("x", x_coords.c_str());
1145 }
1146 if ( same_coords[1] ) {
1147 sp_repr_set_svg_double(tspan_node, "y", last_delta_pos[1]);
1148 } else {
1149 tspan_node->setAttribute("y", y_coords.c_str());
1150 }
1151 TRACE(("tspan content: %s\n", text_buffer.c_str()));
1152 if ( glyphs_in_a_row > 1 ) {
1153 tspan_node->setAttribute("sodipodi:role", "line");
1154 }
1155 // Add text content node to tspan
1156 Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str());
1157 tspan_node->appendChild(text_content);
1158 Inkscape::GC::release(text_content);
1159 text_node->appendChild(tspan_node);
1160 // Clear temporary buffers
1161 x_coords.clear();
1162 y_coords.clear();
1163 text_buffer.clear();
1164 Inkscape::GC::release(tspan_node);
1165 glyphs_in_a_row = 0;
1166 }
1167 if ( i == _glyphs.end() ) {
1168 sp_repr_css_attr_unref((*prev_iterator).style);
1169 break;
1170 } else {
1171 tspan_node = _xml_doc->createElement("svg:tspan");
1172 tspan_node->setAttribute("inkscape:font-specification", glyph.font_specification);
1173 // Set style and unref SPCSSAttr if it won't be needed anymore
1174 sp_repr_css_change(tspan_node, glyph.style, "style");
1175 if ( glyph.style_changed && i != _glyphs.begin() ) { // Free previous style
1176 sp_repr_css_attr_unref((*prev_iterator).style);
1177 }
1178 }
1179 new_tspan = false;
1180 }
1181 if ( glyphs_in_a_row > 0 ) {
1182 x_coords.append(" ");
1183 y_coords.append(" ");
1184 // Check if we have the same coordinates
1185 const SvgGlyph& prev_glyph = (*prev_iterator);
1186 for ( int p = 0 ; p < 2 ; p++ ) {
1187 if ( glyph.text_position[p] != prev_glyph.text_position[p] ) {
1188 same_coords[p] = false;
1189 }
1190 }
1191 }
1192 // Append the coordinates to their respective strings
1193 NR::Point delta_pos( glyph.text_position - first_glyph.text_position );
1194 delta_pos[1] += glyph.rise;
1195 delta_pos[1] *= -1.0; // flip it
1196 delta_pos *= _font_scaling;
1197 Inkscape::CSSOStringStream os_x;
1198 os_x << delta_pos[0];
1199 x_coords.append(os_x.str());
1200 Inkscape::CSSOStringStream os_y;
1201 os_y << delta_pos[1];
1202 y_coords.append(os_y.str());
1203 last_delta_pos = delta_pos;
1205 // Append the character to the text buffer
1206 text_buffer.append((char *)&glyph.code, 1);
1208 glyphs_in_a_row++;
1209 i++;
1210 }
1211 _container->appendChild(text_node);
1212 Inkscape::GC::release(text_node);
1214 _glyphs.clear();
1215 }
1217 void SvgBuilder::beginString(GfxState *state, GooString *s) {
1218 if (_need_font_update) {
1219 updateFont(state);
1220 }
1221 IFTRACE(double *m = state->getTextMat());
1222 TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1223 IFTRACE(m = state->getCTM());
1224 TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1225 }
1227 /**
1228 * \brief Adds the specified character to the text buffer
1229 * Takes care of converting it to UTF-8 and generates a new style repr if style
1230 * has changed since the last call.
1231 */
1232 void SvgBuilder::addChar(GfxState *state, double x, double y,
1233 double dx, double dy,
1234 double originX, double originY,
1235 CharCode code, int nBytes, Unicode *u, int uLen) {
1238 bool is_space = ( uLen == 1 && u[0] == 32 );
1239 // Skip beginning space
1240 if ( is_space && _glyphs.size() < 1 ) {
1241 NR::Point delta(dx, dy);
1242 _text_position += delta;
1243 return;
1244 }
1245 // Allow only one space in a row
1246 if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 &&
1247 _glyphs[_glyphs.size() - 1].code[0] == 32 ) {
1248 NR::Point delta(dx, dy);
1249 _text_position += delta;
1250 return;
1251 }
1253 SvgGlyph new_glyph;
1254 new_glyph.is_space = is_space;
1255 new_glyph.position = NR::Point( x - originX, y - originY );
1256 new_glyph.text_position = _text_position;
1257 new_glyph.dx = dx;
1258 new_glyph.dy = dy;
1259 NR::Point delta(dx, dy);
1260 _text_position += delta;
1262 // Convert the character to UTF-8 since that's our SVG document's encoding
1263 static UnicodeMap *u_map = NULL;
1264 if ( u_map == NULL ) {
1265 GooString *enc = new GooString("UTF-8");
1266 u_map = globalParams->getUnicodeMap(enc);
1267 u_map->incRefCnt();
1268 delete enc;
1269 }
1270 int code_size = 0;
1271 for ( int i = 0 ; i < uLen ; i++ ) {
1272 code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size);
1273 }
1274 new_glyph.code_size = code_size;
1276 // Copy current style if it has changed since the previous glyph
1277 if (_invalidated_style || _glyphs.size() == 0 ) {
1278 new_glyph.style_changed = true;
1279 int render_mode = state->getRender();
1280 // Set style
1281 bool has_fill = !( render_mode & 1 );
1282 bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2;
1283 new_glyph.style = _setStyle(state, has_fill, has_stroke);
1284 new_glyph.render_mode = render_mode;
1285 sp_repr_css_merge(new_glyph.style, _font_style); // Merge with font style
1286 _invalidated_style = false;
1287 } else {
1288 new_glyph.style_changed = false;
1289 // Point to previous glyph's style information
1290 const SvgGlyph& prev_glyph = _glyphs.back();
1291 new_glyph.style = prev_glyph.style;
1292 new_glyph.render_mode = prev_glyph.render_mode;
1293 }
1294 new_glyph.font_specification = _font_specification;
1295 new_glyph.rise = state->getRise();
1297 _glyphs.push_back(new_glyph);
1298 }
1300 void SvgBuilder::endString(GfxState *state) {
1301 }
1303 void SvgBuilder::beginTextObject(GfxState *state) {
1304 _in_text_object = true;
1305 _invalidated_style = true; // Force copying of current state
1306 _current_state = state;
1307 }
1309 void SvgBuilder::endTextObject(GfxState *state) {
1310 _flushText();
1311 // TODO: clip if render_mode >= 4
1312 _in_text_object = false;
1313 }
1315 /**
1316 * Helper functions for supporting direct PNG output into a base64 encoded stream
1317 */
1318 void png_write_base64stream(png_structp png_ptr, png_bytep data, png_size_t length)
1319 {
1320 Inkscape::IO::Base64OutputStream *stream =
1321 (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1322 for ( unsigned i = 0 ; i < length ; i++ ) {
1323 stream->put((int)data[i]);
1324 }
1325 }
1327 void png_flush_base64stream(png_structp png_ptr)
1328 {
1329 Inkscape::IO::Base64OutputStream *stream =
1330 (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1331 stream->flush();
1332 }
1334 /**
1335 * \brief Creates an <image> element containing the given ImageStream as a PNG
1336 *
1337 */
1338 Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height,
1339 GfxImageColorMap *color_map, int *mask_colors, bool alpha_only, bool invert_alpha) {
1341 // Create PNG write struct
1342 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1343 if ( png_ptr == NULL ) {
1344 return NULL;
1345 }
1346 // Create PNG info struct
1347 png_infop info_ptr = png_create_info_struct(png_ptr);
1348 if ( info_ptr == NULL ) {
1349 png_destroy_write_struct(&png_ptr, NULL);
1350 return NULL;
1351 }
1352 // Set error handler
1353 if (setjmp(png_ptr->jmpbuf)) {
1354 png_destroy_write_struct(&png_ptr, &info_ptr);
1355 return NULL;
1356 }
1357 // Decide whether we should embed this image
1358 double attr_value = 1.0;
1359 sp_repr_get_double(_preferences, "embedImages", &attr_value);
1360 bool embed_image = ( attr_value != 0.0 );
1361 // Set read/write functions
1362 Inkscape::IO::StringOutputStream base64_string;
1363 Inkscape::IO::Base64OutputStream base64_stream(base64_string);
1364 FILE *fp = NULL;
1365 gchar *file_name = NULL;
1366 if (embed_image) {
1367 base64_stream.setColumnWidth(0); // Disable line breaks
1368 png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream);
1369 } else {
1370 static int counter = 0;
1371 file_name = g_strdup_printf("%s_img%d.png", _docname, counter++);
1372 fp = fopen(file_name, "wb");
1373 if ( fp == NULL ) {
1374 png_destroy_write_struct(&png_ptr, &info_ptr);
1375 g_free(file_name);
1376 return NULL;
1377 }
1378 png_init_io(png_ptr, fp);
1379 }
1381 // Set header data
1382 if ( !invert_alpha && !alpha_only ) {
1383 png_set_invert_alpha(png_ptr);
1384 }
1385 png_color_8 sig_bit;
1386 if (alpha_only) {
1387 png_set_IHDR(png_ptr, info_ptr,
1388 width,
1389 height,
1390 8, /* bit_depth */
1391 PNG_COLOR_TYPE_GRAY,
1392 PNG_INTERLACE_NONE,
1393 PNG_COMPRESSION_TYPE_BASE,
1394 PNG_FILTER_TYPE_BASE);
1395 sig_bit.red = 0;
1396 sig_bit.green = 0;
1397 sig_bit.blue = 0;
1398 sig_bit.gray = 8;
1399 sig_bit.alpha = 0;
1400 } else {
1401 png_set_IHDR(png_ptr, info_ptr,
1402 width,
1403 height,
1404 8, /* bit_depth */
1405 PNG_COLOR_TYPE_RGB_ALPHA,
1406 PNG_INTERLACE_NONE,
1407 PNG_COMPRESSION_TYPE_BASE,
1408 PNG_FILTER_TYPE_BASE);
1409 sig_bit.red = 8;
1410 sig_bit.green = 8;
1411 sig_bit.blue = 8;
1412 sig_bit.alpha = 8;
1413 }
1414 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
1415 png_set_bgr(png_ptr);
1416 // Write the file header
1417 png_write_info(png_ptr, info_ptr);
1419 // Convert pixels
1420 ImageStream *image_stream;
1421 if (alpha_only) {
1422 if (color_map) {
1423 image_stream = new ImageStream(str, width, color_map->getNumPixelComps(),
1424 color_map->getBits());
1425 } else {
1426 image_stream = new ImageStream(str, width, 1, 1);
1427 }
1428 image_stream->reset();
1430 // Convert grayscale values
1431 unsigned char *buffer = new unsigned char[width];
1432 int invert_bit = invert_alpha ? 1 : 0;
1433 for ( int y = 0 ; y < height ; y++ ) {
1434 unsigned char *row = image_stream->getLine();
1435 if (color_map) {
1436 color_map->getGrayLine(row, buffer, width);
1437 } else {
1438 unsigned char *buf_ptr = buffer;
1439 for ( int x = 0 ; x < width ; x++ ) {
1440 if ( row[x] ^ invert_bit ) {
1441 *buf_ptr++ = 0;
1442 } else {
1443 *buf_ptr++ = 255;
1444 }
1445 }
1446 }
1447 png_write_row(png_ptr, (png_bytep)buffer);
1448 }
1449 delete buffer;
1450 } else if (color_map) {
1451 image_stream = new ImageStream(str, width,
1452 color_map->getNumPixelComps(),
1453 color_map->getBits());
1454 image_stream->reset();
1456 // Convert RGB values
1457 unsigned int *buffer = new unsigned int[width];
1458 if (mask_colors) {
1459 for ( int y = 0 ; y < height ; y++ ) {
1460 unsigned char *row = image_stream->getLine();
1461 color_map->getRGBLine(row, buffer, width);
1463 unsigned int *dest = buffer;
1464 for ( int x = 0 ; x < width ; x++ ) {
1465 // Check each color component against the mask
1466 for ( int i = 0; i < color_map->getNumPixelComps() ; i++) {
1467 if ( row[i] < mask_colors[2*i] * 255 ||
1468 row[i] > mask_colors[2*i + 1] * 255 ) {
1469 *dest = *dest | 0xff000000;
1470 break;
1471 }
1472 }
1473 // Advance to the next pixel
1474 row += color_map->getNumPixelComps();
1475 dest++;
1476 }
1477 // Write it to the PNG
1478 png_write_row(png_ptr, (png_bytep)buffer);
1479 }
1480 } else {
1481 for ( int i = 0 ; i < height ; i++ ) {
1482 unsigned char *row = image_stream->getLine();
1483 memset((void*)buffer, 0xff, sizeof(int) * width);
1484 color_map->getRGBLine(row, buffer, width);
1485 png_write_row(png_ptr, (png_bytep)buffer);
1486 }
1487 }
1488 delete buffer;
1490 } else { // A colormap must be provided, so quit
1491 png_destroy_write_struct(&png_ptr, &info_ptr);
1492 if (!embed_image) {
1493 fclose(fp);
1494 g_free(file_name);
1495 }
1496 return NULL;
1497 }
1498 delete image_stream;
1499 str->close();
1500 // Close PNG
1501 png_write_end(png_ptr, info_ptr);
1502 png_destroy_write_struct(&png_ptr, &info_ptr);
1503 base64_stream.close();
1505 // Create repr
1506 Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image");
1507 sp_repr_set_svg_double(image_node, "width", 1);
1508 sp_repr_set_svg_double(image_node, "height", 1);
1509 // Set transformation
1510 if (_is_top_level) {
1511 svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1512 }
1514 // Create href
1515 if (embed_image) {
1516 // Append format specification to the URI
1517 Glib::ustring& png_data = base64_string.getString();
1518 png_data.insert(0, "data:image/png;base64,");
1519 image_node->setAttribute("xlink:href", png_data.c_str());
1520 } else {
1521 fclose(fp);
1522 image_node->setAttribute("xlink:href", file_name);
1523 g_free(file_name);
1524 }
1526 return image_node;
1527 }
1529 /**
1530 * \brief Creates a <mask> with the specified width and height and adds to <defs>
1531 * If we're not the top-level SvgBuilder, creates a <defs> too and adds the mask to it.
1532 * \return the created XML node
1533 */
1534 Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) {
1535 Inkscape::XML::Node *mask_node = _xml_doc->createElement("svg:mask");
1536 mask_node->setAttribute("maskUnits", "userSpaceOnUse");
1537 sp_repr_set_svg_double(mask_node, "x", 0.0);
1538 sp_repr_set_svg_double(mask_node, "y", 0.0);
1539 sp_repr_set_svg_double(mask_node, "width", width);
1540 sp_repr_set_svg_double(mask_node, "height", height);
1541 // Append mask to defs
1542 if (_is_top_level) {
1543 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(mask_node);
1544 Inkscape::GC::release(mask_node);
1545 return SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->lastChild();
1546 } else { // Work around for renderer bug when mask isn't defined in pattern
1547 static int mask_count = 0;
1548 Inkscape::XML::Node *defs = _root->firstChild();
1549 if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) {
1550 // Create <defs> node
1551 defs = _xml_doc->createElement("svg:defs");
1552 _root->addChild(defs, NULL);
1553 Inkscape::GC::release(defs);
1554 defs = _root->firstChild();
1555 }
1556 gchar *mask_id = g_strdup_printf("_mask%d", mask_count++);
1557 mask_node->setAttribute("id", mask_id);
1558 g_free(mask_id);
1559 defs->appendChild(mask_node);
1560 Inkscape::GC::release(mask_node);
1561 return defs->lastChild();
1562 }
1563 }
1565 void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height,
1566 GfxImageColorMap *color_map, int *mask_colors) {
1568 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, mask_colors);
1569 if (image_node) {
1570 _container->appendChild(image_node);
1571 Inkscape::GC::release(image_node);
1572 }
1573 }
1575 void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height,
1576 bool invert) {
1578 // Create a rectangle
1579 Inkscape::XML::Node *rect = _xml_doc->createElement("svg:rect");
1580 sp_repr_set_svg_double(rect, "x", 0.0);
1581 sp_repr_set_svg_double(rect, "y", 0.0);
1582 sp_repr_set_svg_double(rect, "width", 1.0);
1583 sp_repr_set_svg_double(rect, "height", 1.0);
1584 svgSetTransform(rect, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1585 // Get current fill style and set it on the rectangle
1586 SPCSSAttr *css = sp_repr_css_attr_new();
1587 _setFillStyle(css, state, false);
1588 sp_repr_css_change(rect, css, "style");
1589 sp_repr_css_attr_unref(css);
1591 // Scaling 1x1 surfaces might not work so skip setting a mask with this size
1592 if ( width > 1 || height > 1 ) {
1593 Inkscape::XML::Node *mask_image_node = _createImage(str, width, height, NULL, NULL, true, invert);
1594 if (mask_image_node) {
1595 // Create the mask
1596 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1597 // Remove unnecessary transformation from the mask image
1598 mask_image_node->setAttribute("transform", NULL);
1599 mask_node->appendChild(mask_image_node);
1600 Inkscape::GC::release(mask_image_node);
1601 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1602 rect->setAttribute("mask", mask_url);
1603 g_free(mask_url);
1604 }
1605 }
1607 // Add the rectangle to the container
1608 _container->appendChild(rect);
1609 Inkscape::GC::release(rect);
1610 }
1612 void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int height,
1613 GfxImageColorMap *color_map,
1614 Stream *mask_str, int mask_width, int mask_height,
1615 bool invert_mask) {
1617 Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1618 NULL, NULL, true, invert_mask);
1619 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1620 if ( mask_image_node && image_node ) {
1621 // Create mask for the image
1622 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1623 // Remove unnecessary transformation from the mask image
1624 mask_image_node->setAttribute("transform", NULL);
1625 mask_node->appendChild(mask_image_node);
1626 // Scale the mask to the size of the image
1627 NR::Matrix mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
1628 gchar *transform_text = sp_svg_transform_write(mask_transform);
1629 mask_node->setAttribute("maskTransform", transform_text);
1630 g_free(transform_text);
1631 // Set mask and add image
1632 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1633 image_node->setAttribute("mask", mask_url);
1634 g_free(mask_url);
1635 _container->appendChild(image_node);
1636 }
1637 if (mask_image_node) {
1638 Inkscape::GC::release(mask_image_node);
1639 }
1640 if (image_node) {
1641 Inkscape::GC::release(image_node);
1642 }
1643 }
1645 void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int height,
1646 GfxImageColorMap *color_map,
1647 Stream *mask_str, int mask_width, int mask_height,
1648 GfxImageColorMap *mask_color_map) {
1650 Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1651 mask_color_map, NULL, true);
1652 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1653 if ( mask_image_node && image_node ) {
1654 // Create mask for the image
1655 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1656 // Remove unnecessary transformation from the mask image
1657 mask_image_node->setAttribute("transform", NULL);
1658 mask_node->appendChild(mask_image_node);
1659 // Set mask and add image
1660 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1661 image_node->setAttribute("mask", mask_url);
1662 g_free(mask_url);
1663 _container->appendChild(image_node);
1664 }
1665 if (mask_image_node) {
1666 Inkscape::GC::release(mask_image_node);
1667 }
1668 if (image_node) {
1669 Inkscape::GC::release(image_node);
1670 }
1671 }
1673 /**
1674 * \brief Starts building a new transparency group
1675 */
1676 void SvgBuilder::pushTransparencyGroup(GfxState *state, double *bbox,
1677 GfxColorSpace *blending_color_space,
1678 bool isolated, bool knockout,
1679 bool for_softmask) {
1681 // Push node stack
1682 pushNode("svg:g");
1684 // Setup new transparency group
1685 SvgTransparencyGroup *transpGroup = new SvgTransparencyGroup;
1686 memcpy(&transpGroup->bbox, bbox, sizeof(bbox));
1687 transpGroup->isolated = isolated;
1688 transpGroup->knockout = knockout;
1689 transpGroup->for_softmask = for_softmask;
1690 transpGroup->container = _container;
1692 // Push onto the stack
1693 transpGroup->next = _transp_group_stack;
1694 _transp_group_stack = transpGroup;
1695 }
1697 void SvgBuilder::popTransparencyGroup(GfxState *state) {
1698 // Restore node stack
1699 popNode();
1700 }
1702 /**
1703 * \brief Places the current transparency group into the current container
1704 */
1705 void SvgBuilder::paintTransparencyGroup(GfxState *state, double *bbox) {
1706 SvgTransparencyGroup *transpGroup = _transp_group_stack;
1707 _container->appendChild(transpGroup->container);
1708 Inkscape::GC::release(transpGroup->container);
1709 // Pop the stack
1710 _transp_group_stack = transpGroup->next;
1711 delete transpGroup;
1712 }
1714 /**
1715 * \brief Creates a mask using the current transparency group as its content
1716 */
1717 void SvgBuilder::setSoftMask(GfxState *state, double *bbox, bool alpha,
1718 Function *transfer_func, GfxColor *backdrop_color) {
1720 // Create mask
1721 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1722 // Add the softmask content to it
1723 SvgTransparencyGroup *transpGroup = _transp_group_stack;
1724 mask_node->appendChild(transpGroup->container);
1725 Inkscape::GC::release(transpGroup->container);
1726 // Apply the mask
1727 _state_stack.back().softmask = mask_node;
1728 pushGroup();
1729 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1730 _container->setAttribute("mask", mask_url);
1731 g_free(mask_url);
1732 // Pop the stack
1733 _transp_group_stack = transpGroup->next;
1734 delete transpGroup;
1735 }
1737 void SvgBuilder::clearSoftMask(GfxState *state) {
1738 if (_state_stack.back().softmask) {
1739 _state_stack.back().softmask = NULL;
1740 popGroup();
1741 }
1742 }
1744 } } } /* namespace Inkscape, Extension, Internal */
1746 #endif /* HAVE_POPPLER */
1748 /*
1749 Local Variables:
1750 mode:c++
1751 c-file-style:"stroustrup"
1752 c-file-offsets:((innamespace . 0)(inline-open . 0))
1753 indent-tabs-mode:nil
1754 fill-column:99
1755 End:
1756 */
1757 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :