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 SvgBuilder();
78 }
80 SvgBuilder::SvgBuilder(SvgBuilder *parent, Inkscape::XML::Node *root) {
81 _doc = parent->_doc;
82 _xref = parent->_xref;
83 _xml_doc = parent->_xml_doc;
84 _container = this->_root = root;
85 SvgBuilder();
86 }
88 SvgBuilder::~SvgBuilder() {
89 }
91 void SvgBuilder::setDocumentSize(double width, double height) {
92 sp_repr_set_svg_double(_root, "width", width);
93 sp_repr_set_svg_double(_root, "height", height);
94 this->_width = width;
95 this->_height = height;
96 }
98 void SvgBuilder::saveState() {
99 _group_depth.push_back(0);
100 pushGroup();
101 }
103 void SvgBuilder::restoreState() {
104 while (_group_depth.back() > 0) {
105 popGroup();
106 }
107 _group_depth.pop_back();
108 }
110 Inkscape::XML::Node *SvgBuilder::pushGroup() {
111 Inkscape::XML::Node *node = _xml_doc->createElement("svg:g");
112 _container->appendChild(node);
113 _container = node;
114 Inkscape::GC::release(node);
115 _group_depth.back()++;
117 return _container;
118 }
120 Inkscape::XML::Node *SvgBuilder::popGroup() {
121 if (_container != _root) { // Pop if the current container isn't root
122 _container = _container->parent();
123 _group_depth[_group_depth.size()-1] = --_group_depth.back();
124 }
126 return _container;
127 }
129 Inkscape::XML::Node *SvgBuilder::getContainer() {
130 return _container;
131 }
133 static gchar *svgConvertRGBToText(double r, double g, double b) {
134 static gchar tmp[1023] = {0};
135 snprintf(tmp, 1023,
136 "#%02x%02x%02x",
137 CLAMP(SP_COLOR_F_TO_U(r), 0, 255),
138 CLAMP(SP_COLOR_F_TO_U(g), 0, 255),
139 CLAMP(SP_COLOR_F_TO_U(b), 0, 255));
140 return (gchar *)&tmp;
141 }
143 static gchar *svgConvertGfxRGB(GfxRGB *color) {
144 double r = color->r / 65535.0;
145 double g = color->g / 65535.0;
146 double b = color->b / 65535.0;
147 return svgConvertRGBToText(r, g, b);
148 }
150 static void svgSetTransform(Inkscape::XML::Node *node, double c0, double c1,
151 double c2, double c3, double c4, double c5) {
152 NR::Matrix matrix(c0, c1, c2, c3, c4, c5);
153 gchar *transform_text = sp_svg_transform_write(matrix);
154 node->setAttribute("transform", transform_text);
155 g_free(transform_text);
156 }
158 static void svgSetTransform(Inkscape::XML::Node *node, double *transform) {
159 svgSetTransform(node, transform[0], transform[1], transform[2], transform[3],
160 transform[4], transform[5]);
161 }
163 /**
164 * \brief Generates a SVG path string from poppler's data structure
165 */
166 static gchar *svgInterpretPath(GfxPath *path) {
167 GfxSubpath *subpath;
168 Inkscape::SVG::PathString pathString;
169 int i, j;
170 for ( i = 0 ; i < path->getNumSubpaths() ; ++i ) {
171 subpath = path->getSubpath(i);
172 if (subpath->getNumPoints() > 0) {
173 pathString.moveTo(subpath->getX(0), subpath->getY(0));
174 j = 1;
175 while (j < subpath->getNumPoints()) {
176 if (subpath->getCurve(j)) {
177 pathString.curveTo(subpath->getX(j), subpath->getY(j),
178 subpath->getX(j+1), subpath->getY(j+1),
179 subpath->getX(j+2), subpath->getY(j+2));
181 j += 3;
182 } else {
183 pathString.lineTo(subpath->getX(j), subpath->getY(j));
184 ++j;
185 }
186 }
187 if (subpath->isClosed()) {
188 pathString.closePath();
189 }
190 }
191 }
193 return g_strdup(pathString.c_str());
194 }
196 /**
197 * \brief Sets stroke style from poppler's GfxState data structure
198 * Uses the given SPCSSAttr for storing the style properties
199 */
200 void SvgBuilder::_setStrokeStyle(SPCSSAttr *css, GfxState *state) {
202 // Check line width
203 if ( state->getLineWidth() <= 0.0 ) {
204 // Ignore stroke
205 sp_repr_css_set_property(css, "stroke", "none");
206 return;
207 }
209 // Stroke color/pattern
210 if ( state->getStrokeColorSpace()->getMode() == csPattern ) {
211 gchar *urltext = _createPattern(state->getStrokePattern(), state, true);
212 sp_repr_css_set_property(css, "stroke", urltext);
213 if (urltext) {
214 g_free(urltext);
215 }
216 } else {
217 GfxRGB stroke_color;
218 state->getStrokeRGB(&stroke_color);
219 sp_repr_css_set_property(css, "stroke", svgConvertGfxRGB(&stroke_color));
220 }
222 // Opacity
223 Inkscape::CSSOStringStream os_opacity;
224 os_opacity << state->getStrokeOpacity();
225 sp_repr_css_set_property(css, "stroke-opacity", os_opacity.str().c_str());
227 // Line width
228 Inkscape::CSSOStringStream os_width;
229 os_width << state->getLineWidth();
230 sp_repr_css_set_property(css, "stroke-width", os_width.str().c_str());
232 // Line cap
233 switch (state->getLineCap()) {
234 case 0:
235 sp_repr_css_set_property(css, "stroke-linecap", "butt");
236 break;
237 case 1:
238 sp_repr_css_set_property(css, "stroke-linecap", "round");
239 break;
240 case 2:
241 sp_repr_css_set_property(css, "stroke-linecap", "square");
242 break;
243 }
245 // Line join
246 switch (state->getLineJoin()) {
247 case 0:
248 sp_repr_css_set_property(css, "stroke-linejoin", "miter");
249 break;
250 case 1:
251 sp_repr_css_set_property(css, "stroke-linejoin", "round");
252 break;
253 case 2:
254 sp_repr_css_set_property(css, "stroke-linejoin", "bevel");
255 break;
256 }
258 // Miterlimit
259 Inkscape::CSSOStringStream os_ml;
260 os_ml << state->getMiterLimit();
261 sp_repr_css_set_property(css, "stroke-miterlimit", os_ml.str().c_str());
263 // Line dash
264 double *dash_pattern;
265 int dash_length;
266 double dash_start;
267 state->getLineDash(&dash_pattern, &dash_length, &dash_start);
268 if ( dash_length > 0 ) {
269 Inkscape::CSSOStringStream os_array;
270 for ( int i = 0 ; i < dash_length ; i++ ) {
271 os_array << dash_pattern[i];
272 if (i < (dash_length - 1)) {
273 os_array << ",";
274 }
275 }
276 sp_repr_css_set_property(css, "stroke-dasharray", os_array.str().c_str());
278 Inkscape::CSSOStringStream os_offset;
279 os_offset << dash_start;
280 sp_repr_css_set_property(css, "stroke-dashoffset", os_offset.str().c_str());
281 } else {
282 sp_repr_css_set_property(css, "stroke-dasharray", "none");
283 sp_repr_css_set_property(css, "stroke-dashoffset", NULL);
284 }
285 }
287 /**
288 * \brief Sets fill style from poppler's GfxState data structure
289 * Uses the given SPCSSAttr for storing the style properties.
290 */
291 void SvgBuilder::_setFillStyle(SPCSSAttr *css, GfxState *state, bool even_odd) {
293 // Fill color/pattern
294 if ( state->getFillColorSpace()->getMode() == csPattern ) {
295 gchar *urltext = _createPattern(state->getFillPattern(), state);
296 sp_repr_css_set_property(css, "fill", urltext);
297 if (urltext) {
298 g_free(urltext);
299 }
300 } else {
301 GfxRGB fill_color;
302 state->getFillRGB(&fill_color);
303 sp_repr_css_set_property(css, "fill", svgConvertGfxRGB(&fill_color));
304 }
306 // Opacity
307 Inkscape::CSSOStringStream os_opacity;
308 os_opacity << state->getFillOpacity();
309 sp_repr_css_set_property(css, "fill-opacity", os_opacity.str().c_str());
311 // Fill rule
312 sp_repr_css_set_property(css, "fill-rule", even_odd ? "evenodd" : "nonzero");
313 }
315 /**
316 * \brief Sets style properties from poppler's GfxState data structure
317 * \return SPCSSAttr with all the relevant properties set
318 */
319 SPCSSAttr *SvgBuilder::_setStyle(GfxState *state, bool fill, bool stroke, bool even_odd) {
320 SPCSSAttr *css = sp_repr_css_attr_new();
321 if (fill) {
322 _setFillStyle(css, state, even_odd);
323 } else {
324 sp_repr_css_set_property(css, "fill", "none");
325 }
327 if (stroke) {
328 _setStrokeStyle(css, state);
329 } else {
330 sp_repr_css_set_property(css, "stroke", "none");
331 }
333 return css;
334 }
336 /**
337 * \brief Emits the current path in poppler's GfxState data structure
338 * Can be used to do filling and stroking at once.
339 *
340 * \param fill whether the path should be filled
341 * \param stroke whether the path should be stroked
342 * \param even_odd whether the even-odd rule should be used when filling the path
343 */
344 void SvgBuilder::addPath(GfxState *state, bool fill, bool stroke, bool even_odd) {
345 Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
346 gchar *pathtext = svgInterpretPath(state->getPath());
347 path->setAttribute("d", pathtext);
348 g_free(pathtext);
350 // Set style
351 SPCSSAttr *css = _setStyle(state, fill, stroke, even_odd);
352 sp_repr_css_change(path, css, "style");
353 sp_repr_css_attr_unref(css);
355 _container->appendChild(path);
356 Inkscape::GC::release(path);
357 }
359 /**
360 * \brief Clips to the current path set in GfxState
361 * \param state poppler's data structure
362 * \param even_odd whether the even-odd rule should be applied
363 */
364 void SvgBuilder::clip(GfxState *state, bool even_odd) {
365 pushGroup();
366 setClipPath(state, even_odd);
367 }
369 void SvgBuilder::setClipPath(GfxState *state, bool even_odd) {
370 // Create the clipPath repr
371 Inkscape::XML::Node *clip_path = _xml_doc->createElement("svg:clipPath");
372 clip_path->setAttribute("clipPathUnits", "userSpaceOnUse");
373 // Create the path
374 Inkscape::XML::Node *path = _xml_doc->createElement("svg:path");
375 gchar *pathtext = svgInterpretPath(state->getPath());
376 path->setAttribute("d", pathtext);
377 g_free(pathtext);
378 clip_path->appendChild(path);
379 Inkscape::GC::release(path);
380 // Append clipPath to defs and get id
381 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(clip_path);
382 gchar *urltext = g_strdup_printf ("url(#%s)", clip_path->attribute("id"));
383 Inkscape::GC::release(clip_path);
384 _container->setAttribute("clip-path", urltext);
385 g_free(urltext);
386 }
388 /**
389 * \brief Fills the given array with the current container's transform, if set
390 * \param transform array of doubles to be filled
391 * \return true on success; false on invalid transformation
392 */
393 bool SvgBuilder::getTransform(double *transform) {
394 NR::Matrix svd;
395 gchar const *tr = _container->attribute("transform");
396 bool valid = sp_svg_transform_read(tr, &svd);
397 if (valid) {
398 for ( int i = 0 ; i < 6 ; i++ ) {
399 transform[i] = svd[i];
400 }
401 return true;
402 } else {
403 return false;
404 }
405 }
407 /**
408 * \brief Sets the transformation matrix of the current container
409 */
410 void SvgBuilder::setTransform(double c0, double c1, double c2, double c3,
411 double c4, double c5) {
413 TRACE(("setTransform: %f %f %f %f %f %f\n", c0, c1, c2, c3, c4, c5));
414 svgSetTransform(_container, c0, c1, c2, c3, c4, c5);
415 }
417 void SvgBuilder::setTransform(double *transform) {
418 setTransform(transform[0], transform[1], transform[2], transform[3],
419 transform[4], transform[5]);
420 }
422 /**
423 * \brief Checks whether the given pattern type can be represented in SVG
424 * Used by PdfParser to decide when to do fallback operations.
425 */
426 bool SvgBuilder::isPatternTypeSupported(GfxPattern *pattern) {
427 if ( pattern != NULL ) {
428 if ( pattern->getType() == 2 ) { // shading pattern
429 GfxShading *shading = ((GfxShadingPattern *)pattern)->getShading();
430 int shadingType = shading->getType();
431 if ( shadingType == 2 || // axial shading
432 shadingType == 3 ) { // radial shading
433 return true;
434 }
435 return false;
436 } else if ( pattern->getType() == 1 ) { // tiling pattern
437 return true;
438 }
439 }
441 return false;
442 }
444 /**
445 * \brief Creates a pattern from poppler's data structure
446 * Handles linear and radial gradients. Creates a new PdfParser and uses it to
447 * build a tiling pattern.
448 * \return an url pointing to the created pattern
449 */
450 gchar *SvgBuilder::_createPattern(GfxPattern *pattern, GfxState *state, bool is_stroke) {
451 gchar *id = NULL;
452 if ( pattern != NULL ) {
453 if ( pattern->getType() == 2 ) { // Shading pattern
454 id = _createGradient((GfxShadingPattern*)pattern);
455 } else if ( pattern->getType() == 1 ) { // Tiling pattern
456 id = _createTilingPattern((GfxTilingPattern*)pattern, state, is_stroke);
457 }
458 } else {
459 return NULL;
460 }
461 gchar *urltext = g_strdup_printf ("url(#%s)", id);
462 g_free(id);
463 return urltext;
464 }
466 /**
467 * \brief Creates a tiling pattern from poppler's data structure
468 * Creates a sub-page PdfParser and uses it to parse the pattern's content stream.
469 * \return id of the created pattern
470 */
471 gchar *SvgBuilder::_createTilingPattern(GfxTilingPattern *tiling_pattern,
472 GfxState *state, bool is_stroke) {
474 Inkscape::XML::Node *pattern_node = _xml_doc->createElement("svg:pattern");
475 // Set pattern transform matrix
476 double *p2u = tiling_pattern->getMatrix();
477 NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
478 gchar *transform_text = sp_svg_transform_write(pat_matrix);
479 pattern_node->setAttribute("patternTransform", transform_text);
480 g_free(transform_text);
481 pattern_node->setAttribute("patternUnits", "userSpaceOnUse");
482 // Set pattern tiling
483 // FIXME: don't ignore XStep and YStep
484 double *bbox = tiling_pattern->getBBox();
485 sp_repr_set_svg_double(pattern_node, "x", 0.0);
486 sp_repr_set_svg_double(pattern_node, "y", 0.0);
487 sp_repr_set_svg_double(pattern_node, "width", bbox[2] - bbox[0]);
488 sp_repr_set_svg_double(pattern_node, "height", bbox[3] - bbox[1]);
490 // Convert BBox for PdfParser
491 PDFRectangle box;
492 box.x1 = bbox[0];
493 box.y1 = bbox[1];
494 box.x2 = bbox[2];
495 box.y2 = bbox[3];
496 // Create new SvgBuilder and sub-page PdfParser
497 SvgBuilder *pattern_builder = new SvgBuilder(this, pattern_node);
498 PdfParser *pdf_parser = new PdfParser(_xref, pattern_builder, tiling_pattern->getResDict(),
499 &box);
500 // Get pattern color space
501 GfxPatternColorSpace *pat_cs = (GfxPatternColorSpace *)( is_stroke ? state->getStrokeColorSpace()
502 : state->getFillColorSpace() );
503 // Set fill/stroke colors if this is an uncolored tiling pattern
504 GfxColorSpace *cs = NULL;
505 if ( tiling_pattern->getPaintType() == 2 && ( cs = pat_cs->getUnder() ) ) {
506 GfxState *pattern_state = pdf_parser->getState();
507 pattern_state->setFillColorSpace(cs->copy());
508 pattern_state->setFillColor(state->getFillColor());
509 pattern_state->setStrokeColorSpace(cs->copy());
510 pattern_state->setStrokeColor(state->getFillColor());
511 }
513 // Generate the SVG pattern
514 pdf_parser->parse(tiling_pattern->getContentStream());
516 // Cleanup
517 delete pdf_parser;
518 delete pattern_builder;
520 // Append the pattern to defs
521 SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc))->appendChild(pattern_node);
522 gchar *id = g_strdup(pattern_node->attribute("id"));
523 Inkscape::GC::release(pattern_node);
525 return id;
526 }
528 /**
529 * \brief Creates a linear or radial gradient from poppler's data structure
530 * \return id of the created object
531 */
532 gchar *SvgBuilder::_createGradient(GfxShadingPattern *shading_pattern) {
533 GfxShading *shading = shading_pattern->getShading();
534 Inkscape::XML::Node *gradient;
535 Function *func;
536 int num_funcs;
537 bool extend0, extend1;
539 if ( shading->getType() == 2 ) { // Axial shading
540 gradient = _xml_doc->createElement("svg:linearGradient");
541 GfxAxialShading *axial_shading = (GfxAxialShading*)shading;
542 double x1, y1, x2, y2;
543 axial_shading->getCoords(&x1, &y1, &x2, &y2);
544 sp_repr_set_svg_double(gradient, "x1", x1);
545 sp_repr_set_svg_double(gradient, "y1", y1);
546 sp_repr_set_svg_double(gradient, "x2", x2);
547 sp_repr_set_svg_double(gradient, "y2", y2);
548 extend0 = axial_shading->getExtend0();
549 extend1 = axial_shading->getExtend1();
550 num_funcs = axial_shading->getNFuncs();
551 func = axial_shading->getFunc(0);
552 } else if (shading->getType() == 3) { // Radial shading
553 gradient = _xml_doc->createElement("svg:radialGradient");
554 GfxRadialShading *radial_shading = (GfxRadialShading*)shading;
555 double x1, y1, r1, x2, y2, r2;
556 radial_shading->getCoords(&x1, &y1, &r1, &x2, &y2, &r2);
557 // FIXME: the inner circle's radius is ignored here
558 sp_repr_set_svg_double(gradient, "fx", x1);
559 sp_repr_set_svg_double(gradient, "fy", y1);
560 sp_repr_set_svg_double(gradient, "cx", x2);
561 sp_repr_set_svg_double(gradient, "cy", y2);
562 sp_repr_set_svg_double(gradient, "r", r2);
563 extend0 = radial_shading->getExtend0();
564 extend1 = radial_shading->getExtend1();
565 num_funcs = radial_shading->getNFuncs();
566 func = radial_shading->getFunc(0);
567 } else { // Unsupported shading type
568 return NULL;
569 }
570 gradient->setAttribute("gradientUnits", "userSpaceOnUse");
571 // Flip the gradient transform around the y axis
572 double *p2u = shading_pattern->getMatrix();
573 NR::Matrix pat_matrix(p2u[0], p2u[1], p2u[2], p2u[3], p2u[4], p2u[5]);
574 NR::Matrix flip(1.0, 0.0, 0.0, -1.0, 0.0, _height * PT_PER_PX);
575 pat_matrix *= flip;
576 gchar *transform_text = sp_svg_transform_write(pat_matrix);
577 gradient->setAttribute("gradientTransform", transform_text);
578 g_free(transform_text);
580 if ( extend0 && extend1 ) {
581 gradient->setAttribute("spreadMethod", "pad");
582 }
584 if ( num_funcs > 1 || !_addStopsToGradient(gradient, func, 1.0) ) {
585 Inkscape::GC::release(gradient);
586 return NULL;
587 }
589 Inkscape::XML::Node *defs = SP_OBJECT_REPR (SP_DOCUMENT_DEFS (_doc));
590 defs->appendChild(gradient);
591 gchar *id = g_strdup(gradient->attribute("id"));
592 Inkscape::GC::release(gradient);
594 return id;
595 }
597 #define EPSILON 0.0001
598 bool SvgBuilder::_addSamplesToGradient(Inkscape::XML::Node *gradient,
599 SampledFunction *func, double offset0,
600 double offset1, double opacity) {
602 // Check whether this sampled function can be converted to color stops
603 int sample_size = func->getSampleSize(0);
604 if ( sample_size != 2 )
605 return false;
606 int num_comps = func->getOutputSize();
607 if ( num_comps != 3 )
608 return false;
610 double *samples = func->getSamples();
611 unsigned stop_count = gradient->childCount();
612 bool is_continuation = false;
613 // Check if this sampled function is the continuation of the previous one
614 if ( stop_count > 0 ) {
615 // Get previous stop
616 Inkscape::XML::Node *prev_stop = gradient->nthChild(stop_count-1);
617 // Read its properties
618 double prev_offset;
619 sp_repr_get_double(prev_stop, "offset", &prev_offset);
620 SPCSSAttr *css = sp_repr_css_attr(prev_stop, "style");
621 guint32 prev_stop_color = sp_svg_read_color(sp_repr_css_property(css, "stop-color", NULL), 0);
622 sp_repr_css_attr_unref(css);
623 // Convert colors
624 double r = SP_RGBA32_R_F (prev_stop_color);
625 double g = SP_RGBA32_G_F (prev_stop_color);
626 double b = SP_RGBA32_B_F (prev_stop_color);
627 if ( fabs(prev_offset - offset0) < EPSILON &&
628 fabs(samples[0] - r) < EPSILON &&
629 fabs(samples[1] - g) < EPSILON &&
630 fabs(samples[2] - b) < EPSILON ) {
632 is_continuation = true;
633 }
634 }
636 int i = is_continuation ? num_comps : 0;
637 while (i < sample_size*num_comps) {
638 Inkscape::XML::Node *stop = _xml_doc->createElement("svg:stop");
639 SPCSSAttr *css = sp_repr_css_attr_new();
640 Inkscape::CSSOStringStream os_opacity;
641 os_opacity << opacity;
642 sp_repr_css_set_property(css, "stop-opacity", os_opacity.str().c_str());
643 gchar c[64];
644 sp_svg_write_color (c, 64, SP_RGBA32_F_COMPOSE (samples[i], samples[i+1], samples[i+2], 1.0));
645 sp_repr_css_set_property(css, "stop-color", c);
646 sp_repr_css_change(stop, css, "style");
647 sp_repr_css_attr_unref(css);
648 sp_repr_set_css_double(stop, "offset", ( i < num_comps ) ? offset0 : offset1);
650 gradient->appendChild(stop);
651 Inkscape::GC::release(stop);
652 i += num_comps;
653 }
655 return true;
656 }
658 bool SvgBuilder::_addStopsToGradient(Inkscape::XML::Node *gradient, Function *func,
659 double opacity) {
661 int type = func->getType();
662 if ( type == 0 ) { // Sampled
663 SampledFunction *sampledFunc = (SampledFunction*)func;
664 _addSamplesToGradient(gradient, sampledFunc, 0.0, 1.0, opacity);
665 } else if ( type == 3 ) { // Stitching
666 StitchingFunction *stitchingFunc = (StitchingFunction*)func;
667 double *bounds = stitchingFunc->getBounds();
668 int num_funcs = stitchingFunc->getNumFuncs();
669 // Add samples from all the stitched functions
670 for ( int i = 0 ; i < num_funcs ; i++ ) {
671 Function *func = stitchingFunc->getFunc(i);
672 if ( func->getType() != 0 ) // Only sampled functions are supported
673 continue;
675 SampledFunction *sampledFunc = (SampledFunction*)func;
676 _addSamplesToGradient(gradient, sampledFunc, bounds[i],
677 bounds[i+1], opacity);
678 }
679 } else { // Unsupported function type
680 return false;
681 }
683 return true;
684 }
686 /**
687 * \brief Sets _invalidated_style to true to indicate that styles have to be updated
688 * Used for text output when glyphs are buffered till a font change
689 */
690 void SvgBuilder::updateStyle(GfxState *state) {
691 if (_in_text_object) {
692 _invalidated_style = true;
693 _current_state = state;
694 }
695 }
697 /**
698 * This array holds info about translating font weight names to more or less CSS equivalents
699 */
700 static char *font_weight_translator[][2] = {
701 {"bold", "bold"},
702 {"light", "300"},
703 {"black", "900"},
704 {"heavy", "900"},
705 {"ultrabold", "800"},
706 {"extrabold", "800"},
707 {"demibold", "600"},
708 {"semibold", "600"},
709 {"medium", "500"},
710 {"book", "normal"},
711 {"regular", "normal"},
712 {"roman", "normal"},
713 {"normal", "normal"},
714 {"ultralight", "200"},
715 {"extralight", "200"},
716 {"thin", "100"}
717 };
719 /**
720 * \brief Updates _font_style according to the font set in parameter state
721 */
722 void SvgBuilder::updateFont(GfxState *state) {
724 TRACE(("updateFont()\n"));
725 _need_font_update = false;
726 // Flush buffered text before resetting matrices and font style
727 _flushText();
729 if (_font_style) {
730 //sp_repr_css_attr_unref(_font_style);
731 }
732 _font_style = sp_repr_css_attr_new();
733 GfxFont *font = state->getFont();
734 // Store original name
735 if (font->getOrigName()) {
736 _font_specification = font->getOrigName()->getCString();
737 } else {
738 _font_specification = font->getName()->getCString();
739 }
741 // Prune the font name to get the correct font family name
742 // In a PDF font names can look like this: IONIPB+MetaPlusBold-Italic
743 char *font_family = NULL;
744 char *font_style = NULL;
745 char *font_style_lowercase = NULL;
746 char *plus_sign = strstr(_font_specification, "+");
747 if (plus_sign) {
748 font_family = g_strdup(plus_sign + 1);
749 _font_specification = plus_sign + 1;
750 } else {
751 font_family = g_strdup(_font_specification);
752 }
753 char *minus_sign = g_strrstr(font_family, "-");
754 if (minus_sign) {
755 font_style = minus_sign + 1;
756 font_style_lowercase = g_ascii_strdown(font_style, -1);
757 minus_sign[0] = 0;
758 }
760 // Font family
761 if (font->getFamily()) {
762 const gchar *family = font->getFamily()->getCString();
763 sp_repr_css_set_property(_font_style, "font-family", font->getFamily()->getCString());
764 } else {
765 sp_repr_css_set_property(_font_style, "font-family", font_family);
766 }
768 // Font style
769 if (font->isItalic()) {
770 sp_repr_css_set_property(_font_style, "font-style", "italic");
771 } else if (font_style) {
772 if ( strstr(font_style_lowercase, "italic") ||
773 strstr(font_style_lowercase, "slanted") ) {
774 sp_repr_css_set_property(_font_style, "font-style", "italic");
775 } else if (strstr(font_style_lowercase, "oblique")) {
776 sp_repr_css_set_property(_font_style, "font-style", "oblique");
777 }
778 }
780 // Font variant -- default 'normal' value
781 sp_repr_css_set_property(_font_style, "font-variant", "normal");
783 // Font weight
784 GfxFont::Weight font_weight = font->getWeight();
785 if ( font_weight != GfxFont::WeightNotDefined ) {
786 if ( font_weight == GfxFont::W400 ) {
787 sp_repr_css_set_property(_font_style, "font-weight", "normal");
788 } else if ( font_weight == GfxFont::W700 ) {
789 sp_repr_css_set_property(_font_style, "font-weight", "bold");
790 } else {
791 gchar weight_num[4] = "100";
792 weight_num[0] = (gchar)( '1' + (font_weight - GfxFont::W100) );
793 sp_repr_css_set_property(_font_style, "font-weight", (gchar *)&weight_num);
794 }
795 } else if (font_style) {
796 // Apply the font weight translations
797 int num_translations = sizeof(font_weight_translator) / ( 2 * sizeof(char *) );
798 for ( int i = 0 ; i < num_translations ; i++ ) {
799 if (strstr(font_style_lowercase, font_weight_translator[i][0])) {
800 sp_repr_css_set_property(_font_style, "font-weight",
801 font_weight_translator[i][1]);
802 }
803 }
804 }
805 g_free(font_family);
806 if (font_style_lowercase) {
807 g_free(font_style_lowercase);
808 }
810 // Font stretch
811 GfxFont::Stretch font_stretch = font->getStretch();
812 gchar *stretch_value = NULL;
813 switch (font_stretch) {
814 case GfxFont::UltraCondensed:
815 stretch_value = "ultra-condensed";
816 break;
817 case GfxFont::ExtraCondensed:
818 stretch_value = "extra-condensed";
819 break;
820 case GfxFont::Condensed:
821 stretch_value = "condensed";
822 break;
823 case GfxFont::SemiCondensed:
824 stretch_value = "semi-condensed";
825 break;
826 case GfxFont::Normal:
827 stretch_value = "normal";
828 break;
829 case GfxFont::SemiExpanded:
830 stretch_value = "semi-expanded";
831 break;
832 case GfxFont::Expanded:
833 stretch_value = "expanded";
834 break;
835 case GfxFont::ExtraExpanded:
836 stretch_value = "extra-expanded";
837 break;
838 case GfxFont::UltraExpanded:
839 stretch_value = "ultra-expanded";
840 break;
841 default:
842 break;
843 }
844 if ( stretch_value != NULL ) {
845 sp_repr_css_set_property(_font_style, "font-stretch", stretch_value);
846 }
848 // Font size
849 Inkscape::CSSOStringStream os_font_size;
850 double *text_matrix = state->getTextMat();
851 double font_size = sqrt( text_matrix[0] * text_matrix[3] - text_matrix[1] * text_matrix[2] );
852 font_size *= state->getFontSize() * state->getHorizScaling();
853 os_font_size << font_size;
854 sp_repr_css_set_property(_font_style, "font-size", os_font_size.str().c_str());
856 // Writing mode
857 if ( font->getWMode() == 0 ) {
858 sp_repr_css_set_property(_font_style, "writing-mode", "lr");
859 } else {
860 sp_repr_css_set_property(_font_style, "writing-mode", "tb");
861 }
863 // Calculate new text matrix
864 double *font_matrix = font->getFontMatrix();
865 NR::Matrix nr_font_matrix(font_matrix[0], font_matrix[1], font_matrix[2],
866 font_matrix[3], font_matrix[4], font_matrix[5]);
867 NR::Matrix new_text_matrix(text_matrix[0], text_matrix[1],
868 -text_matrix[2], -text_matrix[3],
869 0.0, 0.0);
870 new_text_matrix *= NR::scale( 1.0 / font_size, 1.0 / font_size );
871 _text_matrix = nr_font_matrix * new_text_matrix;
873 _current_font = font;
874 }
876 /**
877 * \brief Writes the buffered characters to the SVG document
878 */
879 void SvgBuilder::_flushText() {
880 // Ignore empty strings
881 if ( _glyphs.size() < 1 ) {
882 _glyphs.clear();
883 return;
884 }
885 const SvgGlyph& first_glyph = _glyphs[0];
886 int render_mode = first_glyph.render_mode;
887 // Ignore invisible characters
888 if ( render_mode == 3 ) {
889 _glyphs.clear();
890 return;
891 }
893 Inkscape::XML::Node *text_node = _xml_doc->createElement("svg:text");
894 text_node->setAttribute("xml:space", "preserve");
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 :