Code

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