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 = (double)color->r / 65535.0;
171 double g = (double)color->g / 65535.0;
172 double b = (double)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 Emits the current path in poppler's GfxState data structure
387 * The path is set to be filled with the given shading.
388 */
389 void SvgBuilder::addShadedFill(GfxShading *shading, double *matrix, GfxPath *path,
390 bool even_odd) {
392 Inkscape::XML::Node *path_node = _xml_doc->createElement("svg:path");
393 gchar *pathtext = svgInterpretPath(path);
394 path_node->setAttribute("d", pathtext);
395 g_free(pathtext);
397 // Set style
398 SPCSSAttr *css = sp_repr_css_attr_new();
399 gchar *id = _createGradient(shading, matrix, true);
400 if (id) {
401 gchar *urltext = g_strdup_printf ("url(#%s)", id);
402 sp_repr_css_set_property(css, "fill", urltext);
403 g_free(urltext);
404 g_free(id);
405 } else {
406 sp_repr_css_attr_unref(css);
407 Inkscape::GC::release(path_node);
408 return;
409 }
410 if (even_odd) {
411 sp_repr_css_set_property(css, "fill-rule", "evenodd");
412 }
413 sp_repr_css_set_property(css, "stroke", "none");
414 sp_repr_css_change(path_node, css, "style");
415 sp_repr_css_attr_unref(css);
417 _container->appendChild(path_node);
418 Inkscape::GC::release(path_node);
419 }
421 /**
422 * \brief Clips to the current path set in GfxState
423 * \param state poppler's data structure
424 * \param even_odd whether the even-odd rule should be applied
425 */
426 void SvgBuilder::clip(GfxState *state, bool even_odd) {
427 pushGroup();
428 setClipPath(state, even_odd);
429 }
431 void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
432 // Create the clipPath repr
433 Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath");
434 clip_path->setAttribute("clipPathUnits", "userSpaceOnUse");
435 // Create the path
436 Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
437 gchar *pathtext = svgInterpretPath(state->getPath());
438 path->setAttribute("d", pathtext);
439 g_free(pathtext);
440 if (even_odd) {
441 path->setAttribute("clip-rule", "evenodd");
442 }
443 clip_path->appendChild(path);
444 Inkscape::GC::release(path);
445 // Append clipPath to defs and get id
446 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(clip_path);
447 gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id"));
448 Inkscape::GC::release(clip_path);
449 _container->setAttribute("clip-path", urltext);
450 g_free(urltext);
451 }
453 /**
454 * \brief Fills the given array with the current container's transform, if set
455 * \param transform array of doubles to be filled
456 * \return true on success; false on invalid transformation
457 */
458 bool SvgBuilder::getTransform(double *transform) {
459 NR::Matrix svd;
460 gchar const *tr = _container->attribute("transform");
461 bool valid = sp_svg_transform_read(tr, &svd);
462 if (valid) {
463 for ( int i = 0 ; i < 6 ; i++ ) {
464 transform[i] = svd[i];
465 }
466 return true;
467 } else {
468 return false;
469 }
470 }
472 /**
473 * \brief Sets the transformation matrix of the current container
474 */
475 void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
476 double c4, double c5) {
478 TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
479 svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
480 }
482 void SvgBuilder::setTransform(double *transform) {
483 setTransform(transform[0], transform[1], transform[2], transform[3],
484 transform[4], transform[5]);
485 }
487 /**
488 * \brief Checks whether the given pattern type can be represented in SVG
489 * Used by PdfParser to decide when to do fallback operations.
490 */
491 bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) {
492 if ( pattern != NULL ) {
493 if ( pattern->getType() == 2 ) { // shading pattern
494 GfxShading *shading = ((GfxShadingPattern *)pattern)->getShading();
495 int shadingType = shading->getType();
496 if ( shadingType == 2 || // axial shading
497 shadingType == 3 ) { // radial shading
498 return true;
499 }
500 return false;
501 } else if ( pattern->getType() == 1 ) { // tiling pattern
502 return true;
503 }
504 }
506 return false;
507 }
509 /**
510 * \brief Creates a pattern from poppler's data structure
511 * Handles linear and radial gradients. Creates a new PdfParser and uses it to
512 * build a tiling pattern.
513 * \return an url pointing to the created pattern
514 */
515 gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) {
516 gchar *id = NULL;
517 if ( pattern != NULL ) {
518 if ( pattern->getType() == 2 ) { // Shading pattern
519 GfxShadingPattern *shading_pattern = (GfxShadingPattern*)pattern;
520 id = _createGradient(shading_pattern->getShading(),
521 shading_pattern->getMatrix());
522 } else if ( pattern->getType() == 1 ) { // Tiling pattern
523 id = _createTilingPattern((GfxTilingPattern*)pattern, state, is_stroke);
524 }
525 } else {
526 return NULL;
527 }
528 gchar *urltext = g_strdup_printf ("url(#%s)", id);
529 g_free(id);
530 return urltext;
531 }
533 /**
534 * \brief Creates a tiling pattern from poppler's data structure
535 * Creates a sub-page PdfParser and uses it to parse the pattern's content stream.
536 * \return id of the created pattern
537 */
538 gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
539 GfxState *state, bool is_stroke) {
541 Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
542 // Set pattern transform matrix
543 double *p2u = tiling_pattern->getMatrix();
544 NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
545 gchar *transform_text = sp_svg_transform_write(pat_matrix);
546 pattern_node->setAttribute("patternTransform", transform_text);
547 g_free(transform_text);
548 pattern_node->setAttribute("patternUnits", "userSpaceOnUse");
549 // Set pattern tiling
550 // FIXME: don't ignore XStep and YStep
551 double *bbox = tiling_pattern->getBBox();
552 sp_repr_set_svg_double(pattern_node, "x", 0.0);
553 sp_repr_set_svg_double(pattern_node, "y", 0.0);
554 sp_repr_set_svg_double(pattern_node, "width", bbox[2] - bbox[0]);
555 sp_repr_set_svg_double(pattern_node, "height", bbox[3] - bbox[1]);
557 // Convert BBox for PdfParser
558 PDFRectangle box;
559 box.x1 = bbox[0];
560 box.y1 = bbox[1];
561 box.x2 = bbox[2];
562 box.y2 = bbox[3];
563 // Create new SvgBuilder and sub-page PdfParser
564 SvgBuilder *pattern_builder = new SvgBuilder(this, pattern_node);
565 PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(),
566 &box);
567 // Get pattern color space
568 GfxPatternColorSpace *pat_cs = (GfxPatternColorSpace *)( is_stroke ? state->getStrokeColorSpace()
569 : state->getFillColorSpace() );
570 // Set fill/stroke colors if this is an uncolored tiling pattern
571 GfxColorSpace *cs = NULL;
572 if ( tiling_pattern->getPaintType() == 2 && ( cs = pat_cs->getUnder() ) ) {
573 GfxState *pattern_state = pdf_parser->getState();
574 pattern_state->setFillColorSpace(cs->copy());
575 pattern_state->setFillColor(state->getFillColor());
576 pattern_state->setStrokeColorSpace(cs->copy());
577 pattern_state->setStrokeColor(state->getFillColor());
578 }
580 // Generate the SVG pattern
581 pdf_parser->parse(tiling_pattern->getContentStream());
583 // Cleanup
584 delete pdf_parser;
585 delete pattern_builder;
587 // Append the pattern to defs
588 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(pattern_node);
589 gchar *id = g_strdup(pattern_node->attribute("id"));
590 Inkscape::GC::release(pattern_node);
592 return id;
593 }
595 /**
596 * \brief Creates a linear or radial gradient from poppler's data structure
597 * \param shading poppler's data structure for the shading
598 * \param matrix gradient transformation, can be null
599 * \param for_shading true if we're creating this for a shading operator; false otherwise
600 * \return id of the created object
601 */
602 gchar *SvgBuilder::_createGradient(GfxShading *shading, double *matrix, bool for_shading) {
603 Inkscape::XML::Node *gradient;
604 Function *func;
605 int num_funcs;
606 bool extend0, extend1;
608 if ( shading->getType() == 2 ) { // Axial shading
609 gradient = _xml_doc->createElement("svg:linearGradient");
610 GfxAxialShading *axial_shading = (GfxAxialShading*)shading;
611 double x1, y1, x2, y2;
612 axial_shading->getCoords(&x1, &y1, &x2, &y2);
613 sp_repr_set_svg_double(gradient, "x1", x1);
614 sp_repr_set_svg_double(gradient, "y1", y1);
615 sp_repr_set_svg_double(gradient, "x2", x2);
616 sp_repr_set_svg_double(gradient, "y2", y2);
617 extend0 = axial_shading->getExtend0();
618 extend1 = axial_shading->getExtend1();
619 num_funcs = axial_shading->getNFuncs();
620 func = axial_shading->getFunc(0);
621 } else if (shading->getType() == 3) { // Radial shading
622 gradient = _xml_doc->createElement("svg:radialGradient");
623 GfxRadialShading *radial_shading = (GfxRadialShading*)shading;
624 double x1, y1, r1, x2, y2, r2;
625 radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2);
626 // FIXME: the inner circle's radius is ignored here
627 sp_repr_set_svg_double(gradient, "fx", x1);
628 sp_repr_set_svg_double(gradient, "fy", y1);
629 sp_repr_set_svg_double(gradient, "cx", x2);
630 sp_repr_set_svg_double(gradient, "cy", y2);
631 sp_repr_set_svg_double(gradient, "r", r2);
632 extend0 = radial_shading->getExtend0();
633 extend1 = radial_shading->getExtend1();
634 num_funcs = radial_shading->getNFuncs();
635 func = radial_shading->getFunc(0);
636 } else { // Unsupported shading type
637 return NULL;
638 }
639 gradient->setAttribute("gradientUnits", "userSpaceOnUse");
640 // If needed, flip the gradient transform around the y axis
641 if (matrix) {
642 NR::Matrix pat_matrix(matrix[0], matrix[1], matrix[2], matrix[3],
643 matrix[4], matrix[5]);
644 if ( !for_shading && _is_top_level ) {
645 NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
646 pat_matrix *= flip;
647 }
648 gchar *transform_text = sp_svg_transform_write(pat_matrix);
649 gradient->setAttribute("gradientTransform", transform_text);
650 g_free(transform_text);
651 }
653 if ( extend0 && extend1 ) {
654 gradient->setAttribute("spreadMethod", "pad");
655 }
657 if ( num_funcs > 1 || !_addGradientStops(gradient, shading, func) ) {
658 Inkscape::GC::release(gradient);
659 return NULL;
660 }
662 Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc));
663 defs->appendChild(gradient);
664 gchar *id = g_strdup(gradient->attribute("id"));
665 Inkscape::GC::release(gradient);
667 return id;
668 }
670 #define EPSILON 0.0001
671 /**
672 * \brief Adds a stop with the given properties to the gradient's representation
673 */
674 void SvgBuilder::_addStopToGradient(Inkscape::XML::Node *gradient, double offset,
675 GfxRGB *color, double opacity) {
676 Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
677 SPCSSAttr *css = sp_repr_css_attr_new();
678 Inkscape::CSSOStringStream os_opacity;
679 os_opacity << opacity;
680 sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
681 gchar *color_text = svgConvertGfxRGB(color);
682 sp_repr_css_set_property(css, "stop-color", color_text);
684 sp_repr_css_change(stop, css, "style");
685 sp_repr_css_attr_unref(css);
686 sp_repr_set_css_double(stop, "offset", offset);
688 gradient->appendChild(stop);
689 Inkscape::GC::release(stop);
690 }
692 static bool svgGetShadingColorRGB(GfxShading *shading, double offset, GfxRGB *result) {
693 GfxColorSpace *color_space = shading->getColorSpace();
694 GfxColor temp;
695 if ( shading->getType() == 2 ) { // Axial shading
696 ((GfxAxialShading*)shading)->getColor(offset, &temp);
697 } else if ( shading->getType() == 3 ) { // Radial shading
698 ((GfxRadialShading*)shading)->getColor(offset, &temp);
699 } else {
700 return false;
701 }
702 // Convert it to RGB
703 color_space->getRGB(&temp, result);
705 return true;
706 }
708 #define INT_EPSILON 8
709 bool SvgBuilder::_addGradientStops(Inkscape::XML::Node *gradient, GfxShading *shading,
710 Function *func) {
711 int type = func->getType();
712 if ( type == 0 || type == 2 ) { // Sampled or exponential function
713 GfxRGB stop1, stop2;
714 if ( !svgGetShadingColorRGB(shading, 0.0, &stop1) ||
715 !svgGetShadingColorRGB(shading, 1.0, &stop2) ) {
716 return false;
717 } else {
718 _addStopToGradient(gradient, 0.0, &stop1, 1.0);
719 _addStopToGradient(gradient, 1.0, &stop2, 1.0);
720 }
721 } else if ( type == 3 ) { // Stitching
722 StitchingFunction *stitchingFunc = (StitchingFunction*)func;
723 double *bounds = stitchingFunc->getBounds();
724 int num_funcs = stitchingFunc->getNumFuncs();
725 // Add stops from all the stitched functions
726 for ( int i = 0 ; i < num_funcs ; i++ ) {
727 GfxRGB color;
728 svgGetShadingColorRGB(shading, bounds[i], &color);
729 bool is_continuation = false;
730 if ( i > 0 ) { // Compare to previous stop
731 GfxRGB prev_color;
732 svgGetShadingColorRGB(shading, bounds[i-1], &prev_color);
733 if ( abs(color.r - prev_color.r) < INT_EPSILON &&
734 abs(color.g - prev_color.g) < INT_EPSILON &&
735 abs(color.b - prev_color.b) < INT_EPSILON ) {
736 is_continuation = true;
737 }
738 }
739 // Add stops
740 if ( !is_continuation ) {
741 _addStopToGradient(gradient, bounds[i], &color, 1.0);
742 }
743 if ( is_continuation || ( i == num_funcs - 1 ) ) {
744 GfxRGB next_color;
745 svgGetShadingColorRGB(shading, bounds[i+1], &next_color);
746 _addStopToGradient(gradient, bounds[i+1], &next_color, 1.0);
747 }
748 }
749 } else { // Unsupported function type
750 return false;
751 }
753 return true;
754 }
756 /**
757 * \brief Sets _invalidated_style to true to indicate that styles have to be updated
758 * Used for text output when glyphs are buffered till a font change
759 */
760 void SvgBuilder::updateStyle(GfxState *state) {
761 if (_in_text_object) {
762 _invalidated_style = true;
763 _current_state = state;
764 }
765 }
767 /**
768 * This array holds info about translating font weight names to more or less CSS equivalents
769 */
770 static char *font_weight_translator[][2] = {
771 {"bold", "bold"},
772 {"light", "300"},
773 {"black", "900"},
774 {"heavy", "900"},
775 {"ultrabold", "800"},
776 {"extrabold", "800"},
777 {"demibold", "600"},
778 {"semibold", "600"},
779 {"medium", "500"},
780 {"book", "normal"},
781 {"regular", "normal"},
782 {"roman", "normal"},
783 {"normal", "normal"},
784 {"ultralight", "200"},
785 {"extralight", "200"},
786 {"thin", "100"}
787 };
789 /**
790 * \brief Updates _font_style according to the font set in parameter state
791 */
792 void SvgBuilder::updateFont(GfxState *state) {
794 TRACE(("updateFont()\n"));
795 _need_font_update = false;
797 if (_font_style) {
798 //sp_repr_css_attr_unref(_font_style);
799 }
800 _font_style = sp_repr_css_attr_new();
801 GfxFont *font = state->getFont();
802 // Store original name
803 if (font->getOrigName()) {
804 _font_specification = font->getOrigName()->getCString();
805 } else if (font->getName()) {
806 _font_specification = font->getName()->getCString();
807 } else {
808 _font_specification = "Arial";
809 }
811 // Prune the font name to get the correct font family name
812 // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic
813 char *font_family = NULL;
814 char *font_style = NULL;
815 char *font_style_lowercase = NULL;
816 char *plus_sign = strstr(_font_specification, "+");
817 if (plus_sign) {
818 font_family = g_strdup(plus_sign + 1);
819 _font_specification = plus_sign + 1;
820 } else {
821 font_family = g_strdup(_font_specification);
822 }
823 char *style_delim = NULL;
824 if ( ( style_delim = g_strrstr(font_family, "-") ) ||
825 ( style_delim = g_strrstr(font_family, ",") ) ) {
826 font_style = style_delim + 1;
827 font_style_lowercase = g_ascii_strdown(font_style, -1);
828 style_delim[0] = 0;
829 }
831 // Font family
832 if (font->getFamily()) {
833 sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
834 } else {
835 sp_repr_css_set_property(_font_style, "font-family", font_family);
836 }
838 // Font style
839 if (font->isItalic()) {
840 sp_repr_css_set_property(_font_style, "font-style", "italic");
841 } else if (font_style) {
842 if ( strstr(font_style_lowercase, "italic") ||
843 strstr(font_style_lowercase, "slanted") ) {
844 sp_repr_css_set_property(_font_style, "font-style", "italic");
845 } else if (strstr(font_style_lowercase, "oblique")) {
846 sp_repr_css_set_property(_font_style, "font-style", "oblique");
847 }
848 }
850 // Font variant -- default 'normal' value
851 sp_repr_css_set_property(_font_style, "font-variant", "normal");
853 // Font weight
854 GfxFont::Weight font_weight = font->getWeight();
855 char *css_font_weight = NULL;
856 if ( font_weight != GfxFont::WeightNotDefined ) {
857 if ( font_weight == GfxFont::W400 ) {
858 css_font_weight = "normal";
859 } else if ( font_weight == GfxFont::W700 ) {
860 css_font_weight = "bold";
861 } else {
862 gchar weight_num[4] = "100";
863 weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
864 sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num);
865 }
866 } else if (font_style) {
867 // Apply the font weight translations
868 int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) );
869 for ( int i = 0 ; i < num_translations ; i++ ) {
870 if (strstr(font_style_lowercase, font_weight_translator[i][0])) {
871 css_font_weight = font_weight_translator[i][1];
872 }
873 }
874 } else {
875 css_font_weight = "normal";
876 }
877 if (css_font_weight) {
878 sp_repr_css_set_property(_font_style, "font-weight", css_font_weight);
879 }
880 g_free(font_family);
881 if (font_style_lowercase) {
882 g_free(font_style_lowercase);
883 }
885 // Font stretch
886 GfxFont::Stretch font_stretch = font->getStretch();
887 gchar *stretch_value = NULL;
888 switch (font_stretch) {
889 case GfxFont::UltraCondensed:
890 stretch_value = "ultra-condensed";
891 break;
892 case GfxFont::ExtraCondensed:
893 stretch_value = "extra-condensed";
894 break;
895 case GfxFont::Condensed:
896 stretch_value = "condensed";
897 break;
898 case GfxFont::SemiCondensed:
899 stretch_value = "semi-condensed";
900 break;
901 case GfxFont::Normal:
902 stretch_value = "normal";
903 break;
904 case GfxFont::SemiExpanded:
905 stretch_value = "semi-expanded";
906 break;
907 case GfxFont::Expanded:
908 stretch_value = "expanded";
909 break;
910 case GfxFont::ExtraExpanded:
911 stretch_value = "extra-expanded";
912 break;
913 case GfxFont::UltraExpanded:
914 stretch_value = "ultra-expanded";
915 break;
916 default:
917 break;
918 }
919 if ( stretch_value != NULL ) {
920 sp_repr_css_set_property(_font_style, "font-stretch", stretch_value);
921 }
923 // Font size
924 Inkscape::CSSOStringStream os_font_size;
925 double *text_matrix = state->getTextMat();
926 double w_scale = sqrt( text_matrix[0] * text_matrix[0] + text_matrix[2] * text_matrix[2] );
927 double h_scale = sqrt( text_matrix[1] * text_matrix[1] + text_matrix[3] * text_matrix[3] );
928 double max_scale;
929 if ( w_scale > h_scale ) {
930 max_scale = w_scale;
931 } else {
932 max_scale = h_scale;
933 }
934 double css_font_size = max_scale * state->getFontSize();
935 if ( font->getType() == fontType3 ) {
936 double *font_matrix = font->getFontMatrix();
937 if ( font_matrix[0] != 0.0 ) {
938 css_font_size *= font_matrix[3] / font_matrix[0];
939 }
940 }
942 os_font_size << css_font_size;
943 sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
945 // Writing mode
946 if ( font->getWMode() == 0 ) {
947 sp_repr_css_set_property(_font_style, "writing-mode", "lr");
948 } else {
949 sp_repr_css_set_property(_font_style, "writing-mode", "tb");
950 }
952 // Calculate new text matrix
953 NR::Matrix new_text_matrix(text_matrix[0] * state->getHorizScaling(),
954 text_matrix[1] * state->getHorizScaling(),
955 -text_matrix[2], -text_matrix[3],
956 0.0, 0.0);
958 if ( fabs( max_scale - 1.0 ) > EPSILON ) {
959 // Cancel out scaling by font size in text matrix
960 for ( int i = 0 ; i < 4 ; i++ ) {
961 new_text_matrix[i] /= max_scale;
962 }
963 }
964 _text_matrix = new_text_matrix;
965 _font_scaling = max_scale;
966 _current_font = font;
967 _invalidated_style = true;
968 }
970 /**
971 * \brief Shifts the current text position by the given amount (specified in text space)
972 */
973 void SvgBuilder::updateTextShift(GfxState *state, double shift) {
974 double shift_value = -shift * 0.001 * fabs(state->getFontSize());
975 if (state->getFont()->getWMode()) {
976 _text_position[1] += shift_value;
977 } else {
978 _text_position[0] += shift_value;
979 }
980 }
982 /**
983 * \brief Updates current text position
984 */
985 void SvgBuilder::updateTextPosition(double tx, double ty) {
986 NR::Point new_position(tx, ty);
987 _text_position = new_position;
988 }
990 /**
991 * \brief Flushes the buffered characters
992 */
993 void SvgBuilder::updateTextMatrix(GfxState *state) {
994 _flushText();
995 updateFont(state); // Update text matrix
996 }
998 /**
999 * \brief Writes the buffered characters to the SVG document
1000 */
1001 void SvgBuilder::_flushText() {
1002 // Ignore empty strings
1003 if ( _glyphs.size() < 1 ) {
1004 _glyphs.clear();
1005 return;
1006 }
1007 std::vector<SvgGlyph>::iterator i = _glyphs.begin();
1008 const SvgGlyph& first_glyph = (*i);
1009 int render_mode = first_glyph.render_mode;
1010 // Ignore invisible characters
1011 if ( render_mode == 3 ) {
1012 _glyphs.clear();
1013 return;
1014 }
1016 Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
1017 // Set text matrix
1018 NR::Matrix text_transform(_text_matrix);
1019 text_transform[4] = first_glyph.position[0];
1020 text_transform[5] = first_glyph.position[1];
1021 gchar *transform = sp_svg_transform_write(text_transform);
1022 text_node->setAttribute("transform", transform);
1023 g_free(transform);
1025 bool new_tspan = true;
1026 unsigned int glyphs_in_a_row = 0;
1027 Inkscape::XML::Node *tspan_node = NULL;
1028 Glib::ustring x_coords;
1029 Glib::ustring y_coords;
1030 Glib::ustring text_buffer;
1031 bool is_vertical = !strcmp(sp_repr_css_property(_font_style, "writing-mode", "lr"), "tb"); // FIXME
1033 // Output all buffered glyphs
1034 while (1) {
1035 const SvgGlyph& glyph = (*i);
1036 std::vector<SvgGlyph>::iterator prev_iterator = i - 1;
1037 // Check if we need to make a new tspan
1038 if (glyph.style_changed) {
1039 new_tspan = true;
1040 } else if ( i != _glyphs.begin() ) {
1041 const SvgGlyph& prev_glyph = (*prev_iterator);
1042 if ( !( ( glyph.dy == 0.0 && prev_glyph.dy == 0.0 &&
1043 glyph.text_position[1] == prev_glyph.text_position[1] ) ||
1044 ( glyph.dx == 0.0 && prev_glyph.dx == 0.0 &&
1045 glyph.text_position[0] == prev_glyph.text_position[0] ) ) ) {
1046 new_tspan = true;
1047 }
1048 }
1050 // Create tspan node if needed
1051 if ( new_tspan || i == _glyphs.end() ) {
1052 if (tspan_node) {
1053 // Set the x and y coordinate arrays
1054 tspan_node->setAttribute("x", x_coords.c_str());
1055 tspan_node->setAttribute("y", y_coords.c_str());
1056 TRACE(("tspan content: %s\n", text_buffer.c_str()));
1057 if ( glyphs_in_a_row > 1 ) {
1058 tspan_node->setAttribute("sodipodi:role", "line");
1059 }
1060 // Add text content node to tspan
1061 Inkscape::XML::Node *text_content = _xml_doc->createTextNode(text_buffer.c_str());
1062 tspan_node->appendChild(text_content);
1063 Inkscape::GC::release(text_content);
1064 text_node->appendChild(tspan_node);
1065 // Clear temporary buffers
1066 x_coords.clear();
1067 y_coords.clear();
1068 text_buffer.clear();
1069 Inkscape::GC::release(tspan_node);
1070 glyphs_in_a_row = 0;
1071 }
1072 if ( i == _glyphs.end() ) {
1073 sp_repr_css_attr_unref((*prev_iterator).style);
1074 break;
1075 } else {
1076 tspan_node = _xml_doc->createElement("svg:tspan");
1077 tspan_node->setAttribute("inkscape:font-specification", glyph.font_specification);
1078 // Set style and unref SPCSSAttr if it won't be needed anymore
1079 sp_repr_css_change(tspan_node, glyph.style, "style");
1080 if ( glyph.style_changed && i != _glyphs.begin() ) { // Free previous style
1081 sp_repr_css_attr_unref((*prev_iterator).style);
1082 }
1083 }
1084 new_tspan = false;
1085 }
1086 if ( glyphs_in_a_row > 0 ) {
1087 x_coords.append(" ");
1088 y_coords.append(" ");
1089 }
1090 // Append the coordinates to their respective strings
1091 NR::Point delta_pos( glyph.text_position - first_glyph.text_position );
1092 delta_pos[1] += glyph.rise;
1093 delta_pos[1] *= -1.0; // flip it
1094 delta_pos *= _font_scaling;
1095 Inkscape::CSSOStringStream os_x;
1096 os_x << delta_pos[0];
1097 x_coords.append(os_x.str());
1098 Inkscape::CSSOStringStream os_y;
1099 os_y << delta_pos[1];
1100 y_coords.append(os_y.str());
1102 // Append the character to the text buffer
1103 text_buffer.append((char *)&glyph.code, 1);
1105 glyphs_in_a_row++;
1106 i++;
1107 }
1108 _container->appendChild(text_node);
1109 Inkscape::GC::release(text_node);
1111 _glyphs.clear();
1112 }
1114 void SvgBuilder::beginString(GfxState *state, GooString *s) {
1115 if (_need_font_update) {
1116 updateFont(state);
1117 }
1118 IFTRACE(double *m = state->getTextMat());
1119 TRACE(("tm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1120 IFTRACE(m = state->getCTM());
1121 TRACE(("ctm: %f %f %f %f %f %f\n",m[0], m[1],m[2], m[3], m[4], m[5]));
1122 }
1124 /**
1125 * \brief Adds the specified character to the text buffer
1126 * Takes care of converting it to UTF-8 and generates a new style repr if style
1127 * has changed since the last call.
1128 */
1129 void SvgBuilder::addChar(GfxState *state, double x, double y,
1130 double dx, double dy,
1131 double originX, double originY,
1132 CharCode code, int nBytes, Unicode *u, int uLen) {
1135 bool is_space = ( uLen == 1 && u[0] == 32 );
1136 // Skip beginning space
1137 if ( is_space && _glyphs.size() < 1 ) {
1138 NR::Point delta(dx, dy);
1139 _text_position += delta;
1140 return;
1141 }
1142 // Allow only one space in a row
1143 if ( is_space && _glyphs[_glyphs.size() - 1].code_size == 1 &&
1144 _glyphs[_glyphs.size() - 1].code[0] == 32 ) {
1145 NR::Point delta(dx, dy);
1146 _text_position += delta;
1147 return;
1148 }
1150 SvgGlyph new_glyph;
1151 new_glyph.is_space = is_space;
1152 new_glyph.position = NR::Point( x - originX, y - originY );
1153 new_glyph.text_position = _text_position;
1154 new_glyph.dx = dx;
1155 new_glyph.dy = dy;
1156 NR::Point delta(dx, dy);
1157 _text_position += delta;
1159 // Convert the character to UTF-8 since that's our SVG document's encoding
1160 static UnicodeMap *u_map = NULL;
1161 if ( u_map == NULL ) {
1162 GooString *enc = new GooString("UTF-8");
1163 u_map = globalParams->getUnicodeMap(enc);
1164 u_map->incRefCnt();
1165 delete enc;
1166 }
1167 int code_size = 0;
1168 for ( int i = 0 ; i < uLen ; i++ ) {
1169 code_size += u_map->mapUnicode(u[i], (char *)&new_glyph.code[code_size], sizeof(new_glyph.code) - code_size);
1170 }
1171 new_glyph.code_size = code_size;
1173 // Copy current style if it has changed since the previous glyph
1174 if (_invalidated_style || _glyphs.size() == 0 ) {
1175 new_glyph.style_changed = true;
1176 int render_mode = state->getRender();
1177 // Set style
1178 bool has_fill = !( render_mode & 1 );
1179 bool has_stroke = ( render_mode & 3 ) == 1 || ( render_mode & 3 ) == 2;
1180 new_glyph.style = _setStyle(state, has_fill, has_stroke);
1181 new_glyph.render_mode = render_mode;
1182 sp_repr_css_merge(new_glyph.style, _font_style); // Merge with font style
1183 _invalidated_style = false;
1184 } else {
1185 new_glyph.style_changed = false;
1186 // Point to previous glyph's style information
1187 const SvgGlyph& prev_glyph = _glyphs.back();
1188 new_glyph.style = prev_glyph.style;
1189 new_glyph.render_mode = prev_glyph.render_mode;
1190 }
1191 new_glyph.font_specification = _font_specification;
1192 new_glyph.rise = state->getRise();
1194 _glyphs.push_back(new_glyph);
1195 }
1197 void SvgBuilder::endString(GfxState *state) {
1198 }
1200 void SvgBuilder::beginTextObject(GfxState *state) {
1201 _in_text_object = true;
1202 _invalidated_style = true; // Force copying of current state
1203 _current_state = state;
1204 }
1206 void SvgBuilder::endTextObject(GfxState *state) {
1207 _flushText();
1208 // TODO: clip if render_mode >= 4
1209 _in_text_object = false;
1210 }
1212 /**
1213 * Helper functions for supporting direct PNG output into a base64 encoded stream
1214 */
1215 void png_write_base64stream(png_structp png_ptr, png_bytep data, png_size_t length)
1216 {
1217 Inkscape::IO::Base64OutputStream *stream =
1218 (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1219 for ( unsigned i = 0 ; i < length ; i++ ) {
1220 stream->put((int)data[i]);
1221 }
1222 }
1224 void png_flush_base64stream(png_structp png_ptr)
1225 {
1226 Inkscape::IO::Base64OutputStream *stream =
1227 (Inkscape::IO::Base64OutputStream*)png_get_io_ptr(png_ptr); // Get pointer to stream
1228 stream->flush();
1229 }
1231 /**
1232 * \brief Creates an <image> element containing the given ImageStream as a PNG
1233 *
1234 */
1235 Inkscape::XML::Node *SvgBuilder::_createImage(Stream *str, int width, int height,
1236 GfxImageColorMap *color_map, int *mask_colors, bool alpha_only, bool invert_alpha) {
1238 // Create PNG write struct
1239 png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
1240 if ( png_ptr == NULL ) {
1241 return NULL;
1242 }
1243 // Create PNG info struct
1244 png_infop info_ptr = png_create_info_struct(png_ptr);
1245 if ( info_ptr == NULL ) {
1246 png_destroy_write_struct(&png_ptr, NULL);
1247 return NULL;
1248 }
1249 // Set error handler
1250 if (setjmp(png_ptr->jmpbuf)) {
1251 png_destroy_write_struct(&png_ptr, &info_ptr);
1252 return NULL;
1253 }
1255 // Set read/write functions
1256 Inkscape::IO::StringOutputStream base64_string;
1257 Inkscape::IO::Base64OutputStream base64_stream(base64_string);
1258 FILE *fp;
1259 gchar *file_name;
1260 bool embed_image = true;
1261 if (embed_image) {
1262 base64_stream.setColumnWidth(0); // Disable line breaks
1263 png_set_write_fn(png_ptr, &base64_stream, png_write_base64stream, png_flush_base64stream);
1264 } else {
1265 static int counter = 0;
1266 file_name = g_strdup_printf("%s_img%d.png", _docname, counter++);
1267 fp = fopen(file_name, "wb");
1268 if ( fp == NULL ) {
1269 png_destroy_write_struct(&png_ptr, &info_ptr);
1270 g_free(file_name);
1271 return NULL;
1272 }
1273 png_init_io(png_ptr, fp);
1274 }
1276 // Set header data
1277 if ( !invert_alpha && !alpha_only ) {
1278 png_set_invert_alpha(png_ptr);
1279 }
1280 png_color_8 sig_bit;
1281 if (alpha_only) {
1282 png_set_IHDR(png_ptr, info_ptr,
1283 width,
1284 height,
1285 8, /* bit_depth */
1286 PNG_COLOR_TYPE_GRAY,
1287 PNG_INTERLACE_NONE,
1288 PNG_COMPRESSION_TYPE_BASE,
1289 PNG_FILTER_TYPE_BASE);
1290 sig_bit.red = 0;
1291 sig_bit.green = 0;
1292 sig_bit.blue = 0;
1293 sig_bit.gray = 8;
1294 sig_bit.alpha = 0;
1295 } else {
1296 png_set_IHDR(png_ptr, info_ptr,
1297 width,
1298 height,
1299 8, /* bit_depth */
1300 PNG_COLOR_TYPE_RGB_ALPHA,
1301 PNG_INTERLACE_NONE,
1302 PNG_COMPRESSION_TYPE_BASE,
1303 PNG_FILTER_TYPE_BASE);
1304 sig_bit.red = 8;
1305 sig_bit.green = 8;
1306 sig_bit.blue = 8;
1307 sig_bit.alpha = 8;
1308 }
1309 png_set_sBIT(png_ptr, info_ptr, &sig_bit);
1310 png_set_bgr(png_ptr);
1311 // Write the file header
1312 png_write_info(png_ptr, info_ptr);
1314 // Convert pixels
1315 ImageStream *image_stream;
1316 if (alpha_only) {
1317 if (color_map) {
1318 image_stream = new ImageStream(str, width, color_map->getNumPixelComps(),
1319 color_map->getBits());
1320 } else {
1321 image_stream = new ImageStream(str, width, 1, 1);
1322 }
1323 image_stream->reset();
1325 // Convert grayscale values
1326 unsigned char *buffer = NULL;
1327 if ( color_map || invert_alpha ) {
1328 buffer = new unsigned char[width];
1329 }
1330 if ( color_map ) {
1331 for ( int y = 0 ; y < height ; y++ ) {
1332 unsigned char *row = image_stream->getLine();
1333 color_map->getGrayLine(row, buffer, width);
1334 if (invert_alpha) {
1335 unsigned char *buf_ptr = buffer;
1336 for ( int x = 0 ; x < width ; x++ ) {
1337 *buf_ptr++ = ~(*buf_ptr);
1338 }
1339 }
1340 png_write_row(png_ptr, (png_bytep)buffer);
1341 }
1342 } else {
1343 for ( int y = 0 ; y < height ; y++ ) {
1344 unsigned char *row = image_stream->getLine();
1345 if (invert_alpha) {
1346 unsigned char *buf_ptr = buffer;
1347 for ( int x = 0 ; x < width ; x++ ) {
1348 *buf_ptr++ = ~row[x];
1349 }
1350 png_write_row(png_ptr, (png_bytep)buffer);
1351 } else {
1352 png_write_row(png_ptr, (png_bytep)row);
1353 }
1354 }
1355 }
1356 if (buffer) {
1357 delete buffer;
1358 }
1359 } else if (color_map) {
1360 image_stream = new ImageStream(str, width,
1361 color_map->getNumPixelComps(),
1362 color_map->getBits());
1363 image_stream->reset();
1365 // Convert RGB values
1366 unsigned int *buffer = new unsigned int[width];
1367 if (mask_colors) {
1368 for ( int y = 0 ; y < height ; y++ ) {
1369 unsigned char *row = image_stream->getLine();
1370 color_map->getRGBLine(row, buffer, width);
1372 unsigned int *dest = buffer;
1373 for ( int x = 0 ; x < width ; x++ ) {
1374 // Check each color component against the mask
1375 for ( int i = 0; i < color_map->getNumPixelComps() ; i++) {
1376 if ( row[i] < mask_colors[2*i] * 255 ||
1377 row[i] > mask_colors[2*i + 1] * 255 ) {
1378 *dest = *dest | 0xff000000;
1379 break;
1380 }
1381 }
1382 // Advance to the next pixel
1383 row += color_map->getNumPixelComps();
1384 dest++;
1385 }
1386 // Write it to the PNG
1387 png_write_row(png_ptr, (png_bytep)buffer);
1388 }
1389 } else {
1390 for ( int i = 0 ; i < height ; i++ ) {
1391 unsigned char *row = image_stream->getLine();
1392 memset((void*)buffer, 0xff, sizeof(int) * width);
1393 color_map->getRGBLine(row, buffer, width);
1394 png_write_row(png_ptr, (png_bytep)buffer);
1395 }
1396 }
1397 delete buffer;
1399 } else { // A colormap must be provided, so quit
1400 png_destroy_write_struct(&png_ptr, &info_ptr);
1401 if (!embed_image) {
1402 fclose(fp);
1403 g_free(file_name);
1404 }
1405 return NULL;
1406 }
1407 delete image_stream;
1408 str->close();
1409 // Close PNG
1410 png_write_end(png_ptr, info_ptr);
1411 png_destroy_write_struct(&png_ptr, &info_ptr);
1412 base64_stream.close();
1414 // Create repr
1415 Inkscape::XML::Node *image_node = _xml_doc->createElement("svg:image");
1416 sp_repr_set_svg_double(image_node, "width", 1);
1417 sp_repr_set_svg_double(image_node, "height", 1);
1418 // Set transformation
1419 if (_is_top_level) {
1420 svgSetTransform(image_node, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1421 }
1423 // Create href
1424 if (embed_image) {
1425 // Append format specification to the URI
1426 Glib::ustring& png_data = base64_string.getString();
1427 png_data.insert(0, "data:image/png;base64,");
1428 image_node->setAttribute("xlink:href", png_data.c_str());
1429 } else {
1430 fclose(fp);
1431 image_node->setAttribute("xlink:href", file_name);
1432 g_free(file_name);
1433 }
1435 return image_node;
1436 }
1438 /**
1439 * \brief Creates a <mask> with the specified width and height and adds to <defs>
1440 * If we're not the top-level SvgBuilder, creates a <defs> too and adds the mask to it.
1441 * \return the created XML node
1442 */
1443 Inkscape::XML::Node *SvgBuilder::_createMask(double width, double height) {
1444 Inkscape::XML::Node *mask_node = _xml_doc->createElement("svg:mask");
1445 mask_node->setAttribute("maskUnits", "userSpaceOnUse");
1446 sp_repr_set_svg_double(mask_node, "x", 0.0);
1447 sp_repr_set_svg_double(mask_node, "y", 0.0);
1448 sp_repr_set_svg_double(mask_node, "width", width);
1449 sp_repr_set_svg_double(mask_node, "height", height);
1450 // Append mask to defs
1451 if (_is_top_level) {
1452 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(mask_node);
1453 Inkscape::GC::release(mask_node);
1454 return SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->lastChild();
1455 } else { // Work around for renderer bug when mask isn't defined in pattern
1456 static int mask_count = 0;
1457 Inkscape::XML::Node *defs = _root->firstChild();
1458 Inkscape::XML::Node *result = NULL;
1459 if ( !( defs && !strcmp(defs->name(), "svg:defs") ) ) {
1460 // Create <defs> node
1461 defs = _xml_doc->createElement("svg:defs");
1462 _root->addChild(defs, NULL);
1463 Inkscape::GC::release(defs);
1464 defs = _root->firstChild();
1465 }
1466 gchar *mask_id = g_strdup_printf("_mask%d", mask_count++);
1467 mask_node->setAttribute("id", mask_id);
1468 g_free(mask_id);
1469 defs->appendChild(mask_node);
1470 Inkscape::GC::release(mask_node);
1471 return defs->lastChild();
1472 }
1473 }
1475 void SvgBuilder::addImage(GfxState *state, Stream *str, int width, int height,
1476 GfxImageColorMap *color_map, int *mask_colors) {
1478 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, mask_colors);
1479 if (image_node) {
1480 _container->appendChild(image_node);
1481 Inkscape::GC::release(image_node);
1482 }
1483 }
1485 void SvgBuilder::addImageMask(GfxState *state, Stream *str, int width, int height,
1486 bool invert) {
1488 // Create a rectangle
1489 Inkscape::XML::Node *rect = _xml_doc->createElement("svg:rect");
1490 sp_repr_set_svg_double(rect, "x", 0.0);
1491 sp_repr_set_svg_double(rect, "y", 0.0);
1492 sp_repr_set_svg_double(rect, "width", 1.0);
1493 sp_repr_set_svg_double(rect, "height", 1.0);
1494 svgSetTransform(rect, 1.0, 0.0, 0.0, -1.0, 0.0, 1.0);
1495 // Get current fill style and set it on the rectangle
1496 SPCSSAttr *css = sp_repr_css_attr_new();
1497 _setFillStyle(css, state, false);
1498 sp_repr_css_change(rect, css, "style");
1499 sp_repr_css_attr_unref(css);
1501 // Scaling 1x1 surfaces might not work so skip setting a mask with this size
1502 if ( width > 1 || height > 1 ) {
1503 Inkscape::XML::Node *mask_image_node = _createImage(str, width, height, NULL, NULL, true, invert);
1504 if (mask_image_node) {
1505 // Create the mask
1506 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1507 // Remove unnecessary transformation from the mask image
1508 mask_image_node->setAttribute("transform", NULL);
1509 mask_node->appendChild(mask_image_node);
1510 Inkscape::GC::release(mask_image_node);
1511 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1512 rect->setAttribute("mask", mask_url);
1513 g_free(mask_url);
1514 }
1515 }
1517 // Add the rectangle to the container
1518 _container->appendChild(rect);
1519 Inkscape::GC::release(rect);
1520 }
1522 void SvgBuilder::addMaskedImage(GfxState *state, Stream *str, int width, int height,
1523 GfxImageColorMap *color_map,
1524 Stream *mask_str, int mask_width, int mask_height,
1525 bool invert_mask) {
1527 Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1528 NULL, NULL, true, invert_mask);
1529 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1530 if ( mask_image_node && image_node ) {
1531 // Create mask for the image
1532 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1533 // Remove unnecessary transformation from the mask image
1534 mask_image_node->setAttribute("transform", NULL);
1535 mask_node->appendChild(mask_image_node);
1536 // Scale the mask to the size of the image
1537 NR::Matrix mask_transform((double)width, 0.0, 0.0, (double)height, 0.0, 0.0);
1538 gchar *transform_text = sp_svg_transform_write(mask_transform);
1539 mask_node->setAttribute("maskTransform", transform_text);
1540 g_free(transform_text);
1541 // Set mask and add image
1542 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1543 image_node->setAttribute("mask", mask_url);
1544 g_free(mask_url);
1545 _container->appendChild(image_node);
1546 }
1547 if (mask_image_node) {
1548 Inkscape::GC::release(mask_image_node);
1549 }
1550 if (image_node) {
1551 Inkscape::GC::release(image_node);
1552 }
1553 }
1555 void SvgBuilder::addSoftMaskedImage(GfxState *state, Stream *str, int width, int height,
1556 GfxImageColorMap *color_map,
1557 Stream *mask_str, int mask_width, int mask_height,
1558 GfxImageColorMap *mask_color_map) {
1560 Inkscape::XML::Node *mask_image_node = _createImage(mask_str, mask_width, mask_height,
1561 mask_color_map, NULL, true);
1562 Inkscape::XML::Node *image_node = _createImage(str, width, height, color_map, NULL);
1563 if ( mask_image_node && image_node ) {
1564 // Create mask for the image
1565 Inkscape::XML::Node *mask_node = _createMask(1.0, 1.0);
1566 // Remove unnecessary transformation from the mask image
1567 mask_image_node->setAttribute("transform", NULL);
1568 mask_node->appendChild(mask_image_node);
1569 // Set mask and add image
1570 gchar *mask_url = g_strdup_printf("url(#%s)", mask_node->attribute("id"));
1571 image_node->setAttribute("mask", mask_url);
1572 g_free(mask_url);
1573 _container->appendChild(image_node);
1574 }
1575 if (mask_image_node) {
1576 Inkscape::GC::release(mask_image_node);
1577 }
1578 if (image_node) {
1579 Inkscape::GC::release(image_node);
1580 }
1581 }
1583 } } } /* namespace Inkscape, Extension, Internal */
1585 #endif /* HAVE_POPPLER */
1587 /*
1588 Local Variables:
1589 mode:c++
1590 c-file-style:"stroustrup"
1591 c-file-offsets:((innamespace . 0)(inline-open . 0))
1592 indent-tabs-mode:nil
1593 fill-column:99
1594 End:
1595 */
1596 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :