Code

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