Code

Use the #RRGGBB color format instead of rgb() since most extensions don't support...
[inkscape.git] / src / extension / internal / pdfinput / svg-builder.cpp
1  /** \file
2  * Native PDF import using libpoppler.
3  * 
4  * Authors:
5  *   miklos erdelyi
6  *
7  * Copyright (C) 2007 Authors
8  *
9  * Released under GNU GPL, read the file 'COPYING' for more information
10  *
11  */
13 #ifdef HAVE_CONFIG_H
14 # include <config.h>
15 #endif
17 #ifdef HAVE_POPPLER
19 #include "svg-builder.h"
20 #include "pdf-parser.h"
22 #include <png.h>
24 #include "document-private.h"
25 #include "xml/document.h"
26 #include "xml/node.h"
27 #include "xml/repr.h"
28 #include "svg/svg.h"
29 #include "svg/path-string.h"
30 #include "svg/css-ostringstream.h"
31 #include "svg/svg-color.h"
32 #include "color.h"
33 #include "unit-constants.h"
34 #include "io/stringstream.h"
35 #include "io/base64stream.h"
36 #include "libnr/nr-matrix-ops.h"
37 #include "libnr/nr-macros.h"
38 #include "libnrtype/font-instance.h"
40 #include "Function.h"
41 #include "GfxState.h"
42 #include "GfxFont.h"
43 #include "Stream.h"
44 #include "UnicodeMap.h"
45 #include "GlobalParams.h"
47 namespace Inkscape {
48 namespace Extension {
49 namespace Internal {
51 //#define IFTRACE(_code)  _code
52 #define IFTRACE(_code)
54 #define TRACE(_args) IFTRACE(g_print _args)
57 /**
58  * \class SvgBuilder
59  * 
60  */
62 SvgBuilder::SvgBuilder() {
63     _in_text_object = false;
64     _need_font_update = true;
65     _invalidated_style = true;
66     _font_style = NULL;
67     _current_font = NULL;
68     _current_state = NULL;
69 }
71 SvgBuilder::SvgBuilder(SPDocument *document) {
72     _doc = document;
73     _xml_doc = sp_document_repr_doc(_doc);
74     _container = _root = _doc->rroot;
75     SvgBuilder();
76 }
78 SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) {
79     _doc = parent->_doc;
80     _xml_doc = parent->_xml_doc;
81     _container = this->_root = root;
82     SvgBuilder();
83 }
85 SvgBuilder::~SvgBuilder() {
86 }
88 void SvgBuilder::setDocumentSize(double width, double height) {
89     sp_repr_set_svg_double(_root, "width", width);
90     sp_repr_set_svg_double(_root, "height", height);
91     this->_width = width;
92     this->_height = height;
93 }
95 void SvgBuilder::saveState() {
96     _group_depth.push_back(0);
97     pushGroup();
98 }
100 void SvgBuilder::restoreState() {
101     while (_group_depth.back() > 0) {
102         popGroup();
103     }
104     _group_depth.pop_back();
107 Inkscape::XML::Node *SvgBuilder::pushGroup() {
108     Inkscape::XML::Node *node = _xml_doc->createElement("svg:g");
109     _container->appendChild(node);
110     _container = node;
111     Inkscape::GC::release(node);
112     _group_depth.back()++;
114     return _container;
117 Inkscape::XML::Node *SvgBuilder::popGroup() {
118     if (_container != _root) {  // Pop if the current container isn't root
119         _container = _container->parent();
120         _group_depth[_group_depth.size()-1] = --_group_depth.back();
121     }
123     return _container;
126 Inkscape::XML::Node *SvgBuilder::getContainer() {
127     return _container;
130 static gchar *svgConvertRGBToText(double r, double g, double b) {
131     static gchar tmp[1023] = {0};
132     snprintf(tmp, 1023,
133              "#%02x%02x%02x",
134              CLAMP(SP_COLOR_F_TO_U(r), 0, 255),
135              CLAMP(SP_COLOR_F_TO_U(g), 0, 255),
136              CLAMP(SP_COLOR_F_TO_U(b), 0, 255));
137     return (gchar *)&tmp;
140 static gchar *svgConvertGfxRGB(GfxRGB *color) {
141     double r = color->r / 65535.0;
142     double g = color->g / 65535.0;
143     double b = color->b / 65535.0;
144     return svgConvertRGBToText(r, g, b);
147 static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1,
148                               double c2, double c3, double c4, double c5) {
149     NR::Matrix matrix(c0, c1, c2, c3, c4, c5);
150     gchar *transform_text = sp_svg_transform_write(matrix);
151     node->setAttribute("transform", transform_text);
152     g_free(transform_text);
155 static void svgSetTransform(Inkscape::XML::Node *node, double *transform) {
156     svgSetTransform(node, transform[0], transform[1], transform[2], transform[3],
157                     transform[4], transform[5]);
160 /**
161  * \brief Generates a SVG path string from poppler's data structure
162  */
163 static gchar *svgInterpretPath(GfxPath *path) {
164     GfxSubpath *subpath;
165     Inkscape::SVG::PathString pathString;
166     int i, j;
167     for ( i = 0 ; i < path->getNumSubpaths() ; ++i ) {
168         subpath = path->getSubpath(i);
169         if (subpath->getNumPoints() > 0) {
170             pathString.moveTo(subpath->getX(0), subpath->getY(0));
171             j = 1;
172             while (j < subpath->getNumPoints()) {
173                 if (subpath->getCurve(j)) {
174                     pathString.curveTo(subpath->getX(j), subpath->getY(j),
175                                        subpath->getX(j+1), subpath->getY(j+1),
176                                        subpath->getX(j+2), subpath->getY(j+2));
178                     j += 3;
179                 } else {
180                     pathString.lineTo(subpath->getX(j), subpath->getY(j));
181                     ++j;
182                 }
183             }
184             if (subpath->isClosed()) {
185                 pathString.closePath();
186             }
187         }
188     }
190     return g_strdup(pathString.c_str());
193 /**
194  * \brief Sets stroke style from poppler's GfxState data structure
195  * Uses the given SPCSSAttr for storing the style properties
196  */
197 void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) {
199     // Check line width
200     if ( state->getLineWidth() <= 0.0 ) {
201         // Ignore stroke
202         sp_repr_css_set_property(css, "stroke", "none");
203         return;
204     }
206     // Stroke color/pattern
207     if ( state->getStrokeColorSpace()->getMode() == csPattern ) {
208         gchar *urltext = _createPattern(state->getStrokePattern());
209         sp_repr_css_set_property(css, "stroke", urltext);
210         if (urltext) {
211             g_free(urltext);
212         }
213     } else {
214         GfxRGB stroke_color;
215         state->getStrokeRGB(&stroke_color);
216         sp_repr_css_set_property(css, "stroke", svgConvertGfxRGB(&stroke_color));
217     }
219     // Opacity
220     Inkscape::CSSOStringStream os_opacity;
221     os_opacity << state->getStrokeOpacity();
222     sp_repr_css_set_property(css, "stroke-opacity", os_opacity.str().c_str());
224     // Line width
225     Inkscape::CSSOStringStream os_width;
226     os_width << state->getLineWidth();
227     sp_repr_css_set_property(css, "stroke-width", os_width.str().c_str());
229     // Line cap
230     switch (state->getLineCap()) {
231         case 0:
232             sp_repr_css_set_property(css, "stroke-linecap", "butt");
233             break;
234         case 1:
235             sp_repr_css_set_property(css, "stroke-linecap", "round");
236             break;
237         case 2:
238             sp_repr_css_set_property(css, "stroke-linecap", "square");
239             break;
240     }
242     // Line join
243     switch (state->getLineJoin()) {
244         case 0:
245             sp_repr_css_set_property(css, "stroke-linejoin", "miter");
246             break;
247         case 1:
248             sp_repr_css_set_property(css, "stroke-linejoin", "round");
249             break;
250         case 2:
251             sp_repr_css_set_property(css, "stroke-linejoin", "bevel");
252             break;
253     }
255     // Miterlimit
256     Inkscape::CSSOStringStream os_ml;
257     os_ml << state->getMiterLimit();
258     sp_repr_css_set_property(css, "stroke-miterlimit", os_ml.str().c_str());
260     // Line dash
261     double *dash_pattern;
262     int dash_length;
263     double dash_start;
264     state->getLineDash(&dash_pattern, &dash_length, &dash_start);
265     if ( dash_length > 0 ) {
266         Inkscape::CSSOStringStream os_array;
267         for ( int i = 0 ; i < dash_length ; i++ ) {
268             os_array << dash_pattern[i];
269             if (i < (dash_length - 1)) {
270                 os_array << ",";
271             }
272         }
273         sp_repr_css_set_property(css, "stroke-dasharray", os_array.str().c_str());
275         Inkscape::CSSOStringStream os_offset;
276         os_offset << dash_start;
277         sp_repr_css_set_property(css, "stroke-dashoffset", os_offset.str().c_str());
278     } else {
279         sp_repr_css_set_property(css, "stroke-dasharray", "none");
280         sp_repr_css_set_property(css, "stroke-dashoffset", NULL);
281     }
284 /**
285  * \brief Sets fill style from poppler's GfxState data structure
286  * Uses the given SPCSSAttr for storing the style properties.
287  */
288 void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) {
290     // Fill color/pattern
291     if ( state->getFillColorSpace()->getMode() == csPattern ) {
292         gchar *urltext = _createPattern(state->getFillPattern());
293         sp_repr_css_set_property(css, "fill", urltext);
294         if (urltext) {
295             g_free(urltext);
296         }
297     } else {
298         GfxRGB fill_color;
299         state->getFillRGB(&fill_color);
300         sp_repr_css_set_property(css, "fill", svgConvertGfxRGB(&fill_color));
301     }
303     // Opacity
304     Inkscape::CSSOStringStream os_opacity;
305     os_opacity << state->getFillOpacity();
306     sp_repr_css_set_property(css, "fill-opacity", os_opacity.str().c_str());
307     
308     // Fill rule
309     sp_repr_css_set_property(css, "fill-rule", even_odd ? "evenodd" : "nonzero");
312 /**
313  * \brief Sets style properties from poppler's GfxState data structure
314  * \return SPCSSAttr with all the relevant properties set
315  */
316 SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) {
317     SPCSSAttr *css = sp_repr_css_attr_new();
318     if (fill) {
319         _setFillStyle(css, state, even_odd);
320     } else {
321         sp_repr_css_set_property(css, "fill", "none");
322     }
323     
324     if (stroke) {
325         _setStrokeStyle(css, state);
326     } else {
327         sp_repr_css_set_property(css, "stroke", "none");
328     }
330     return css;
333 /**
334  * \brief Emits the current path in poppler's GfxState data structure
335  * Can be used to do filling and stroking at once.
336  *
337  * \param fill whether the path should be filled
338  * \param stroke whether the path should be stroked
339  * \param even_odd whether the even-odd rule should be used when filling the path
340  */
341 void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) {
342     Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
343     gchar *pathtext = svgInterpretPath(state->getPath());
344     path->setAttribute("d", pathtext);
345     g_free(pathtext);
347     // Set style
348     SPCSSAttr *css = _setStyle(state, fill, stroke, even_odd);
349     sp_repr_css_change(path, css, "style");
350     sp_repr_css_attr_unref(css);
352     _container->appendChild(path);
353     Inkscape::GC::release(path);
356 /**
357  * \brief Clips to the current path set in GfxState
358  * \param state poppler's data structure
359  * \param even_odd whether the even-odd rule should be applied
360  */
361 void SvgBuilder::clip(GfxState *state, bool even_odd) {
362     pushGroup();
363     setClipPath(state, even_odd);
366 void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
367     // Create the clipPath repr
368     Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath");
369     clip_path->setAttribute("clipPathUnits", "userSpaceOnUse");
370     // Create the path
371     Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
372     gchar *pathtext = svgInterpretPath(state->getPath());
373     path->setAttribute("d", pathtext);
374     g_free(pathtext);
375     clip_path->appendChild(path);
376     Inkscape::GC::release(path);
377     // Append clipPath to defs and get id
378     SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(clip_path);
379     gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id"));
380     Inkscape::GC::release(clip_path);
381     _container->setAttribute("clip-path", urltext);
382     g_free(urltext);
385 /**
386  * \brief Fills the given array with the current container's transform, if set
387  * \param transform array of doubles to be filled
388  * \return true on success; false on invalid transformation
389  */
390 bool SvgBuilder::getTransform(double *transform) {
391     NR::Matrix svd;
392     gchar const *tr = _container->attribute("transform");
393     bool valid = sp_svg_transform_read(tr, &svd);
394     if (valid) {
395         for ( int i = 0 ; i < 6 ; i++ ) {
396             transform[i] = svd[i];
397         }
398         return true;
399     } else {
400         return false;
401     }
404 /**
405  * \brief Sets the transformation matrix of the current container
406  */
407 void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
408                               double c4, double c5) {
410     TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
411     svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
414 void SvgBuilder::setTransform(double *transform) {
415     setTransform(transform[0], transform[1], transform[2], transform[3],
416                  transform[4], transform[5]);
419 /**
420  * \brief Checks whether the given pattern type can be represented in SVG
421  * Used by PdfParser to decide when to do fallback operations.
422  */
423 bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) {
424     if ( pattern != NULL ) {
425         if ( pattern->getType() == 2 ) {    // shading pattern
426             GfxShading *shading = ((GfxShadingPattern *)pattern)->getShading();
427             int shadingType = shading->getType();
428             if ( shadingType == 2 || // axial shading
429                  shadingType == 3 ) {   // radial shading
430                 return true;
431             }
432             return false;
433         } else if ( pattern->getType() == 1 ) {   // tiling pattern
434             return true;
435         }
436     }
438     return false;
441 /**
442  * \brief Creates a pattern from poppler's data structure
443  * Handles linear and radial gradients. Creates a new PdfParser and uses it to
444  * build a tiling pattern.
445  * \return an url pointing to the created pattern
446  */
447 gchar *SvgBuilder::_createPattern(GfxPattern *pattern) {
448     gchar *id = NULL;
449     if ( pattern != NULL ) {
450         if ( pattern->getType() == 2 ) {  // Shading pattern
451             id = _createGradient((GfxShadingPattern*)pattern);
452         } else if ( pattern->getType() == 1 ) {   // Tiling pattern
453             id = _createTilingPattern((GfxTilingPattern*)pattern);
454         }
455     } else {
456         return NULL;
457     }
458     gchar *urltext = g_strdup_printf ("url(#%s)", id);
459     g_free(id);
460     return urltext;
463 gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern) {
464     return NULL;
467 /**
468  * \brief Creates a linear or radial gradient from poppler's data structure
469  * \return id of the created object
470  */
471 gchar *SvgBuilder::_createGradient(GfxShadingPattern *shading_pattern) {
472     GfxShading *shading = shading_pattern->getShading();
473     Inkscape::XML::Node *gradient;
474     Function *func;
475     int num_funcs;
476     bool extend0, extend1;
478     if ( shading->getType() == 2 ) {  // Axial shading
479         gradient = _xml_doc->createElement("svg:linearGradient");
480         GfxAxialShading *axial_shading = (GfxAxialShading*)shading;
481         double x1, y1, x2, y2;
482         axial_shading->getCoords(&x1, &y1, &x2, &y2);
483         sp_repr_set_svg_double(gradient, "x1", x1);
484         sp_repr_set_svg_double(gradient, "y1", y1);
485         sp_repr_set_svg_double(gradient, "x2", x2);
486         sp_repr_set_svg_double(gradient, "y2", y2);
487         extend0 = axial_shading->getExtend0();
488         extend1 = axial_shading->getExtend1();
489         num_funcs = axial_shading->getNFuncs();
490         func = axial_shading->getFunc(0);
491     } else if (shading->getType() == 3) {   // Radial shading
492         gradient = _xml_doc->createElement("svg:radialGradient");
493         GfxRadialShading *radial_shading = (GfxRadialShading*)shading;
494         double x1, y1, r1, x2, y2, r2;
495         radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2);
496         // FIXME: the inner circle's radius is ignored here
497         sp_repr_set_svg_double(gradient, "fx", x1);
498         sp_repr_set_svg_double(gradient, "fy", y1);
499         sp_repr_set_svg_double(gradient, "cx", x2);
500         sp_repr_set_svg_double(gradient, "cy", y2);
501         sp_repr_set_svg_double(gradient, "r", r2);
502         extend0 = radial_shading->getExtend0();
503         extend1 = radial_shading->getExtend1();
504         num_funcs = radial_shading->getNFuncs();
505         func = radial_shading->getFunc(0);
506     } else {    // Unsupported shading type
507         return NULL;
508     }
509     gradient->setAttribute("gradientUnits", "userSpaceOnUse");
510     // Flip the gradient transform around the y axis
511     double *p2u = shading_pattern->getMatrix();
512     NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
513     NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
514     pat_matrix *= flip;
515     gchar *transform_text = sp_svg_transform_write(pat_matrix);
516     gradient->setAttribute("gradientTransform", transform_text);
517     g_free(transform_text);
519     if ( extend0 && extend1 ) {
520         gradient->setAttribute("spreadMethod", "pad");
521     }
523     if ( num_funcs > 1 || !_addStopsToGradient(gradient, func, 1.0) ) {
524         Inkscape::GC::release(gradient);
525         return NULL;
526     }
528     Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc));
529     defs->appendChild(gradient);
530     gchar *id = g_strdup(gradient->attribute("id"));
531     Inkscape::GC::release(gradient);
533     return id;
536 #define EPSILON 0.0001
537 bool SvgBuilder::_addSamplesToGradient(Inkscape::XML::Node *gradient,
538                                        SampledFunction *func, double offset0,
539                                        double offset1, double opacity) {
541     // Check whether this sampled function can be converted to color stops
542     int sample_size = func->getSampleSize(0);
543     if ( sample_size != 2 )
544         return false;
545     int num_comps = func->getOutputSize();
546     if ( num_comps != 3 )
547         return false;
549     double *samples = func->getSamples();
550     unsigned stop_count = gradient->childCount();
551     bool is_continuation = false;
552     // Check if this sampled function is the continuation of the previous one
553     if ( stop_count > 0 ) {
554         // Get previous stop
555         Inkscape::XML::Node *prev_stop = gradient->nthChild(stop_count-1);
556         // Read its properties
557         double prev_offset;
558         sp_repr_get_double(prev_stop, "offset", &prev_offset);
559         SPCSSAttr *css = sp_repr_css_attr(prev_stop, "style");
560         guint32 prev_stop_color = sp_svg_read_color(sp_repr_css_property(css, "stop-color", NULL), 0);
561         sp_repr_css_attr_unref(css);
562         // Convert colors
563         double r = SP_RGBA32_R_F (prev_stop_color);
564         double g = SP_RGBA32_G_F (prev_stop_color);
565         double b = SP_RGBA32_B_F (prev_stop_color);
566         if ( fabs(prev_offset - offset0) < EPSILON &&
567              fabs(samples[0] - r) < EPSILON &&
568              fabs(samples[1] - g) < EPSILON &&
569              fabs(samples[2] - b) < EPSILON ) {
571             is_continuation = true;
572         }
573     }
575     int i = is_continuation ? num_comps : 0;
576     while (i < sample_size*num_comps) {
577         Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
578         SPCSSAttr *css = sp_repr_css_attr_new();
579         Inkscape::CSSOStringStream os_opacity;
580         os_opacity << opacity;
581         sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
582         gchar c[64];
583         sp_svg_write_color (c, 64, SP_RGBA32_F_COMPOSE (samples[i], samples[i+1], samples[i+2], 1.0));
584         sp_repr_css_set_property(css, "stop-color", c);
585         sp_repr_css_change(stop, css, "style");
586         sp_repr_css_attr_unref(css);
587         sp_repr_set_css_double(stop, "offset", ( i < num_comps ) ? offset0 : offset1);
589         gradient->appendChild(stop);
590         Inkscape::GC::release(stop);
591         i += num_comps;
592     }
593   
594     return true;
597 bool SvgBuilder::_addStopsToGradient(Inkscape::XML::Node *gradient, Function *func,
598                                      double opacity) {
599     
600     int type = func->getType();
601     if ( type == 0 ) {  // Sampled
602         SampledFunction *sampledFunc = (SampledFunction*)func;
603         _addSamplesToGradient(gradient, sampledFunc, 0.0, 1.0, opacity);
604     } else if ( type == 3 ) { // Stitching
605         StitchingFunction *stitchingFunc = (StitchingFunction*)func;
606         double *bounds = stitchingFunc->getBounds();
607         int num_funcs = stitchingFunc->getNumFuncs();
608         // Add samples from all the stitched functions
609         for ( int i = 0 ; i < num_funcs ; i++ ) {
610             Function *func = stitchingFunc->getFunc(i);
611             if ( func->getType() != 0 ) // Only sampled functions are supported
612                 continue;
613            
614             SampledFunction *sampledFunc = (SampledFunction*)func;
615             _addSamplesToGradient(gradient, sampledFunc, bounds[i],
616                                   bounds[i+1], opacity);
617         }
618     } else { // Unsupported function type
619         return false;
620     }
622     return true;
625 /**
626  * \brief Sets _invalidated_style to true to indicate that styles have to be updated
627  * Used for text output when glyphs are buffered till a font change
628  */
629 void SvgBuilder::updateStyle(GfxState *state) {
630     if (_in_text_object) {
631         _invalidated_style = true;
632         _current_state = state;
633     }
636 /**
637  * \brief Updates _font_style according to the font set in parameter state
638  */
639 void SvgBuilder::updateFont(GfxState *state) {
641     TRACE(("updateFont()\n"));
642     _need_font_update = false;
643     // Flush buffered text before resetting matrices and font style
644     _flushText();
646     if (_font_style) {
647         //sp_repr_css_attr_unref(_font_style);
648     }
649     _font_style = sp_repr_css_attr_new();
650     GfxFont *font = state->getFont();
651     // Store original name
652     if (font->getOrigName()) {
653         _font_specification = font->getOrigName()->getCString();
654     } else {
655         _font_specification = font->getName()->getCString();
656     }
658     // Prune the font name to get the correct font family name
659     // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic
660     char *font_family = NULL;
661     char *font_style = NULL;
662     char *plus_sign = strstr(_font_specification, "+");
663     if (plus_sign) {
664         font_family = g_strdup(plus_sign + 1);
665         _font_specification = plus_sign + 1;
666     } else {
667         font_family = g_strdup(_font_specification);
668     }
669     char *minus_sign = g_strrstr(font_family, "-");
670     if (minus_sign) {
671         font_style = minus_sign + 1;
672         minus_sign[0] = 0;
673     }
675     // Font family
676     if (font->getFamily()) {
677         const gchar *family = font->getFamily()->getCString();
678         sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
679     } else {
680         sp_repr_css_set_property(_font_style, "font-family", font_family);
681     }
682     g_free(font_family);
684     // Font style
685     if (font->isItalic()) {
686         sp_repr_css_set_property(_font_style, "font-style", "italic");
687     }
689     // Font variant -- default 'normal' value
690     sp_repr_css_set_property(_font_style, "font-variant", "normal");
692     // Font weight
693     GfxFont::Weight font_weight = font->getWeight();
694     if ( font_weight != GfxFont::WeightNotDefined ) {
695         if ( font_weight == GfxFont::W400 ) {
696             sp_repr_css_set_property(_font_style, "font-weight", "normal");
697         } else if ( font_weight == GfxFont::W700 ) {
698             sp_repr_css_set_property(_font_style, "font-weight", "bold");
699         } else {
700             gchar weight_num[4] = "100";
701             weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
702             sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num);
703         }
704     }
706     // Font stretch
707     GfxFont::Stretch font_stretch = font->getStretch();
708     gchar *stretch_value = NULL;
709     switch (font_stretch) {
710         case GfxFont::UltraCondensed:
711             stretch_value = "ultra-condensed";
712             break;
713         case GfxFont::ExtraCondensed:
714             stretch_value = "extra-condensed";
715             break;
716         case GfxFont::Condensed:
717             stretch_value = "condensed";
718             break;
719         case GfxFont::SemiCondensed:
720             stretch_value = "semi-condensed";
721             break;
722         case GfxFont::Normal:
723             stretch_value = "normal";
724             break;
725         case GfxFont::SemiExpanded:
726             stretch_value = "semi-expanded";
727             break;
728         case GfxFont::Expanded:
729             stretch_value = "expanded";
730             break;
731         case GfxFont::ExtraExpanded:
732             stretch_value = "extra-expanded";
733             break;
734         case GfxFont::UltraExpanded:
735             stretch_value = "ultra-expanded";
736             break;
737         default:
738             break;
739     }
740     if ( stretch_value != NULL ) {
741         sp_repr_css_set_property(_font_style, "font-stretch", stretch_value);
742     }
744     // Font size
745     Inkscape::CSSOStringStream os_font_size;
746     double *text_matrix = state->getTextMat();
747     double font_size = sqrt( text_matrix[0] * text_matrix[3] - text_matrix[1] * text_matrix[2] );
748     font_size *= state->getFontSize() * state->getHorizScaling();
749     os_font_size << font_size;
750     sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
752     // Writing mode
753     if ( font->getWMode() == 0 ) {
754         sp_repr_css_set_property(_font_style, "writing-mode", "lr");
755     } else {
756         sp_repr_css_set_property(_font_style, "writing-mode", "tb");
757     }
759     // Calculate new text matrix
760     double *font_matrix = font->getFontMatrix();
761     NR::Matrix nr_font_matrix(font_matrix[0], font_matrix[1], font_matrix[2],
762                               font_matrix[3], font_matrix[4], font_matrix[5]);
763     NR::Matrix new_text_matrix(text_matrix[0], text_matrix[1],
764                                -text_matrix[2], -text_matrix[3],
765                                0.0, 0.0);
766     new_text_matrix *= NR::scale( 1.0 / font_size, 1.0 / font_size );
767     _text_matrix = nr_font_matrix * new_text_matrix;
769     _current_font = font;
772 /**
773  * \brief Writes the buffered characters to the SVG document
774  */
775 void SvgBuilder::_flushText() {
776     // Ignore empty strings
777     if ( _glyphs.size() < 1 ) {
778         _glyphs.clear();
779         return;
780     }
781     const SvgGlyph& first_glyph = _glyphs[0];
782     int render_mode = first_glyph.render_mode;
783     // Ignore invisible characters
784     if ( render_mode == 3 ) {
785         _glyphs.clear();
786         return;
787     }
789     Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
790     // Set current text position
791     sp_repr_set_svg_double(text_node, "x", first_glyph.transformed_position[0]);
792     sp_repr_set_svg_double(text_node, "y", first_glyph.transformed_position[1]);
793     // Set style
794     sp_repr_css_change(text_node, first_glyph.style, "style");
795     text_node->setAttribute("inkscape:font-specification", _font_specification);
796     // Set text matrix
797     gchar *transform = sp_svg_transform_write(_text_matrix);
798     text_node->setAttribute("transform", transform);
799     g_free(transform);
801     bool new_tspan = true;
802     Inkscape::XML::Node *tspan_node = NULL;
803     Glib::ustring x_coords;
804     Glib::ustring y_coords;
805     Glib::ustring text_buffer;
806     bool is_vertical = !strcmp(sp_repr_css_property(_font_style, "writing-mode", "lr"), "tb");  // FIXME
808     // Output all buffered glyphs
809     std::vector<SvgGlyph>::iterator i = _glyphs.begin();
810     while (1) {
811         const SvgGlyph& glyph = (*i);
812         std::vector<SvgGlyph>::iterator prev_iterator = i - 1;
813         // Check if we need to make a new tspan
814         if (glyph.style_changed) {
815             new_tspan = true;
816         } else if ( i != _glyphs.begin() ) {
817             const SvgGlyph& prev_glyph = (*prev_iterator);
818             if ( ( is_vertical && prev_glyph.transformed_position[0] != glyph.transformed_position[0] ) ||
819                  ( !is_vertical && prev_glyph.transformed_position[1] != glyph.transformed_position[1] ) ) {
820                 new_tspan = true;
821             }
822         }
823         // Create tspan node if needed
824         if ( new_tspan || i == _glyphs.end() ) {
825             if (tspan_node) {
826                 // Set the x and y coordinate arrays
827                 tspan_node->setAttribute("x", x_coords.c_str());
828                 tspan_node->setAttribute("y", y_coords.c_str());
829                 TRACE(("tspan content: %s\n", text_buffer.c_str()));
830                 // Add text content node to tspan
831                 Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str());
832                 tspan_node->appendChild(text_content);
833                 Inkscape::GC::release(text_content);
834                 text_node->appendChild(tspan_node);
835                 // Clear temporary buffers
836                 x_coords.clear();
837                 y_coords.clear();
838                 text_buffer.clear();
839                 Inkscape::GC::release(tspan_node);
840             }
841             if ( i == _glyphs.end() ) {
842                 sp_repr_css_attr_unref((*prev_iterator).style);
843                 break;
844             } else {
845                 tspan_node = _xml_doc->createElement("svg:tspan");
846                 // Set style and unref SPCSSAttr if it won't be needed anymore
847                 if ( i != _glyphs.begin() ) {
848                     sp_repr_css_change(tspan_node, glyph.style, "style");
849                     if (glyph.style_changed) {  // Free previous style
850                         sp_repr_css_attr_unref((*prev_iterator).style);
851                     }
852                 }
853             }
854             new_tspan = false;
855         }
856         if ( x_coords.length() > 0 ) {
857             x_coords.append(" ");
858             y_coords.append(" ");
859         }
860         // Append the coordinates to their respective strings
861         Inkscape::CSSOStringStream os_x;
862         os_x << glyph.transformed_position[0];
863         x_coords.append(os_x.str());
864         Inkscape::CSSOStringStream os_y;
865         os_y << glyph.transformed_position[1];
866         y_coords.append(os_y.str());
868         // Append the character to the text buffer
869         text_buffer.append((char *)&glyph.code, 1);
871         i++;
872     }
873     _container->appendChild(text_node);
874     Inkscape::GC::release(text_node);
876     _glyphs.clear();
879 void SvgBuilder::beginString(GfxState *state, GooString *s) {
880     if (_need_font_update) {
881         updateFont(state);
882     }
883     IFTRACE(double *m = state->getTextMat());
884     TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
885     IFTRACE(m = _current_font->getFontMatrix());
886     TRACE(("fm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
887     IFTRACE(m = state->getCTM());
888     TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
891 /**
892  * \brief Adds the specified character to the text buffer
893  * Takes care of converting it to UTF-8 and generates a new style repr if style
894  * has changed since the last call.
895  */
896 void SvgBuilder::addChar(GfxState *state, double x, double y,
897                          double dx, double dy,
898                          double originX, double originY,
899                          CharCode code, int nBytes, Unicode *u, int uLen) {
902     bool is_space = ( uLen == 1 && u[0] == 32 );
903     // Skip beginning space
904     if ( is_space && _glyphs.size() < 1 ) {
905          return;
906     }
907     // Allow only one space in a row
908     if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 &&
909          _glyphs[_glyphs.size() - 1].code[0] == 32 ) {
910         return;
911     }
913     SvgGlyph new_glyph;
914     new_glyph.is_space = is_space;
915     new_glyph.position = NR::Point( x - originX, y - originY );
916     new_glyph.transformed_position = new_glyph.position * _text_matrix;
917     new_glyph.dx = dx;
918     new_glyph.dy = dy;
920     // Convert the character to UTF-8 since that's our SVG document's encoding
921     static UnicodeMap *u_map = NULL;
922     if ( u_map == NULL ) {
923         GooString *enc = new GooString("UTF-8");
924         u_map = globalParams->getUnicodeMap(enc);
925         u_map->incRefCnt();
926         delete enc;
927     }
928     int code_size = 0;
929     for ( int i = 0 ; i < uLen ; i++ ) {
930         code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size);
931     }
932     new_glyph.code_size = code_size;
934     // Copy current style if it has changed since the previous glyph
935     if (_invalidated_style || _glyphs.size() == 0 ) {
936         new_glyph.style_changed = true;
937         int render_mode = state->getRender();
938         // Set style
939         bool has_fill = !( render_mode & 1 );
940         bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2;
941         new_glyph.style = _setStyle(state, has_fill, has_stroke);
942         new_glyph.render_mode = render_mode;
943         sp_repr_css_merge(new_glyph.style, _font_style); // Merge with font style
944         _invalidated_style = false;
945     } else {
946         new_glyph.style_changed = false;
947         // Point to previous glyph's style information
948         const SvgGlyph& prev_glyph = _glyphs.back();
949         new_glyph.style = prev_glyph.style;
950         new_glyph.render_mode = prev_glyph.render_mode;
951     }
952     _glyphs.push_back(new_glyph);
955 void SvgBuilder::endString(GfxState *state) {
958 void SvgBuilder::beginTextObject(GfxState *state) {
959     _in_text_object = true;
960     _invalidated_style = true;  // Force copying of current state
961     _current_state = state;
964 void SvgBuilder::endTextObject(GfxState *state) {
965     _flushText();
966     // TODO: clip if render_mode >= 4
967     _in_text_object = false;
970 /**
971  * Helper functions for supporting direct PNG output into a base64 encoded stream
972  */
973 void png_write_base64stream(png_structp png_ptr, png_bytep data, png_size_t length)
975     Inkscape::IO::Base64OutputStream *stream =
976             (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
977     for ( unsigned i = 0 ; i < length ; i++ ) {
978         stream->put((int)data[i]);
979     }
982 void png_flush_base64stream(png_structp png_ptr)
984     Inkscape::IO::Base64OutputStream *stream =
985             (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
986     stream->flush();
989 /**
990  * \brief Creates an <image> element containing the given ImageStream as a PNG
991  *
992  */
993 Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height,
994         GfxImageColorMap *color_map, int *mask_colors, bool alpha_only, bool invert_alpha) {
996     // Create PNG write struct
997     png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
998     if ( png_ptr == NULL ) {
999         return NULL;
1000     }
1001     // Create PNG info struct
1002     png_infop info_ptr = png_create_info_struct(png_ptr);
1003     if ( info_ptr == NULL ) {
1004         png_destroy_write_struct(&png_ptr, NULL);
1005         return NULL;
1006     }
1007     // Set error handler
1008     if (setjmp(png_ptr->jmpbuf)) {
1009         png_destroy_write_struct(&png_ptr, &info_ptr);
1010         return NULL;
1011     }
1013     // Set read/write functions
1014     Inkscape::IO::StringOutputStream base64_string;
1015     Inkscape::IO::Base64OutputStream base64_stream(base64_string);
1016     FILE *fp;
1017     gchar *file_name;
1018     bool embed_image = true;
1019     if (embed_image) {
1020         base64_stream.setColumnWidth(0);   // Disable line breaks
1021         png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream);
1022     } else {
1023         static int counter = 0;
1024         file_name = g_strdup_printf("createImage%d.png", counter++);
1025         fp = fopen(file_name, "wb");
1026         if ( fp == NULL ) {
1027             png_destroy_write_struct(&png_ptr, &info_ptr);
1028             g_free(file_name);
1029             return NULL;
1030         }
1031         png_init_io(png_ptr, fp);
1032     }
1034     // Set header data
1035     if (!invert_alpha) {
1036         png_set_invert_alpha(png_ptr);
1037     }
1038     png_color_8 sig_bit;
1039     if (alpha_only) {
1040         png_set_IHDR(png_ptr, info_ptr,
1041                      width,
1042                      height,
1043                      8, /* bit_depth */
1044                      PNG_COLOR_TYPE_GRAY,
1045                      PNG_INTERLACE_NONE,
1046                      PNG_COMPRESSION_TYPE_BASE,
1047                      PNG_FILTER_TYPE_BASE);
1048         sig_bit.red = 0;
1049         sig_bit.green = 0;
1050         sig_bit.blue = 0;
1051         sig_bit.gray = 8;
1052         sig_bit.alpha = 0;
1053     } else {
1054         png_set_IHDR(png_ptr, info_ptr,
1055                      width,
1056                      height,
1057                      8, /* bit_depth */
1058                      PNG_COLOR_TYPE_RGB_ALPHA,
1059                      PNG_INTERLACE_NONE,
1060                      PNG_COMPRESSION_TYPE_BASE,
1061                      PNG_FILTER_TYPE_BASE);
1062         sig_bit.red = 8;
1063         sig_bit.green = 8;
1064         sig_bit.blue = 8;
1065         sig_bit.alpha = 8;
1066     }
1067     png_set_sBIT(png_ptr, info_ptr, &sig_bit);
1068     png_set_bgr(png_ptr);
1069     // Write the file header
1070     png_write_info(png_ptr, info_ptr);
1072     // Convert pixels
1073     ImageStream *image_stream;
1074     if (alpha_only) {
1075         if (color_map) {
1076             image_stream = new ImageStream(str, width, color_map->getNumPixelComps(),
1077                                            color_map->getBits());
1078         } else {
1079             image_stream = new ImageStream(str, width, 1, 1);
1080         }
1081         image_stream->reset();
1083         // Convert grayscale values
1084         if (color_map) {
1085             unsigned char *buffer = new unsigned char[width];
1086             for ( int y = 0 ; y < height ; y++ ) {
1087                 unsigned char *row = image_stream->getLine();
1088                 color_map->getGrayLine(row, buffer, width);
1089                 png_write_row(png_ptr, (png_bytep)buffer);
1090             }
1091             delete buffer;
1092         } else {
1093             for ( int y = 0 ; y < height ; y++ ) {
1094                 unsigned char *row = image_stream->getLine();
1095                 png_write_row(png_ptr, (png_bytep)row);
1096             }
1097         }
1098     } else if (color_map) {
1099         image_stream = new ImageStream(str, width,
1100                                        color_map->getNumPixelComps(),
1101                                        color_map->getBits());
1102         image_stream->reset();
1104         // Convert RGB values
1105         unsigned int *buffer = new unsigned int[width];
1106         if (mask_colors) {
1107             for ( int y = 0 ; y < height ; y++ ) {
1108                 unsigned char *row = image_stream->getLine();
1109                 color_map->getRGBLine(row, buffer, width);
1111                 unsigned int *dest = buffer;
1112                 for ( int x = 0 ; x < width ; x++ ) {
1113                     // Check each color component against the mask
1114                     for ( int i = 0; i < color_map->getNumPixelComps() ; i++) {
1115                         if ( row[i] < mask_colors[2*i] * 255 ||
1116                              row[i] > mask_colors[2*i + 1] * 255 ) {
1117                             *dest = *dest | 0xff000000;
1118                             break;
1119                         }
1120                     }
1121                     // Advance to the next pixel
1122                     row += color_map->getNumPixelComps();
1123                     dest++;
1124                 }
1125                 // Write it to the PNG
1126                 png_write_row(png_ptr, (png_bytep)buffer);
1127             }
1128         } else {
1129             for ( int i = 0 ; i < height ; i++ ) {
1130                 unsigned char *row = image_stream->getLine();
1131                 memset((void*)buffer, 0xff, sizeof(int) * width);
1132                 color_map->getRGBLine(row, buffer, width);
1133                 png_write_row(png_ptr, (png_bytep)buffer);
1134             }
1135         }
1136         delete buffer;
1138     } else {    // A colormap must be provided, so quit
1139         png_destroy_write_struct(&png_ptr, &info_ptr);
1140         if (!embed_image) {
1141             fclose(fp);
1142             g_free(file_name);
1143         }
1144         return NULL;
1145     }
1146     delete image_stream;
1147     str->close();
1148     // Close PNG
1149     png_write_end(png_ptr, info_ptr);
1150     png_destroy_write_struct(&png_ptr, &info_ptr);
1151     base64_stream.close();
1153     // Create repr
1154     Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image");
1155     sp_repr_set_svg_double(image_node, "width", width);
1156     sp_repr_set_svg_double(image_node, "height", height);
1157     // Set transformation
1158     svgSetTransform(image_node, 1.0/(double)width, 0.0, 0.0, -1.0/(double)height, 0.0, 1.0);
1160     // Create href
1161     if (embed_image) {
1162         // Append format specification to the URI
1163         Glib::ustring& png_data = base64_string.getString();
1164         png_data.insert(0, "data:image/png;base64,");
1165         image_node->setAttribute("xlink:href", png_data.c_str());
1166     } else {
1167         fclose(fp);
1168         image_node->setAttribute("xlink:href", file_name);
1169         g_free(file_name);
1170     }
1172     return image_node;
1175 void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height,
1176                           GfxImageColorMap *color_map, int *mask_colors) {
1178      Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, mask_colors);
1179      if (image_node) {
1180          _container->appendChild(image_node);
1181         Inkscape::GC::release(image_node);
1182      }
1186 } } } /* namespace Inkscape, Extension, Internal */
1188 #endif /* HAVE_POPPLER */
1190 /*
1191   Local Variables:
1192   mode:c++
1193   c-file-style:"stroustrup"
1194   c-file-offsets:((innamespace . 0)(inline-open . 0))
1195   indent-tabs-mode:nil
1196   fill-column:99
1197   End:
1198 */
1199 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :