Code

Added support for exponential functions in gradients
[inkscape.git] / src / extension / internal / pdfinput / svg-builder.cpp
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  * \class SvgBuilder
60  * 
61  */
63 SvgBuilder::SvgBuilder() {
64     _in_text_object = false;
65     _need_font_update = true;
66     _invalidated_style = true;
67     _font_style = NULL;
68     _current_font = NULL;
69     _current_state = NULL;
70 }
72 SvgBuilder::SvgBuilder(SPDocument *document, gchar *docname, XRef *xref) {
73     _is_top_level = true;
74     _doc = document;
75     _docname = docname;
76     _xref = xref;
77     _xml_doc = sp_document_repr_doc(_doc);
78     _container = _root = _doc->rroot;
79     _root->setAttribute("xml:space", "preserve");
80     SvgBuilder();
81 }
83 SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) {
84     _is_top_level = false;
85     _doc = parent->_doc;
86     _docname = parent->_docname;
87     _xref = parent->_xref;
88     _xml_doc = parent->_xml_doc;
89     _container = this->_root = root;
90     SvgBuilder();
91 }
93 SvgBuilder::~SvgBuilder() {
94 }
96 void SvgBuilder::setDocumentSize(double width, double height) {
97     sp_repr_set_svg_double(_root, "width", width);
98     sp_repr_set_svg_double(_root, "height", height);
99     this->_width = width;
100     this->_height = height;
103 /**
104  * \brief Sets groupmode of the current container to 'layer' and sets its label if given
105  */
106 void SvgBuilder::setAsLayer(char *layer_name) {
107     _container->setAttribute("inkscape:groupmode", "layer");
108     if (layer_name) {
109         _container->setAttribute("inkscape:label", layer_name);
110     }
113 void SvgBuilder::saveState() {
114     _group_depth.push_back(0);
115     pushGroup();
118 void SvgBuilder::restoreState() {
119     while (_group_depth.back() > 0) {
120         popGroup();
121     }
122     _group_depth.pop_back();
125 Inkscape::XML::Node *SvgBuilder::pushGroup() {
126     Inkscape::XML::Node *node = _xml_doc->createElement("svg:g");
127     _container->appendChild(node);
128     _container = node;
129     Inkscape::GC::release(node);
130     _group_depth.back()++;
131     // Set as a layer if this is a top-level group
132     if ( _container->parent() == _root && _is_top_level ) {
133         static int layer_count = 1;
134         if ( layer_count > 1 ) {
135             gchar *layer_name = g_strdup_printf("%s%d", _docname, layer_count);
136             setAsLayer(layer_name);
137             g_free(layer_name);
138         } else {
139             setAsLayer(_docname);
140         }
141     }
143     return _container;
146 Inkscape::XML::Node *SvgBuilder::popGroup() {
147     if (_container != _root) {  // Pop if the current container isn't root
148         _container = _container->parent();
149         _group_depth[_group_depth.size()-1] = --_group_depth.back();
150     }
152     return _container;
155 Inkscape::XML::Node *SvgBuilder::getContainer() {
156     return _container;
159 static gchar *svgConvertRGBToText(double r, double g, double b) {
160     static gchar tmp[1023] = {0};
161     snprintf(tmp, 1023,
162              "#%02x%02x%02x",
163              CLAMP(SP_COLOR_F_TO_U(r), 0, 255),
164              CLAMP(SP_COLOR_F_TO_U(g), 0, 255),
165              CLAMP(SP_COLOR_F_TO_U(b), 0, 255));
166     return (gchar *)&tmp;
169 static gchar *svgConvertGfxRGB(GfxRGB *color) {
170     double r = color->r / 65535.0;
171     double g = color->g / 65535.0;
172     double b = color->b / 65535.0;
173     return svgConvertRGBToText(r, g, b);
176 static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1,
177                               double c2, double c3, double c4, double c5) {
178     NR::Matrix matrix(c0, c1, c2, c3, c4, c5);
179     gchar *transform_text = sp_svg_transform_write(matrix);
180     node->setAttribute("transform", transform_text);
181     g_free(transform_text);
184 static void svgSetTransform(Inkscape::XML::Node *node, double *transform) {
185     svgSetTransform(node, transform[0], transform[1], transform[2], transform[3],
186                     transform[4], transform[5]);
189 /**
190  * \brief Generates a SVG path string from poppler's data structure
191  */
192 static gchar *svgInterpretPath(GfxPath *path) {
193     GfxSubpath *subpath;
194     Inkscape::SVG::PathString pathString;
195     int i, j;
196     for ( i = 0 ; i < path->getNumSubpaths() ; ++i ) {
197         subpath = path->getSubpath(i);
198         if (subpath->getNumPoints() > 0) {
199             pathString.moveTo(subpath->getX(0), subpath->getY(0));
200             j = 1;
201             while (j < subpath->getNumPoints()) {
202                 if (subpath->getCurve(j)) {
203                     pathString.curveTo(subpath->getX(j), subpath->getY(j),
204                                        subpath->getX(j+1), subpath->getY(j+1),
205                                        subpath->getX(j+2), subpath->getY(j+2));
207                     j += 3;
208                 } else {
209                     pathString.lineTo(subpath->getX(j), subpath->getY(j));
210                     ++j;
211                 }
212             }
213             if (subpath->isClosed()) {
214                 pathString.closePath();
215             }
216         }
217     }
219     return g_strdup(pathString.c_str());
222 /**
223  * \brief Sets stroke style from poppler's GfxState data structure
224  * Uses the given SPCSSAttr for storing the style properties
225  */
226 void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) {
228     // Check line width
229     if ( state->getLineWidth() <= 0.0 ) {
230         // Ignore stroke
231         sp_repr_css_set_property(css, "stroke", "none");
232         return;
233     }
235     // Stroke color/pattern
236     if ( state->getStrokeColorSpace()->getMode() == csPattern ) {
237         gchar *urltext = _createPattern(state->getStrokePattern(), state, true);
238         sp_repr_css_set_property(css, "stroke", urltext);
239         if (urltext) {
240             g_free(urltext);
241         }
242     } else {
243         GfxRGB stroke_color;
244         state->getStrokeRGB(&stroke_color);
245         sp_repr_css_set_property(css, "stroke", svgConvertGfxRGB(&stroke_color));
246     }
248     // Opacity
249     Inkscape::CSSOStringStream os_opacity;
250     os_opacity << state->getStrokeOpacity();
251     sp_repr_css_set_property(css, "stroke-opacity", os_opacity.str().c_str());
253     // Line width
254     Inkscape::CSSOStringStream os_width;
255     os_width << state->getLineWidth();
256     sp_repr_css_set_property(css, "stroke-width", os_width.str().c_str());
258     // Line cap
259     switch (state->getLineCap()) {
260         case 0:
261             sp_repr_css_set_property(css, "stroke-linecap", "butt");
262             break;
263         case 1:
264             sp_repr_css_set_property(css, "stroke-linecap", "round");
265             break;
266         case 2:
267             sp_repr_css_set_property(css, "stroke-linecap", "square");
268             break;
269     }
271     // Line join
272     switch (state->getLineJoin()) {
273         case 0:
274             sp_repr_css_set_property(css, "stroke-linejoin", "miter");
275             break;
276         case 1:
277             sp_repr_css_set_property(css, "stroke-linejoin", "round");
278             break;
279         case 2:
280             sp_repr_css_set_property(css, "stroke-linejoin", "bevel");
281             break;
282     }
284     // Miterlimit
285     Inkscape::CSSOStringStream os_ml;
286     os_ml << state->getMiterLimit();
287     sp_repr_css_set_property(css, "stroke-miterlimit", os_ml.str().c_str());
289     // Line dash
290     double *dash_pattern;
291     int dash_length;
292     double dash_start;
293     state->getLineDash(&dash_pattern, &dash_length, &dash_start);
294     if ( dash_length > 0 ) {
295         Inkscape::CSSOStringStream os_array;
296         for ( int i = 0 ; i < dash_length ; i++ ) {
297             os_array << dash_pattern[i];
298             if (i < (dash_length - 1)) {
299                 os_array << ",";
300             }
301         }
302         sp_repr_css_set_property(css, "stroke-dasharray", os_array.str().c_str());
304         Inkscape::CSSOStringStream os_offset;
305         os_offset << dash_start;
306         sp_repr_css_set_property(css, "stroke-dashoffset", os_offset.str().c_str());
307     } else {
308         sp_repr_css_set_property(css, "stroke-dasharray", "none");
309         sp_repr_css_set_property(css, "stroke-dashoffset", NULL);
310     }
313 /**
314  * \brief Sets fill style from poppler's GfxState data structure
315  * Uses the given SPCSSAttr for storing the style properties.
316  */
317 void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) {
319     // Fill color/pattern
320     if ( state->getFillColorSpace()->getMode() == csPattern ) {
321         gchar *urltext = _createPattern(state->getFillPattern(), state);
322         sp_repr_css_set_property(css, "fill", urltext);
323         if (urltext) {
324             g_free(urltext);
325         }
326     } else {
327         GfxRGB fill_color;
328         state->getFillRGB(&fill_color);
329         sp_repr_css_set_property(css, "fill", svgConvertGfxRGB(&fill_color));
330     }
332     // Opacity
333     Inkscape::CSSOStringStream os_opacity;
334     os_opacity << state->getFillOpacity();
335     sp_repr_css_set_property(css, "fill-opacity", os_opacity.str().c_str());
336     
337     // Fill rule
338     sp_repr_css_set_property(css, "fill-rule", even_odd ? "evenodd" : "nonzero");
341 /**
342  * \brief Sets style properties from poppler's GfxState data structure
343  * \return SPCSSAttr with all the relevant properties set
344  */
345 SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) {
346     SPCSSAttr *css = sp_repr_css_attr_new();
347     if (fill) {
348         _setFillStyle(css, state, even_odd);
349     } else {
350         sp_repr_css_set_property(css, "fill", "none");
351     }
352     
353     if (stroke) {
354         _setStrokeStyle(css, state);
355     } else {
356         sp_repr_css_set_property(css, "stroke", "none");
357     }
359     return css;
362 /**
363  * \brief Emits the current path in poppler's GfxState data structure
364  * Can be used to do filling and stroking at once.
365  *
366  * \param fill whether the path should be filled
367  * \param stroke whether the path should be stroked
368  * \param even_odd whether the even-odd rule should be used when filling the path
369  */
370 void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) {
371     Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
372     gchar *pathtext = svgInterpretPath(state->getPath());
373     path->setAttribute("d", pathtext);
374     g_free(pathtext);
376     // Set style
377     SPCSSAttr *css = _setStyle(state, fill, stroke, even_odd);
378     sp_repr_css_change(path, css, "style");
379     sp_repr_css_attr_unref(css);
381     _container->appendChild(path);
382     Inkscape::GC::release(path);
385 /**
386  * \brief Clips to the current path set in GfxState
387  * \param state poppler's data structure
388  * \param even_odd whether the even-odd rule should be applied
389  */
390 void SvgBuilder::clip(GfxState *state, bool even_odd) {
391     pushGroup();
392     setClipPath(state, even_odd);
395 void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
396     // Create the clipPath repr
397     Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath");
398     clip_path->setAttribute("clipPathUnits", "userSpaceOnUse");
399     // Create the path
400     Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
401     gchar *pathtext = svgInterpretPath(state->getPath());
402     path->setAttribute("d", pathtext);
403     g_free(pathtext);
404     if (even_odd) {
405         path->setAttribute("clip-rule", "evenodd");
406     }
407     clip_path->appendChild(path);
408     Inkscape::GC::release(path);
409     // Append clipPath to defs and get id
410     SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(clip_path);
411     gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id"));
412     Inkscape::GC::release(clip_path);
413     _container->setAttribute("clip-path", urltext);
414     g_free(urltext);
417 /**
418  * \brief Fills the given array with the current container's transform, if set
419  * \param transform array of doubles to be filled
420  * \return true on success; false on invalid transformation
421  */
422 bool SvgBuilder::getTransform(double *transform) {
423     NR::Matrix svd;
424     gchar const *tr = _container->attribute("transform");
425     bool valid = sp_svg_transform_read(tr, &svd);
426     if (valid) {
427         for ( int i = 0 ; i < 6 ; i++ ) {
428             transform[i] = svd[i];
429         }
430         return true;
431     } else {
432         return false;
433     }
436 /**
437  * \brief Sets the transformation matrix of the current container
438  */
439 void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
440                               double c4, double c5) {
442     TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
443     svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
446 void SvgBuilder::setTransform(double *transform) {
447     setTransform(transform[0], transform[1], transform[2], transform[3],
448                  transform[4], transform[5]);
451 /**
452  * \brief Checks whether the given pattern type can be represented in SVG
453  * Used by PdfParser to decide when to do fallback operations.
454  */
455 bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) {
456     if ( pattern != NULL ) {
457         if ( pattern->getType() == 2 ) {    // shading pattern
458             GfxShading *shading = ((GfxShadingPattern *)pattern)->getShading();
459             int shadingType = shading->getType();
460             if ( shadingType == 2 || // axial shading
461                  shadingType == 3 ) {   // radial shading
462                 return true;
463             }
464             return false;
465         } else if ( pattern->getType() == 1 ) {   // tiling pattern
466             return true;
467         }
468     }
470     return false;
473 /**
474  * \brief Creates a pattern from poppler's data structure
475  * Handles linear and radial gradients. Creates a new PdfParser and uses it to
476  * build a tiling pattern.
477  * \return an url pointing to the created pattern
478  */
479 gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) {
480     gchar *id = NULL;
481     if ( pattern != NULL ) {
482         if ( pattern->getType() == 2 ) {  // Shading pattern
483             id = _createGradient((GfxShadingPattern*)pattern);
484         } else if ( pattern->getType() == 1 ) {   // Tiling pattern
485             id = _createTilingPattern((GfxTilingPattern*)pattern, state, is_stroke);
486         }
487     } else {
488         return NULL;
489     }
490     gchar *urltext = g_strdup_printf ("url(#%s)", id);
491     g_free(id);
492     return urltext;
495 /**
496  * \brief Creates a tiling pattern from poppler's data structure
497  * Creates a sub-page PdfParser and uses it to parse the pattern's content stream.
498  * \return id of the created pattern
499  */
500 gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
501                                         GfxState *state, bool is_stroke) {
503     Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
504     // Set pattern transform matrix
505     double *p2u = tiling_pattern->getMatrix();
506     NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
507     gchar *transform_text = sp_svg_transform_write(pat_matrix);
508     pattern_node->setAttribute("patternTransform", transform_text);
509     g_free(transform_text);
510     pattern_node->setAttribute("patternUnits", "userSpaceOnUse");
511     // Set pattern tiling
512     // FIXME: don't ignore XStep and YStep
513     double *bbox = tiling_pattern->getBBox();
514     sp_repr_set_svg_double(pattern_node, "x", 0.0);
515     sp_repr_set_svg_double(pattern_node, "y", 0.0);
516     sp_repr_set_svg_double(pattern_node, "width", bbox[2] - bbox[0]);
517     sp_repr_set_svg_double(pattern_node, "height", bbox[3] - bbox[1]);
519     // Convert BBox for PdfParser
520     PDFRectangle box;
521     box.x1 = bbox[0];
522     box.y1 = bbox[1];
523     box.x2 = bbox[2];
524     box.y2 = bbox[3];
525     // Create new SvgBuilder and sub-page PdfParser
526     SvgBuilder *pattern_builder = new SvgBuilder(this, pattern_node);
527     PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(),
528                                           &box);
529     // Get pattern color space
530     GfxPatternColorSpace *pat_cs = (GfxPatternColorSpace *)( is_stroke ? state->getStrokeColorSpace()
531                                                             : state->getFillColorSpace() );
532     // Set fill/stroke colors if this is an uncolored tiling pattern
533     GfxColorSpace *cs = NULL;
534     if ( tiling_pattern->getPaintType() == 2 && ( cs = pat_cs->getUnder() ) ) {
535         GfxState *pattern_state = pdf_parser->getState();
536         pattern_state->setFillColorSpace(cs->copy());
537         pattern_state->setFillColor(state->getFillColor());
538         pattern_state->setStrokeColorSpace(cs->copy());
539         pattern_state->setStrokeColor(state->getFillColor());
540     }
542     // Generate the SVG pattern
543     pdf_parser->parse(tiling_pattern->getContentStream());
545     // Cleanup
546     delete pdf_parser;
547     delete pattern_builder;
549     // Append the pattern to defs
550     SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(pattern_node);
551     gchar *id = g_strdup(pattern_node->attribute("id"));
552     Inkscape::GC::release(pattern_node);
554     return id;
557 /**
558  * \brief Creates a linear or radial gradient from poppler's data structure
559  * \return id of the created object
560  */
561 gchar *SvgBuilder::_createGradient(GfxShadingPattern *shading_pattern) {
562     GfxShading *shading = shading_pattern->getShading();
563     Inkscape::XML::Node *gradient;
564     Function *func;
565     int num_funcs;
566     bool extend0, extend1;
568     if ( shading->getType() == 2 ) {  // Axial shading
569         gradient = _xml_doc->createElement("svg:linearGradient");
570         GfxAxialShading *axial_shading = (GfxAxialShading*)shading;
571         double x1, y1, x2, y2;
572         axial_shading->getCoords(&x1, &y1, &x2, &y2);
573         sp_repr_set_svg_double(gradient, "x1", x1);
574         sp_repr_set_svg_double(gradient, "y1", y1);
575         sp_repr_set_svg_double(gradient, "x2", x2);
576         sp_repr_set_svg_double(gradient, "y2", y2);
577         extend0 = axial_shading->getExtend0();
578         extend1 = axial_shading->getExtend1();
579         num_funcs = axial_shading->getNFuncs();
580         func = axial_shading->getFunc(0);
581     } else if (shading->getType() == 3) {   // Radial shading
582         gradient = _xml_doc->createElement("svg:radialGradient");
583         GfxRadialShading *radial_shading = (GfxRadialShading*)shading;
584         double x1, y1, r1, x2, y2, r2;
585         radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2);
586         // FIXME: the inner circle's radius is ignored here
587         sp_repr_set_svg_double(gradient, "fx", x1);
588         sp_repr_set_svg_double(gradient, "fy", y1);
589         sp_repr_set_svg_double(gradient, "cx", x2);
590         sp_repr_set_svg_double(gradient, "cy", y2);
591         sp_repr_set_svg_double(gradient, "r", r2);
592         extend0 = radial_shading->getExtend0();
593         extend1 = radial_shading->getExtend1();
594         num_funcs = radial_shading->getNFuncs();
595         func = radial_shading->getFunc(0);
596     } else {    // Unsupported shading type
597         return NULL;
598     }
599     gradient->setAttribute("gradientUnits", "userSpaceOnUse");
600     // Flip the gradient transform around the y axis
601     double *p2u = shading_pattern->getMatrix();
602     NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
603     NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
604     pat_matrix *= flip;
605     gchar *transform_text = sp_svg_transform_write(pat_matrix);
606     gradient->setAttribute("gradientTransform", transform_text);
607     g_free(transform_text);
609     if ( extend0 && extend1 ) {
610         gradient->setAttribute("spreadMethod", "pad");
611     }
613     if ( num_funcs > 1 || !_addStopsToGradient(gradient, func, 1.0) ) {
614         Inkscape::GC::release(gradient);
615         return NULL;
616     }
618     Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc));
619     defs->appendChild(gradient);
620     gchar *id = g_strdup(gradient->attribute("id"));
621     Inkscape::GC::release(gradient);
623     return id;
626 #define EPSILON 0.0001
627 bool SvgBuilder::_addSamplesToGradient(Inkscape::XML::Node *gradient,
628                                        Function *func, double offset0,
629                                        double offset1, double opacity) {
631     // Check whether this sampled function can be converted to color stops
632     int sample_size = 0;
633     int num_comps = func->getOutputSize();
634     double *samples = NULL;
635     if ( func->getType() == 0 ) {   // Sampled function
636         SampledFunction *sampled_func = (SampledFunction*)func;
637         sample_size = sampled_func->getSampleSize(0);
638         if ( sample_size != 2 || num_comps != 3 ) {
639             return false;
640         }
641         samples = sampled_func->getSamples();
642     } else if ( func->getType() == 2 ) {    // Exponential function
643         sample_size = 1;
644         if ( num_comps != 1 && num_comps != 3 ) {
645             return false;
646         }
647         double *exp_output = new double[2 * num_comps];
648         ExponentialFunction *exp_func = (ExponentialFunction*)func;
649         double x = 0.0;
650         for ( int i = 0 ; i < 2 * num_comps ; i += num_comps ) {
651             if ( i >= num_comps ) {
652                 x = 1.0;
653             }
654             exp_func->transform(&x, &exp_output[i]);
655         }
656         samples = exp_output;
657     }
659     unsigned stop_count = gradient->childCount();
660     bool is_continuation = false;
661     // Check if this sampled function is the continuation of the previous one
662     if ( stop_count > 0 ) {
663         // Get previous stop
664         Inkscape::XML::Node *prev_stop = gradient->nthChild(stop_count-1);
665         // Read its properties
666         double prev_offset;
667         sp_repr_get_double(prev_stop, "offset", &prev_offset);
668         SPCSSAttr *css = sp_repr_css_attr(prev_stop, "style");
669         guint32 prev_stop_color = sp_svg_read_color(sp_repr_css_property(css, "stop-color", NULL), 0);
670         sp_repr_css_attr_unref(css);
671         // Convert colors
672         double r = SP_RGBA32_R_F (prev_stop_color);
673         double g = SP_RGBA32_G_F (prev_stop_color);
674         double b = SP_RGBA32_B_F (prev_stop_color);
675         if ( fabs(prev_offset - offset0) < EPSILON &&
676              fabs(samples[0] - r) < EPSILON &&
677              fabs(samples[1] - g) < EPSILON &&
678              fabs(samples[2] - b) < EPSILON ) {
680             is_continuation = true;
681         }
682     }
684     int num_stops_added;
685     int i;
686     if (is_continuation) {
687         num_stops_added = 1;
688         i = num_comps;
689     } else {
690         num_stops_added = i = 0;
691     }
692     while ( num_stops_added < 2 ) {
693         Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
694         SPCSSAttr *css = sp_repr_css_attr_new();
695         Inkscape::CSSOStringStream os_opacity;
696         os_opacity << opacity;
697         gchar c[64];
698         if ( num_comps == 1 ) {
699             sp_svg_write_color(c, 64, SP_RGBA32_F_COMPOSE (samples[i], samples[i], samples[i], 1.0));
700         } else {
701             sp_svg_write_color(c, 64, SP_RGBA32_F_COMPOSE (samples[i], samples[i+1], samples[i+2], 1.0));
702         }
703         sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
704         sp_repr_css_set_property(css, "stop-color", c);
706         sp_repr_css_change(stop, css, "style");
707         sp_repr_css_attr_unref(css);
708         sp_repr_set_css_double(stop, "offset", ( i < num_comps ) ? offset0 : offset1);
710         gradient->appendChild(stop);
711         Inkscape::GC::release(stop);
712         i += num_comps; // Advance to the next sample
713         num_stops_added++;
714     }
715     // Free the output of the exponential function
716     if ( func->getType() == 2 ) {
717         delete samples;
718     }
719   
720     return true;
723 bool SvgBuilder::_addStopsToGradient(Inkscape::XML::Node *gradient, Function *func,
724                                      double opacity) {
725     
726     int type = func->getType();
727     if ( type == 0 || type == 2 ) {  // Sampled or exponential function
728         _addSamplesToGradient(gradient, func, 0.0, 1.0, opacity);
729     } else if ( type == 3 ) { // Stitching
730         StitchingFunction *stitchingFunc = (StitchingFunction*)func;
731         double *bounds = stitchingFunc->getBounds();
732         int num_funcs = stitchingFunc->getNumFuncs();
733         // Add samples from all the stitched functions
734         for ( int i = 0 ; i < num_funcs ; i++ ) {
735             Function *func = stitchingFunc->getFunc(i);
736             int func_type = func->getType();
737             if ( func_type != 0 && func_type != 2 ) // Only sampled and exponential functions are supported
738                 continue;
740             _addSamplesToGradient(gradient, func, bounds[i], bounds[i+1], opacity);
741         }
742     } else { // Unsupported function type
743         return false;
744     }
746     return true;
749 /**
750  * \brief Sets _invalidated_style to true to indicate that styles have to be updated
751  * Used for text output when glyphs are buffered till a font change
752  */
753 void SvgBuilder::updateStyle(GfxState *state) {
754     if (_in_text_object) {
755         _invalidated_style = true;
756         _current_state = state;
757     }
760 /**
761  * This array holds info about translating font weight names to more or less CSS equivalents
762  */
763 static char *font_weight_translator[][2] = {
764     {"bold", "bold"},
765     {"light", "300"},
766     {"black", "900"},
767     {"heavy", "900"},
768     {"ultrabold", "800"},
769     {"extrabold", "800"},
770     {"demibold", "600"},
771     {"semibold", "600"},
772     {"medium", "500"},
773     {"book", "normal"},
774     {"regular", "normal"},
775     {"roman", "normal"},
776     {"normal", "normal"},
777     {"ultralight", "200"},
778     {"extralight", "200"},
779     {"thin", "100"}
780 };
782 /**
783  * \brief Updates _font_style according to the font set in parameter state
784  */
785 void SvgBuilder::updateFont(GfxState *state) {
787     TRACE(("updateFont()\n"));
788     _need_font_update = false;
790     if (_font_style) {
791         //sp_repr_css_attr_unref(_font_style);
792     }
793     _font_style = sp_repr_css_attr_new();
794     GfxFont *font = state->getFont();
795     // Store original name
796     if (font->getOrigName()) {
797         _font_specification = font->getOrigName()->getCString();
798     } else if (font->getName()) {
799         _font_specification = font->getName()->getCString();
800     } else {
801         _font_specification = "Arial";
802     }
804     // Prune the font name to get the correct font family name
805     // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic
806     char *font_family = NULL;
807     char *font_style = NULL;
808     char *font_style_lowercase = NULL;
809     char *plus_sign = strstr(_font_specification, "+");
810     if (plus_sign) {
811         font_family = g_strdup(plus_sign + 1);
812         _font_specification = plus_sign + 1;
813     } else {
814         font_family = g_strdup(_font_specification);
815     }
816     char *style_delim = NULL;
817     if ( ( style_delim = g_strrstr(font_family, "-") ) ||
818          ( style_delim = g_strrstr(font_family, ",") ) ) {
819         font_style = style_delim + 1;
820         font_style_lowercase = g_ascii_strdown(font_style, -1);
821         style_delim[0] = 0;
822     }
824     // Font family
825     if (font->getFamily()) {
826         sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
827     } else {
828         sp_repr_css_set_property(_font_style, "font-family", font_family);
829     }
831     // Font style
832     if (font->isItalic()) {
833         sp_repr_css_set_property(_font_style, "font-style", "italic");
834     } else if (font_style) {
835         if ( strstr(font_style_lowercase, "italic") ||
836              strstr(font_style_lowercase, "slanted") ) {
837             sp_repr_css_set_property(_font_style, "font-style", "italic");
838         } else if (strstr(font_style_lowercase, "oblique")) {
839             sp_repr_css_set_property(_font_style, "font-style", "oblique");
840         }
841     }
843     // Font variant -- default 'normal' value
844     sp_repr_css_set_property(_font_style, "font-variant", "normal");
846     // Font weight
847     GfxFont::Weight font_weight = font->getWeight();
848     char *css_font_weight = NULL;
849     if ( font_weight != GfxFont::WeightNotDefined ) {
850         if ( font_weight == GfxFont::W400 ) {
851             css_font_weight = "normal";
852         } else if ( font_weight == GfxFont::W700 ) {
853             css_font_weight = "bold";
854         } else {
855             gchar weight_num[4] = "100";
856             weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
857             sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num);
858         }
859     } else if (font_style) {
860         // Apply the font weight translations
861         int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) );
862         for ( int i = 0 ; i < num_translations ; i++ ) {
863             if (strstr(font_style_lowercase, font_weight_translator[i][0])) {
864                 css_font_weight = font_weight_translator[i][1];
865             }
866         }
867     } else {
868         css_font_weight = "normal";
869     }
870     if (css_font_weight) {
871         sp_repr_css_set_property(_font_style, "font-weight", css_font_weight);
872     }
873     g_free(font_family);
874     if (font_style_lowercase) {
875         g_free(font_style_lowercase);
876     }
878     // Font stretch
879     GfxFont::Stretch font_stretch = font->getStretch();
880     gchar *stretch_value = NULL;
881     switch (font_stretch) {
882         case GfxFont::UltraCondensed:
883             stretch_value = "ultra-condensed";
884             break;
885         case GfxFont::ExtraCondensed:
886             stretch_value = "extra-condensed";
887             break;
888         case GfxFont::Condensed:
889             stretch_value = "condensed";
890             break;
891         case GfxFont::SemiCondensed:
892             stretch_value = "semi-condensed";
893             break;
894         case GfxFont::Normal:
895             stretch_value = "normal";
896             break;
897         case GfxFont::SemiExpanded:
898             stretch_value = "semi-expanded";
899             break;
900         case GfxFont::Expanded:
901             stretch_value = "expanded";
902             break;
903         case GfxFont::ExtraExpanded:
904             stretch_value = "extra-expanded";
905             break;
906         case GfxFont::UltraExpanded:
907             stretch_value = "ultra-expanded";
908             break;
909         default:
910             break;
911     }
912     if ( stretch_value != NULL ) {
913         sp_repr_css_set_property(_font_style, "font-stretch", stretch_value);
914     }
916     // Font size
917     Inkscape::CSSOStringStream os_font_size;
918     double *text_matrix = state->getTextMat();
919     double w_scale = sqrt( text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2] );
920     double h_scale = sqrt( text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3] );
921     double max_scale;
922     if ( w_scale > h_scale ) {
923         max_scale = w_scale;
924     } else {
925         max_scale = h_scale;
926     }
927     double css_font_size = max_scale * state->getFontSize();
928     if ( font->getType() == fontType3 ) {
929         double *font_matrix = font->getFontMatrix();
930         if ( font_matrix[0] != 0.0 ) {
931             css_font_size *= font_matrix[3] / font_matrix[0];
932         }
933     }
935     os_font_size << css_font_size;
936     sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
938     // Writing mode
939     if ( font->getWMode() == 0 ) {
940         sp_repr_css_set_property(_font_style, "writing-mode", "lr");
941     } else {
942         sp_repr_css_set_property(_font_style, "writing-mode", "tb");
943     }
945     // Calculate new text matrix
946     NR::Matrix new_text_matrix(text_matrix[0] * state->getHorizScaling(),
947                                text_matrix[1] * state->getHorizScaling(),
948                                -text_matrix[2], -text_matrix[3],
949                                0.0, 0.0);
951     if ( fabs( max_scale - 1.0 ) > EPSILON ) {
952         // Cancel out scaling by font size in text matrix
953         for ( int i = 0 ; i < 4 ; i++ ) {
954             new_text_matrix[i] /= max_scale;
955         }
956     }
957     _text_matrix = new_text_matrix;
958     _font_scaling = max_scale;
959     _current_font = font;
960     _invalidated_style = true;
963 /**
964  * \brief Shifts the current text position by the given amount (specified in text space)
965  */
966 void SvgBuilder::updateTextShift(GfxState *state, double shift) {
967     double shift_value = -shift * 0.001 * fabs(state->getFontSize());
968     if (state->getFont()->getWMode()) {
969         _text_position[1] += shift_value;
970     } else {
971         _text_position[0] += shift_value;
972     }
975 /**
976  * \brief Updates current text position
977  */
978 void SvgBuilder::updateTextPosition(double tx, double ty) {
979     NR::Point new_position(tx, ty);
980     _text_position = new_position;
983 /**
984  * \brief Flushes the buffered characters
985  */
986 void SvgBuilder::updateTextMatrix(GfxState *state) {
987     _flushText();
988     updateFont(state);   // Update text matrix
991 /**
992  * \brief Writes the buffered characters to the SVG document
993  */
994 void SvgBuilder::_flushText() {
995     // Ignore empty strings
996     if ( _glyphs.size() < 1 ) {
997         _glyphs.clear();
998         return;
999     }
1000     std::vector<SvgGlyph>::iterator i = _glyphs.begin();
1001     const SvgGlyph& first_glyph = (*i);
1002     int render_mode = first_glyph.render_mode;
1003     // Ignore invisible characters
1004     if ( render_mode == 3 ) {
1005         _glyphs.clear();
1006         return;
1007     }
1009     Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
1010     // Set text matrix
1011     NR::Matrix text_transform(_text_matrix);
1012     text_transform[4] = first_glyph.position[0];
1013     text_transform[5] = first_glyph.position[1];
1014     gchar *transform = sp_svg_transform_write(text_transform);
1015     text_node->setAttribute("transform", transform);
1016     g_free(transform);
1018     bool new_tspan = true;
1019     unsigned int glyphs_in_a_row = 0;
1020     Inkscape::XML::Node *tspan_node = NULL;
1021     Glib::ustring x_coords;
1022     Glib::ustring y_coords;
1023     Glib::ustring text_buffer;
1024     bool is_vertical = !strcmp(sp_repr_css_property(_font_style, "writing-mode", "lr"), "tb");  // FIXME
1026     // Output all buffered glyphs
1027     while (1) {
1028         const SvgGlyph& glyph = (*i);
1029         std::vector<SvgGlyph>::iterator prev_iterator = i - 1;
1030         // Check if we need to make a new tspan
1031         if (glyph.style_changed) {
1032             new_tspan = true;
1033         } else if ( i != _glyphs.begin() ) {
1034             const SvgGlyph& prev_glyph = (*prev_iterator);
1035             if ( !( ( glyph.dy == 0.0 && prev_glyph.dy == 0.0 &&
1036                      glyph.text_position[1] == prev_glyph.text_position[1] ) ||
1037                     ( glyph.dx == 0.0 && prev_glyph.dx == 0.0 &&
1038                      glyph.text_position[0] == prev_glyph.text_position[0] ) ) ) {
1039                 new_tspan = true;
1040             }
1041         }
1043         // Create tspan node if needed
1044         if ( new_tspan || i == _glyphs.end() ) {
1045             if (tspan_node) {
1046                 // Set the x and y coordinate arrays
1047                 tspan_node->setAttribute("x", x_coords.c_str());
1048                 tspan_node->setAttribute("y", y_coords.c_str());
1049                 TRACE(("tspan content: %s\n", text_buffer.c_str()));
1050                 if ( glyphs_in_a_row > 1 ) {
1051                     tspan_node->setAttribute("sodipodi:role", "line");
1052                 }
1053                 // Add text content node to tspan
1054                 Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str());
1055                 tspan_node->appendChild(text_content);
1056                 Inkscape::GC::release(text_content);
1057                 text_node->appendChild(tspan_node);
1058                 // Clear temporary buffers
1059                 x_coords.clear();
1060                 y_coords.clear();
1061                 text_buffer.clear();
1062                 Inkscape::GC::release(tspan_node);
1063                 glyphs_in_a_row = 0;
1064             }
1065             if ( i == _glyphs.end() ) {
1066                 sp_repr_css_attr_unref((*prev_iterator).style);
1067                 break;
1068             } else {
1069                 tspan_node = _xml_doc->createElement("svg:tspan");
1070                 tspan_node->setAttribute("inkscape:font-specification", glyph.font_specification);
1071                 // Set style and unref SPCSSAttr if it won't be needed anymore
1072                 sp_repr_css_change(tspan_node, glyph.style, "style");
1073                 if ( glyph.style_changed && i != _glyphs.begin() ) {    // Free previous style
1074                     sp_repr_css_attr_unref((*prev_iterator).style);
1075                 }
1076             }
1077             new_tspan = false;
1078         }
1079         if ( glyphs_in_a_row > 0 ) {
1080             x_coords.append(" ");
1081             y_coords.append(" ");
1082         }
1083         // Append the coordinates to their respective strings
1084         NR::Point delta_pos( glyph.text_position - first_glyph.text_position );
1085         delta_pos[1] += glyph.rise;
1086         delta_pos[1] *= -1.0;   // flip it
1087         delta_pos *= _font_scaling;
1088         Inkscape::CSSOStringStream os_x;
1089         os_x << delta_pos[0];
1090         x_coords.append(os_x.str());
1091         Inkscape::CSSOStringStream os_y;
1092         os_y << delta_pos[1];
1093         y_coords.append(os_y.str());
1095         // Append the character to the text buffer
1096         text_buffer.append((char *)&glyph.code, 1);
1098         glyphs_in_a_row++;
1099         i++;
1100     }
1101     _container->appendChild(text_node);
1102     Inkscape::GC::release(text_node);
1104     _glyphs.clear();
1107 void SvgBuilder::beginString(GfxState *state, GooString *s) {
1108     if (_need_font_update) {
1109         updateFont(state);
1110     }
1111     IFTRACE(double *m = state->getTextMat());
1112     TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1113     IFTRACE(m = state->getCTM());
1114     TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1117 /**
1118  * \brief Adds the specified character to the text buffer
1119  * Takes care of converting it to UTF-8 and generates a new style repr if style
1120  * has changed since the last call.
1121  */
1122 void SvgBuilder::addChar(GfxState *state, double x, double y,
1123                          double dx, double dy,
1124                          double originX, double originY,
1125                          CharCode code, int nBytes, Unicode *u, int uLen) {
1128     bool is_space = ( uLen == 1 && u[0] == 32 );
1129     // Skip beginning space
1130     if ( is_space && _glyphs.size() < 1 ) {
1131         NR::Point delta(dx, dy);
1132          _text_position += delta;
1133          return;
1134     }
1135     // Allow only one space in a row
1136     if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 &&
1137          _glyphs[_glyphs.size() - 1].code[0] == 32 ) {
1138         NR::Point delta(dx, dy);
1139         _text_position += delta;
1140         return;
1141     }
1143     SvgGlyph new_glyph;
1144     new_glyph.is_space = is_space;
1145     new_glyph.position = NR::Point( x - originX, y - originY );
1146     new_glyph.text_position = _text_position;
1147     new_glyph.dx = dx;
1148     new_glyph.dy = dy;
1149     NR::Point delta(dx, dy);
1150     _text_position += delta;
1152     // Convert the character to UTF-8 since that's our SVG document's encoding
1153     static UnicodeMap *u_map = NULL;
1154     if ( u_map == NULL ) {
1155         GooString *enc = new GooString("UTF-8");
1156         u_map = globalParams->getUnicodeMap(enc);
1157         u_map->incRefCnt();
1158         delete enc;
1159     }
1160     int code_size = 0;
1161     for ( int i = 0 ; i < uLen ; i++ ) {
1162         code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size);
1163     }
1164     new_glyph.code_size = code_size;
1166     // Copy current style if it has changed since the previous glyph
1167     if (_invalidated_style || _glyphs.size() == 0 ) {
1168         new_glyph.style_changed = true;
1169         int render_mode = state->getRender();
1170         // Set style
1171         bool has_fill = !( render_mode & 1 );
1172         bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2;
1173         new_glyph.style = _setStyle(state, has_fill, has_stroke);
1174         new_glyph.render_mode = render_mode;
1175         sp_repr_css_merge(new_glyph.style, _font_style); // Merge with font style
1176         _invalidated_style = false;
1177     } else {
1178         new_glyph.style_changed = false;
1179         // Point to previous glyph's style information
1180         const SvgGlyph& prev_glyph = _glyphs.back();
1181         new_glyph.style = prev_glyph.style;
1182         new_glyph.render_mode = prev_glyph.render_mode;
1183     }
1184     new_glyph.font_specification = _font_specification;
1185     new_glyph.rise = state->getRise();
1187     _glyphs.push_back(new_glyph);
1190 void SvgBuilder::endString(GfxState *state) {
1193 void SvgBuilder::beginTextObject(GfxState *state) {
1194     _in_text_object = true;
1195     _invalidated_style = true;  // Force copying of current state
1196     _current_state = state;
1199 void SvgBuilder::endTextObject(GfxState *state) {
1200     _flushText();
1201     // TODO: clip if render_mode >= 4
1202     _in_text_object = false;
1205 /**
1206  * Helper functions for supporting direct PNG output into a base64 encoded stream
1207  */
1208 void png_write_base64stream(png_structp png_ptr, png_bytep data, png_size_t length)
1210     Inkscape::IO::Base64OutputStream *stream =
1211             (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1212     for ( unsigned i = 0 ; i < length ; i++ ) {
1213         stream->put((int)data[i]);
1214     }
1217 void png_flush_base64stream(png_structp png_ptr)
1219     Inkscape::IO::Base64OutputStream *stream =
1220             (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1221     stream->flush();
1224 /**
1225  * \brief Creates an <image> element containing the given ImageStream as a PNG
1226  *
1227  */
1228 Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height,
1229         GfxImageColorMap *color_map, int *mask_colors, bool alpha_only, bool invert_alpha) {
1231     // Create PNG write struct
1232     png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1233     if ( png_ptr == NULL ) {
1234         return NULL;
1235     }
1236     // Create PNG info struct
1237     png_infop info_ptr = png_create_info_struct(png_ptr);
1238     if ( info_ptr == NULL ) {
1239         png_destroy_write_struct(&png_ptr, NULL);
1240         return NULL;
1241     }
1242     // Set error handler
1243     if (setjmp(png_ptr->jmpbuf)) {
1244         png_destroy_write_struct(&png_ptr, &info_ptr);
1245         return NULL;
1246     }
1248     // Set read/write functions
1249     Inkscape::IO::StringOutputStream base64_string;
1250     Inkscape::IO::Base64OutputStream base64_stream(base64_string);
1251     FILE *fp;
1252     gchar *file_name;
1253     bool embed_image = true;
1254     if (embed_image) {
1255         base64_stream.setColumnWidth(0);   // Disable line breaks
1256         png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream);
1257     } else {
1258         static int counter = 0;
1259         file_name = g_strdup_printf("%s_img%d.png", _docname, counter++);
1260         fp = fopen(file_name, "wb");
1261         if ( fp == NULL ) {
1262             png_destroy_write_struct(&png_ptr, &info_ptr);
1263             g_free(file_name);
1264             return NULL;
1265         }
1266         png_init_io(png_ptr, fp);
1267     }
1269     // Set header data
1270     if ( !invert_alpha && !alpha_only ) {
1271         png_set_invert_alpha(png_ptr);
1272     }
1273     png_color_8 sig_bit;
1274     if (alpha_only) {
1275         png_set_IHDR(png_ptr, info_ptr,
1276                      width,
1277                      height,
1278                      8, /* bit_depth */
1279                      PNG_COLOR_TYPE_GRAY,
1280                      PNG_INTERLACE_NONE,
1281                      PNG_COMPRESSION_TYPE_BASE,
1282                      PNG_FILTER_TYPE_BASE);
1283         sig_bit.red = 0;
1284         sig_bit.green = 0;
1285         sig_bit.blue = 0;
1286         sig_bit.gray = 8;
1287         sig_bit.alpha = 0;
1288     } else {
1289         png_set_IHDR(png_ptr, info_ptr,
1290                      width,
1291                      height,
1292                      8, /* bit_depth */
1293                      PNG_COLOR_TYPE_RGB_ALPHA,
1294                      PNG_INTERLACE_NONE,
1295                      PNG_COMPRESSION_TYPE_BASE,
1296                      PNG_FILTER_TYPE_BASE);
1297         sig_bit.red = 8;
1298         sig_bit.green = 8;
1299         sig_bit.blue = 8;
1300         sig_bit.alpha = 8;
1301     }
1302     png_set_sBIT(png_ptr, info_ptr, &sig_bit);
1303     png_set_bgr(png_ptr);
1304     // Write the file header
1305     png_write_info(png_ptr, info_ptr);
1307     // Convert pixels
1308     ImageStream *image_stream;
1309     if (alpha_only) {
1310         if (color_map) {
1311             image_stream = new ImageStream(str, width, color_map->getNumPixelComps(),
1312                                            color_map->getBits());
1313         } else {
1314             image_stream = new ImageStream(str, width, 1, 1);
1315         }
1316         image_stream->reset();
1318         // Convert grayscale values
1319         unsigned char *buffer = NULL;
1320         if ( color_map || invert_alpha ) {
1321             buffer = new unsigned char[width];
1322         }
1323         if ( color_map ) {
1324             for ( int y = 0 ; y < height ; y++ ) {
1325                 unsigned char *row = image_stream->getLine();
1326                 color_map->getGrayLine(row, buffer, width);
1327                 if (invert_alpha) {
1328                     unsigned char *buf_ptr = buffer;
1329                     for ( int x = 0 ; x < width ; x++ ) {
1330                         *buf_ptr++ = ~(*buf_ptr);
1331                     }
1332                 }
1333                 png_write_row(png_ptr, (png_bytep)buffer);
1334             }
1335         } else {
1336             for ( int y = 0 ; y < height ; y++ ) {
1337                 unsigned char *row = image_stream->getLine();
1338                 if (invert_alpha) {
1339                     unsigned char *buf_ptr = buffer;
1340                     for ( int x = 0 ; x < width ; x++ ) {
1341                         *buf_ptr++ = ~row[x];
1342                     }
1343                     png_write_row(png_ptr, (png_bytep)buffer);
1344                 } else {
1345                     png_write_row(png_ptr, (png_bytep)row);
1346                 }
1347             }
1348         }
1349         if (buffer) {
1350             delete buffer;
1351         }
1352     } else if (color_map) {
1353         image_stream = new ImageStream(str, width,
1354                                        color_map->getNumPixelComps(),
1355                                        color_map->getBits());
1356         image_stream->reset();
1358         // Convert RGB values
1359         unsigned int *buffer = new unsigned int[width];
1360         if (mask_colors) {
1361             for ( int y = 0 ; y < height ; y++ ) {
1362                 unsigned char *row = image_stream->getLine();
1363                 color_map->getRGBLine(row, buffer, width);
1365                 unsigned int *dest = buffer;
1366                 for ( int x = 0 ; x < width ; x++ ) {
1367                     // Check each color component against the mask
1368                     for ( int i = 0; i < color_map->getNumPixelComps() ; i++) {
1369                         if ( row[i] < mask_colors[2*i] * 255 ||
1370                              row[i] > mask_colors[2*i + 1] * 255 ) {
1371                             *dest = *dest | 0xff000000;
1372                             break;
1373                         }
1374                     }
1375                     // Advance to the next pixel
1376                     row += color_map->getNumPixelComps();
1377                     dest++;
1378                 }
1379                 // Write it to the PNG
1380                 png_write_row(png_ptr, (png_bytep)buffer);
1381             }
1382         } else {
1383             for ( int i = 0 ; i < height ; i++ ) {
1384                 unsigned char *row = image_stream->getLine();
1385                 memset((void*)buffer, 0xff, sizeof(int) * width);
1386                 color_map->getRGBLine(row, buffer, width);
1387                 png_write_row(png_ptr, (png_bytep)buffer);
1388             }
1389         }
1390         delete buffer;
1392     } else {    // A colormap must be provided, so quit
1393         png_destroy_write_struct(&png_ptr, &info_ptr);
1394         if (!embed_image) {
1395             fclose(fp);
1396             g_free(file_name);
1397         }
1398         return NULL;
1399     }
1400     delete image_stream;
1401     str->close();
1402     // Close PNG
1403     png_write_end(png_ptr, info_ptr);
1404     png_destroy_write_struct(&png_ptr, &info_ptr);
1405     base64_stream.close();
1407     // Create repr
1408     Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image");
1409     sp_repr_set_svg_double(image_node, "width", 1);
1410     sp_repr_set_svg_double(image_node, "height", 1);
1411     // Set transformation
1412     if (_is_top_level) {
1413         svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1414     }
1416     // Create href
1417     if (embed_image) {
1418         // Append format specification to the URI
1419         Glib::ustring& png_data = base64_string.getString();
1420         png_data.insert(0, "data:image/png;base64,");
1421         image_node->setAttribute("xlink:href", png_data.c_str());
1422     } else {
1423         fclose(fp);
1424         image_node->setAttribute("xlink:href", file_name);
1425         g_free(file_name);
1426     }
1428     return image_node;
1431 /**
1432  * \brief Creates a <mask> with the specified width and height and adds to <defs>
1433  *  If we're not the top-level SvgBuilder, creates a <defs> too and adds the mask to it.
1434  * \return the created XML node
1435  */
1436 Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) {
1437     Inkscape::XML::Node *mask_node = _xml_doc->createElement("svg:mask");
1438     mask_node->setAttribute("maskUnits", "userSpaceOnUse");
1439     sp_repr_set_svg_double(mask_node, "x", 0.0);
1440     sp_repr_set_svg_double(mask_node, "y", 0.0);
1441     sp_repr_set_svg_double(mask_node, "width", width);
1442     sp_repr_set_svg_double(mask_node, "height", height);
1443     // Append mask to defs
1444     if (_is_top_level) {
1445         SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(mask_node);
1446         Inkscape::GC::release(mask_node);
1447         return SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->lastChild();
1448     } else {    // Work around for renderer bug when mask isn't defined in pattern
1449         static int mask_count = 0;
1450         Inkscape::XML::Node *defs = _root->firstChild();
1451         Inkscape::XML::Node *result = NULL;
1452         if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) {
1453             // Create <defs> node
1454             defs = _xml_doc->createElement("svg:defs");
1455             _root->addChild(defs, NULL);
1456             Inkscape::GC::release(defs);
1457             defs = _root->firstChild();
1458         }
1459         gchar *mask_id = g_strdup_printf("_mask%d", mask_count++);
1460         mask_node->setAttribute("id", mask_id);
1461         g_free(mask_id);
1462         defs->appendChild(mask_node);
1463         Inkscape::GC::release(mask_node);
1464         return defs->lastChild();
1465     }
1468 void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height,
1469                           GfxImageColorMap *color_map, int *mask_colors) {
1471      Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, mask_colors);
1472      if (image_node) {
1473          _container->appendChild(image_node);
1474         Inkscape::GC::release(image_node);
1475      }
1478 void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height,
1479                               bool invert) {
1481     // Create a rectangle
1482     Inkscape::XML::Node *rect = _xml_doc->createElement("svg:rect");
1483     sp_repr_set_svg_double(rect, "x", 0.0);
1484     sp_repr_set_svg_double(rect, "y", 0.0);
1485     sp_repr_set_svg_double(rect, "width", 1.0);
1486     sp_repr_set_svg_double(rect, "height", 1.0);
1487     svgSetTransform(rect, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1488     // Get current fill style and set it on the rectangle
1489     SPCSSAttr *css = sp_repr_css_attr_new();
1490     _setFillStyle(css, state, false);
1491     sp_repr_css_change(rect, css, "style");
1492     sp_repr_css_attr_unref(css);
1494     // Scaling 1x1 surfaces might not work so skip setting a mask with this size
1495     if ( width > 1 || height > 1 ) {
1496         Inkscape::XML::Node *mask_image_node = _createImage(str, width, height, NULL, NULL, true, invert);
1497         if (mask_image_node) {
1498             // Create the mask
1499             Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1500             // Remove unnecessary transformation from the mask image
1501             mask_image_node->setAttribute("transform", NULL);
1502             mask_node->appendChild(mask_image_node);
1503             Inkscape::GC::release(mask_image_node);
1504             gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1505             rect->setAttribute("mask", mask_url);
1506             g_free(mask_url);
1507         }
1508     }
1510     // Add the rectangle to the container
1511     _container->appendChild(rect);
1512     Inkscape::GC::release(rect);
1515 void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int height,
1516                                 GfxImageColorMap *color_map,
1517                                 Stream *mask_str, int mask_width, int mask_height,
1518                                 bool invert_mask) {
1520     Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1521                                                         NULL, NULL, true, invert_mask);
1522     Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1523     if ( mask_image_node && image_node ) {
1524         // Create mask for the image
1525         Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1526         // Remove unnecessary transformation from the mask image
1527         mask_image_node->setAttribute("transform", NULL);
1528         mask_node->appendChild(mask_image_node);
1529         // Scale the mask to the size of the image
1530         NR::Matrix mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
1531         gchar *transform_text = sp_svg_transform_write(mask_transform);
1532         mask_node->setAttribute("maskTransform", transform_text);
1533         g_free(transform_text);
1534         // Set mask and add image
1535         gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1536         image_node->setAttribute("mask", mask_url);
1537         g_free(mask_url);
1538         _container->appendChild(image_node);
1539     }
1540     if (mask_image_node) {
1541         Inkscape::GC::release(mask_image_node);
1542     }
1543     if (image_node) {
1544         Inkscape::GC::release(image_node);
1545     }
1547     
1548 void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int height,
1549                                     GfxImageColorMap *color_map,
1550                                     Stream *mask_str, int mask_width, int mask_height,
1551                                     GfxImageColorMap *mask_color_map) {
1553     Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1554                                                         mask_color_map, NULL, true);
1555     Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1556     if ( mask_image_node && image_node ) {
1557         // Create mask for the image
1558         Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1559         // Remove unnecessary transformation from the mask image
1560         mask_image_node->setAttribute("transform", NULL);
1561         mask_node->appendChild(mask_image_node);
1562         // Set mask and add image
1563         gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1564         image_node->setAttribute("mask", mask_url);
1565         g_free(mask_url);
1566         _container->appendChild(image_node);
1567     }
1568     if (mask_image_node) {
1569         Inkscape::GC::release(mask_image_node);
1570     }
1571     if (image_node) {
1572         Inkscape::GC::release(image_node);
1573     }
1576 } } } /* namespace Inkscape, Extension, Internal */
1578 #endif /* HAVE_POPPLER */
1580 /*
1581   Local Variables:
1582   mode:c++
1583   c-file-style:"stroustrup"
1584   c-file-offsets:((innamespace . 0)(inline-open . 0))
1585   indent-tabs-mode:nil
1586   fill-column:99
1587   End:
1588 */
1589 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :