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