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