Code

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