Debian Codegraph @

Nasal/canvas/svg.nas

raw
1 # Parse an xml file into a canvas group element
2 #
3 # @param group The canvas.Group instance to append the parsed elements to
4 # @param path The path of the svg file (absolute or relative to FG_ROOT)
5 # @param options Optional hash of options
6 # font-mapper func
7 # parse_images bool
8 var parsesvg = func(group, path, options = nil)
9 {
10 if( !isa(group, Group) )
11 die("Invalid argument group (type != Group)");
12
13 if( options == nil )
14 options = {};
15
16 if (!ishash(options)) {
17 die("Options need to be of type hash!");
18 }
19
20 # resolve paths using standard SimGear logic
21 var file_path = resolvepath(path);
22 if (file_path == "")
23 die("File not found: "~path);
24 path = file_path;
25
26
27 var logpr = func(level, msg)
28 {
29 logprint(level, "parsesvg: "~msg~" [path='"~ path~"']");
30 };
31
32 # Helper to get number without unit (eg. px)
33 var evalCSSNum = func(css_num)
34 {
35 if (css_num == nil)
36 return;
37
38 if( css_num.ends_with("px") )
39 return substr(css_num, 0, size(css_num) - 2);
40 else if( css_num.ends_with("%") )
41 return substr(css_num, 0, size(css_num) - 1) / 100;
42
43 return css_num;
44 }
45
46 var level = 0;
47 var skip = 0;
48 var stack = [group];
49 var close_stack = []; # helper for check tag closing
50
51 var defs_stack = [];
52
53 var text = nil;
54 var tspans = nil;
55
56 # lookup table for element ids (for <use> element)
57 var id_dict = {};
58
59 # lookup table for mask and clipPath element ids
60 var clip_dict = {};
61 var cur_clip = nil;
62
63 # ----------------------------------------------------------------------------
64 # Create a new child an push it onto the stack
65 var pushElement = func(type, id = nil)
66 {
67 append(stack, stack[-1].createChild(type, id));
68 append(close_stack, level);
69
70 if (isscalar(id) and size(id)) {
71 id_dict[ id ] = stack[-1];
72 }
73
74 if( cur_clip != nil )
75 {
76 if(cur_clip['x'] != nil and cur_clip['y'] != nil
77 and cur_clip['width'] != nil and cur_clip['height'] != nil ) {
78 stack[-1].setClipByBoundingBox(cur_clip['x'], cur_clip['y'],
79 cur_clip['x'] + cur_clip['width'], cur_clip['y'] + cur_clip['height']);
80 }
81 else {
82 logpr(LOG_WARN, "Invalid or unsupported clip for element '" ~ id ~ "'");
83 }
84 cur_clip = nil;
85 }
86 }
87
88 # ----------------------------------------------------------------------------
89 # Remove the topmost element from the stack
90 var popElement = func
91 {
92 stack[-1].updateCenter();
93 # Create rotation matrix after all SVG defined transformations
94 stack[-1].set("tf-rot-index", stack[-1].createTransform()._node.getIndex());
95
96 pop(stack);
97 pop(close_stack);
98 }
99
100 # ----------------------------------------------------------------------------
101 # Parse a transformation (matrix)
102 # http://www.w3.org/TR/SVG/coords.html#TransformAttribute
103 var parseTransform = func(tf)
104 {
105 if( tf == nil )
106 return;
107
108 var end = 0;
109 while(1)
110 {
111 var start_type = tf.find_first_not_of("\t\n ", end);
112 if( start_type < 0 )
113 break;
114
115 var end_type = tf.find_first_of("(\t\n ", start_type + 1);
116 if( end_type < 0 )
117 break;
118
119 var start_args = tf.find('(', end_type);
120 if( start_args < 0 )
121 break;
122
123 var values = [];
124 end = start_args + 1;
125 while(1)
126 {
127 var start_num = tf.find_first_not_of(",\t\n ", end);
128 if( start_num < 0 )
129 break;
130 if( tf[start_num] == `)` )
131 break;
132
133 end = tf.find_first_of("),\t\n ", start_num + 1);
134 if( end < 0 )
135 break;
136 append(values, substr(tf, start_num, end - start_num));
137 }
138
139 if( end > 0 )
140 end += 1;
141
142 var type = substr(tf, start_type, end_type - start_type);
143
144 # TODO should we warn if to much/wrong number of arguments given?
145 if( type == "translate" )
146 {
147 # translate(<tx> [<ty>]), which specifies a translation by tx and ty. If
148 # <ty> is not provided, it is assumed to be zero.
149 stack[-1].createTransform().setTranslation
150 (
151 values[0],
152 size(values) > 1 ? values[1] : 0,
153 );
154 }
155 else if( type == "scale" )
156 {
157 # scale(<sx> [<sy>]), which specifies a scale operation by sx and sy. If
158 # <sy> is not provided, it is assumed to be equal to <sx>.
159 stack[-1].createTransform().setScale(values);
160 }
161 else if( type == "rotate" )
162 {
163 # rotate(<rotate-angle> [<cx> <cy>]), which specifies a rotation by
164 # <rotate-angle> degrees about a given point.
165 stack[-1].createTransform().setRotation
166 (
167 values[0] * D2R, # internal functions use rad
168 size(values) > 1 ? values[1:] : nil
169 );
170 }
171 else if( type == "matrix" )
172 {
173 if( size(values) == 6 )
174 stack[-1].createTransform(values);
175 else
176 logpr(LOG_WARN,
177 "Invalid arguments to matrix transform: " ~ debug.string(values, 0)
178 );
179 }
180 else
181 logpr(LOG_WARN, "Unknown transform type: '" ~ type ~ "'");
182 }
183 };
184
185 # ----------------------------------------------------------------------------
186 # Parse a path
187 # http://www.w3.org/TR/SVG/paths.html#PathData
188
189 # map svg commands OpenVG commands
190 var cmd_map = {
191 z: Path.VG_CLOSE_PATH,
192 m: Path.VG_MOVE_TO,
193 l: Path.VG_LINE_TO,
194 h: Path.VG_HLINE_TO,
195 v: Path.VG_VLINE_TO,
196 q: Path.VG_QUAD_TO,
197 c: Path.VG_CUBIC_TO,
198 t: Path.VG_SQUAD_TO,
199 s: Path.VG_SCUBIC_TO
200 };
201
202 var parsePath = func(path_data)
203 {
204 if( path_data == nil )
205 return;
206
207 var pos = 0;
208 var cmds = [];
209 var coords = [];
210
211 while(1)
212 {
213 # skip leading spaces
214 pos = path_data.find_first_not_of("\t\n ", pos);
215 if( pos < 0 )
216 break;
217
218 # get command (single character);
219 var cmd = substr(path_data, pos, 1);
220 pos += 1;
221
222 # and get all following arguments
223 # the '-' is kind of hard, it belongs to a number, might appear twice in
224 # one arg (e.g. -2e-3) and some SVG do not separate args starting with '-'
225 # so the '-' is the separator as well in this case.
226 # SVG samples (cut)
227 # 1: m 547.56916,962.17731 c 10e-6,25.66886 -20.80872,46.47759 -46.47758,46.47759 -25.66886,0 ...
228 # 2: M831,144.861c-0.236,0.087-0.423,0.255-0.629,0.39c-1.169,0.765-2.333,1.536-3.499,2.305 c-0.019,0.013-0.041, ...
229 var args = [];
230 #skip non-argument spaces and separator
231 pos = path_data.find_first_not_of(",\t\n ", pos);
232 var start_num = pos;
233 while(1)
234 {
235 pos = path_data.find_first_not_of(",\t\n ", pos);
236 if (pos < 0) break;
237 start_num = pos;
238 while (1) {
239 var chr1 = substr(path_data, pos, 1);
240 if (chr1 == "-")
241 pos = path_data.find_first_not_of("e.0123456789", pos + 1);
242 else
243 pos = path_data.find_first_not_of("e.0123456789", pos);
244 #check for e- (e.g. 42e-6)
245 if (pos > 0 and substr(path_data, pos - 1, 1) == "e"
246 and substr(path_data, pos, 1) == "-")
247 continue;
248 else
249 break;
250 }
251 if (start_num == pos) break;
252
253 append(args, substr( path_data,
254 start_num,
255 pos > 0 ? pos - start_num : nil ));
256 }
257
258 # now execute the command
259 var rel = string.islower(cmd[0]);
260 var cmd = string.lc(cmd);
261 if( cmd == 'a' )
262 {
263 for(var i = 0; i + 7 <= size(args); i += 7)
264 {
265 # SVG: (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+
266 # OpenVG: rh,rv,rot,x0,y0
267 if( args[i + 3] )
268 var cmd_vg = args[i + 4] ? Path.VG_LCWARC_TO : Path.VG_LCCWARC_TO;
269 else
270 var cmd_vg = args[i + 4] ? Path.VG_SCWARC_TO : Path.VG_SCCWARC_TO;
271 append(cmds, rel ? cmd_vg + 1: cmd_vg);
272 append(coords, args[i],
273 args[i + 1],
274 args[i + 2],
275 args[i + 5],
276 args[i + 6] );
277 }
278
279 if( math.mod(size(args), 7) > 0 ) {
280 logpr(LOG_WARN, "Invalid number of coords for cmd 'a' ("~
281 size(args)~" mod 7 != 0)");
282 }
283 }
284 else
285 {
286 var cmd_vg = cmd_map[cmd];
287 if( cmd_vg == nil )
288 {
289 logpr(LOG_WARN, "command not found: '" ~ cmd ~ "'");
290 continue;
291 }
292
293 var num_coords = Path.num_coords[int(cmd_vg)];
294 if( num_coords == 0 )
295 append(cmds, cmd_vg);
296 else
297 {
298 for(var i = 0; i + num_coords <= size(args); i += num_coords)
299 {
300 append(cmds, rel ? cmd_vg + 1: cmd_vg);
301 for(var j = i; j < i + num_coords; j += 1)
302 append(coords, args[j]);
303
304 # If a moveto is followed by multiple pairs of coordinates, the
305 # subsequent pairs are treated as implicit lineto commands.
306 if( cmd == 'm' )
307 cmd_vg = cmd_map['l'];
308 }
309
310 if( math.mod(size(args), num_coords) > 0 )
311 logpr(LOG_WARN,"Invalid number of coords for cmd '" ~ cmd ~ "' ("
312 ~size(args)~" mod "~num_coords~" != 0)"
313 );
314 }
315 }
316 }
317
318 stack[-1].setData(cmds, coords);
319 };
320
321 # ----------------------------------------------------------------------------
322 # Parse text styles (and apply them to the topmost element)
323 var parseTextStyles = func(style)
324 {
325 # http://www.w3.org/TR/SVG/text.html#TextAnchorProperty
326 var h_align = style["text-anchor"];
327 if( h_align != nil )
328 {
329 if( h_align == "end" )
330 h_align = "right";
331 else if( h_align == "middle" )
332 h_align = "center";
333 else # "start"
334 h_align = "left";
335 stack[-1].set("alignment", h_align ~ "-baseline");
336 }
337 # TODO vertical align
338
339 var fill = style['fill'];
340 if( fill != nil )
341 stack[-1].set("fill", fill);
342
343 var font_family = style["font-family"];
344 var font_weight = style["font-weight"];
345 var font_style = style["font-style"];
346 if( font_family != nil or font_weight != nil or font_style != nil )
347 stack[-1].set("font", font_mapper(font_family, font_weight, font_style, options));
348
349 var font_size = style["font-size"];
350 if( font_size != nil )
351 stack[-1].setDouble("character-size", evalCSSNum(font_size));
352
353 var line_height = style["line-height"];
354 if( line_height != nil )
355 stack[-1].setDouble("line-height", evalCSSNum(line_height));
356 }
357
358 # ----------------------------------------------------------------------------
359 # Parse a css style attribute
360 var parseStyle = func(style)
361 {
362 if( style == nil )
363 return {};
364
365 var styles = {};
366 foreach(var part; split(';', style))
367 {
368 if( !size(part = string.trim(part)) )
369 continue;
370 if( size(part = split(':',part)) != 2 )
371 continue;
372
373 var key = string.trim(part[0]);
374 if( !size(key) )
375 continue;
376
377 var value = string.trim(part[1]);
378 if( !size(value) )
379 continue;
380
381 styles[key] = value;
382 }
383
384 return styles;
385 }
386
387 # ----------------------------------------------------------------------------
388 # Parse a css color
389 var parseColor = func(s)
390 {
391 var color = [0, 0, 0];
392 if( s == nil )
393 return color;
394
395 if( size(s) == 7 and substr(s, 0, 1) == '#' )
396 {
397 return [ std.stoul(substr(s, 1, 2), 16) / 255,
398 std.stoul(substr(s, 3, 2), 16) / 255,
399 std.stoul(substr(s, 5, 2), 16) / 255 ];
400 }
401
402 return color;
403 };
404
405 # ----------------------------------------------------------------------------
406 # XML parsers element open callback
407 var start = func(name, attr)
408 {
409 level += 1;
410
411 if( skip )
412 return;
413
414 if( level == 1 )
415 {
416 if( name != 'svg' )
417 die("Not an svg file (root=" ~ name ~ ")");
418 else
419 return;
420 }
421
422 if( size(defs_stack) > 0 )
423 {
424 if( name == "mask" or name == "clipPath" )
425 {
426 append(defs_stack, {'type': name, 'id': attr['id']});
427 }
428 else if( ishash(defs_stack[-1]) and name == "rect" )
429 {
430 foreach(var p; ["x", "y", "width", "height"])
431 defs_stack[-1][p] = evalCSSNum(attr[p]);
432 skip = level;
433 }
434 else
435 {
436 logpr(LOG_INFO, "Skipping unknown element in <defs>: <" ~ name ~ ">");
437 skip = level;
438 }
439 return;
440 }
441
442 var style = parseStyle(attr['style']);
443
444 var clip_id = attr['clip-path'] or attr['mask'];
445 if( clip_id != nil and clip_id != "none" )
446 {
447 if( clip_id.starts_with("url(#")
448 and clip_id[-1] == `)` )
449 clip_id = substr(clip_id, 5, size(clip_id) - 5 - 1);
450
451 cur_clip = clip_dict[clip_id];
452 if( cur_clip == nil )
453 logpr(LOG_WARN, "Clip not found: '" ~ clip_id ~ "'");
454 }
455
456 if( style['display'] == 'none' )
457 {
458 skip = level;
459 return;
460 }
461 else if( name == "g" )
462 {
463 pushElement('group', attr['id']);
464 }
465 else if( name == "text" )
466 {
467 text = {
468 "attr": attr,
469 "style": style,
470 "text": ""
471 };
472 tspans = [];
473 return;
474 }
475 else if( name == "tspan" )
476 {
477 append(tspans, {
478 "attr": attr,
479 "style": style,
480 "text": ""
481 });
482 return;
483 }
484 else if( name == "path" or name == "rect" or name == "circle" or name == "ellipse")
485 {
486 pushElement('path', attr['id']);
487
488 if( name == "rect" )
489 {
490 var width = evalCSSNum(attr['width']);
491 var height = evalCSSNum(attr['height']);
492 if (!contains(attr, 'x'))
493 attr['x'] = 0;
494 if (!contains(attr, 'y'))
495 attr['y'] = 0;
496 var x = evalCSSNum(attr['x']);
497 var y = evalCSSNum(attr['y']);
498 var rx = attr['rx'];
499 var ry = attr['ry'];
500
501 if( ry == nil )
502 ry = rx;
503 else if( rx == nil )
504 rx = ry;
505
506 var cfg = {};
507 if( rx != nil )
508 cfg["border-radius"] = [evalCSSNum(rx), evalCSSNum(ry)];
509
510 stack[-1].rect(x, y, width, height, cfg);
511 }
512 if (name == "circle") {
513 var cx = evalCSSNum(attr['cx']);
514 var cy = evalCSSNum(attr['cy']);
515 var r = evalCSSNum(attr['r']);
516 stack[-1].circle(r, cx, cy);
517 }
518 if (name == "ellipse") {
519 var cx = evalCSSNum(attr['cx']);
520 var cy = evalCSSNum(attr['cy']);
521 var rx = evalCSSNum(attr['rx']);
522 var ry = evalCSSNum(attr['ry']);
523 stack[-1].ellipse(rx, ry, cx, cy);
524 }
525 if (name == "path") {
526 parsePath(attr['d']);
527 }
528
529 var fill = style['fill'];
530 if( fill != nil )
531 stack[-1].set('fill', fill);
532
533 var fill_opacity = style['fill-opacity'];
534 if( fill_opacity != nil)
535 stack[-1].setDouble('fill-opacity', fill_opacity);
536
537 var stroke = style['stroke'];
538 if( stroke != nil )
539 stack[-1].set('stroke', stroke);
540
541 var stroke_opacity = style['stroke-opacity'];
542 if( stroke_opacity != nil)
543 stack[-1].setDouble('stroke-opacity', stroke_opacity);
544
545 var w = style['stroke-width'];
546 stack[-1].setStrokeLineWidth( w != nil ? evalCSSNum(w) : 1 );
547
548 var linecap = style['stroke-linecap'];
549 if( linecap != nil )
550 stack[-1].setStrokeLineCap(style['stroke-linecap']);
551
552 var linejoin = style['stroke-linejoin'];
553 if( linejoin != nil )
554 stack[-1].setStrokeLineJoin(style['stroke-linejoin']);
555
556 # http://www.w3.org/TR/SVG/painting.html#StrokeDasharrayProperty
557 var dash = style['stroke-dasharray'];
558 if( dash and size(dash) > 3 )
559 # at least 2 comma separated values...
560 stack[-1].setStrokeDashArray(split(',', dash));
561 } #end path/rect/ellipse/circle
562 else if( name == "use" )
563 {
564 var ref = attr["xlink:href"];
565 if( ref == nil or size(ref) < 2 or ref[0] != `#` )
566 return logpr(LOG_WARN, "Invalid or missing href: '" ~ ref ~ "'");
567
568 var el_src = id_dict[ substr(ref, 1) ];
569 if( el_src == nil )
570 return logpr(LOG_WARN, "Reference to unknown element '" ~ ref ~ "'");
571
572 # Create new element and copy sub branch from source node
573 pushElement(el_src._node.getName(), attr['id']);
574 props.copy(el_src._node, stack[-1]._node);
575
576 # copying also overrides the id so we need to set it again
577 stack[-1]._node.getNode("id").setValue(attr['id']);
578 }
579 else if( name == "defs" )
580 {
581 append(defs_stack, "defs");
582 return;
583 }
584 else if (name == "image" and options["parse_images"])
585 {
586 var ref = attr["xlink:href"];
587 # ref must not be missing and shall not contain Windows path separator
588 # find("\\") is correct, backslash is control character and must be escaped
589 # by adding another backslash - otherwise parse error anywhere below
590 if (ref == nil or find("\\", ref) > -1)
591 {
592 return logpr(LOG_WARN, "Invalid or missing href in image tag: '" ~ ref ~ "'");
593 }
594 if (substr(ref, 0, 5) == "data:") {
595 return logpr(LOG_WARN, "Unsupported embedded image");
596 }
597 elsif (substr(ref, 0, 5) != "file:") {
598 # absolute paths seem to start with "file:"
599 # prepend relative paths with the path of SVG file and hope the image is there
600 # file access limitations apply
601 ref = io.dirname(path) ~ ref;
602 }
603 pushElement("image", attr["id"]);
604
605 if (attr["x"] != nil and attr["y"] != nil) {
606 stack[-1].createTransform().setTranslation(attr["x"], attr["y"]);
607 }
608 if (attr["width"] != nil and attr["height"] != nil) {
609 stack[-1].setSize(attr["width"], attr["height"]);
610 }
611 stack[-1].setFile(ref);
612 }
613 elsif (name == "sodipodi:namedview" or name == "metadata")
614 {
615 # silently skip these
616 skip = level;
617 return;
618 }
619 else
620 {
621 logpr(LOG_INFO, "Skipping unknown element '" ~ name ~ "'");
622 skip = level;
623 return;
624 }
625
626 parseTransform(attr['transform']);
627
628 var cx = attr['inkscape:transform-center-x'];
629 if( cx != nil and cx != 0 )
630 stack[-1].setDouble("center-offset-x", evalCSSNum(cx));
631
632 var cy = attr['inkscape:transform-center-y'];
633 if( cy != nil and cy != 0 )
634 stack[-1].setDouble("center-offset-y", -evalCSSNum(cy));
635 };
636
637 # XML parsers element close callback
638 var end = func(name)
639 {
640 level -= 1;
641
642 if( skip )
643 {
644 if( level < skip )
645 skip = 0;
646 return;
647 }
648
649 if( size(defs_stack) > 0 )
650 {
651 if( name != "defs" )
652 {
653 var type = defs_stack[-1]['type'];
654 if( type == "mask" or type == "clipPath" )
655 clip_dict[defs_stack[-1]['id']] = defs_stack[-1];
656 }
657
658 pop(defs_stack);
659 return;
660 }
661
662 if( size(close_stack) and (level + 1) == close_stack[-1] )
663 popElement();
664
665 if( name == "text" )
666 {
667 # Inkscape/SVG text is a bit complicated. If we only got a single tspan
668 # or text without tspan we create just a single canvas.Text, otherwise
669 # we create a canvas.Group with a canvas.Text as child for each tspan.
670 # We need to take care to apply the transform attribute of the text
671 # element to the correct canvas element, and also correctly inherit
672 # the style properties.
673 var character_size = 24;
674 if( size(tspans) > 1 )
675 {
676 pushElement('group', text.attr['id']);
677 parseTextStyles(text.style);
678 parseTransform(text.attr['transform']);
679
680 character_size = stack[-1].get("character-size", character_size);
681 }
682
683 # Helper for getting first number in space separated list of numbers.
684 var first_num = func(str)
685 {
686 if( str == nil )
687 return 0;
688 var end = str.find_first_of(" \n\t");
689 if( end < 0 )
690 return str;
691 else
692 return substr(str, 0, end);
693 }
694
695 var line = 0;
696 foreach(var tspan; tspans)
697 {
698 # Always take first number and ignore individual character placment
699 var x = first_num(tspan.attr['x'] or text.attr['x']);
700 var y = first_num(tspan.attr['y'] or text.attr['y']);
701
702 # Sometimes Inkscape forgets writing x and y coordinates and instead
703 # just indicates a multiline text with sodipodi:role="line".
704 if( tspan.attr['y'] == nil and tspan.attr['sodipodi:role'] == "line" )
705 # TODO should we combine multiple lines into a single text separated
706 # with newline characters?
707 y += line
708 * stack[-1].get("line-height", 1.25)
709 * stack[-1].get("character-size", character_size);
710
711 # Use id of text element with single tspan child, fall back to id of
712 # tspan if text has no id.
713 var id = text.attr['id'];
714 if( id == nil or size(tspans) > 1 )
715 id = tspan.attr['id'];
716
717 pushElement('text', id);
718 stack[-1].setText(tspan.text);
719
720 if( x != 0 or y != 0 )
721 stack[-1].createTransform().setTranslation(x, y);
722
723 if( size(tspans) == 1 )
724 {
725 parseTextStyles(text.style);
726 parseTransform(text.attr['transform']);
727 }
728
729 parseTextStyles(tspan.style);
730 popElement();
731
732 line += 1;
733 }
734
735 if( size(tspans) > 1 )
736 popElement();
737
738 text = nil;
739 tspans = nil;
740 }
741 }; #end()
742
743 # XML parsers element data callback
744 var data = func(data)
745 {
746 if( skip )
747 return;
748
749 if( size(data) and tspans != nil )
750 {
751 if( size(tspans) == 0 )
752 # If no tspan is found use text element itself
753 append(tspans, text);
754
755 # If text contains xml entities it gets split at each entity. So let's
756 # glue it back into a single text...
757 tspans[-1]["text"] ~= data;
758 }
759 };
760
761 call(func parsexml(path, start, end, data), nil, var err = []);
762 if( size(err) )
763 {
764 logpr(LOG_ALERT, "parse XML failed");
765 debug.printerror(err);
766 return 0;
767 }
768
769 return 1;
770 }