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