lib/Graphics/Penplotter/GcodeXY/SVG.pm untested

filter: Statementstmt 0.0% 0 / 546 Branchbran 0.0% 0 / 256 Conditioncond 0.0% 0 / 187 MC/DCmcdc 0.0% 0 / 102 Subroutinesub 0.0% 0 / 46 Podpod 0.0% 0 / 32 totaltotal 0.0% 0 / 1169 CC 129 SCAR 46.6
CC
129
Cov
0%
_handle_element
420.0
exportsvg
210.0
_dopath
182.0
CRAP 105.4
1 package Graphics::Penplotter::GcodeXY::SVG v0.9.4;
2  
3 use v5.38.2;
4 use feature qw( signatures );
5 no warnings qw( experimental::signatures );
6 use strict;
7 use warnings;
8 use Role::Tiny;
9 use Carp qw( croak );
10 use Readonly qw( Readonly );
11 use Math::Trig qw( acos tan );
12 use List::Util qw( max );
13 use POSIX qw( ceil );
14 use Image::SVG::Transform ();
15 use Image::SVG::Path qw( extract_path_info );
16  
17 # ---------------------------------------------------------------------------
18 # Graphics::Penplotter::GcodeXY::SVG
19 # Role providing SVG import for GcodeXY.
20 # ---------------------------------------------------------------------------
21  
22 requires qw(gsave grestore translate scale rotate skewX skewY _premulmat line
23 box boxround circle ellipse polygon curve moveto stroke penup pendown
24 _genfastmove _genslowmove stroketext setfont currentpoint _croak
25 _flushPsegments _parse);
26  
27 # ---------------------------------------------------------------------------
28 # Constants -- private copies of values from GcodeXY.pm.
29 # ---------------------------------------------------------------------------
30  
31 Readonly my $TWOPI => 6.28318530718;
32 Readonly my $EOL => qq{\n};
33 Readonly my $SPACE => q{ };
34 Readonly my $EMPTY_STR => q{};
35 Readonly my $I2P => 72.0; # inches to points scale factor
36 Readonly my $BBMAX => 1_000_000.0; # sentinel for bounding box initialisation
37 Readonly my $G00 => 3; # G00 line opcode (fast move)
38 Readonly my $G01 => 4; # G01 line opcode (slow move / draw)
39  
40 # ---------------------------------------------------------------------------
41 # Unit conversion tables -- copied from GcodeXY.pm.
42 # ---------------------------------------------------------------------------
43  
44 my %unit_to_inches = (
45 px => 1.0/96.0,
46 pt => 1.0/72.0,
47 pc => 1.0/6.0,
48 in => 1.0,
49 cm => 1.0/2.54,
50 mm => 1.0/25.4,
51 );
52  
53 my %inches_to_unit = (
54 pt => 72.0,
55 in => 1.0,
56 mm => 25.4,
57 cm => 2.54,
58 px => 96.0,
59 pc => 6.0,
60 );
61  
62 # ---------------------------------------------------------------------------
63 # Module-level state for SVG import.
64 # These are reset at the start of each importsvg() call.
65 # ---------------------------------------------------------------------------
66  
67 my %_svg_defs = (); # id => XML::LibXML::Node
68 my @_svg_style_stack = (); # reserved for future CSS inheritance
69 my %_svg_css_rules = (); # selector => { property => value }
70  
71  
72 # ===========================================================================
73 # PUBLIC ENTRY POINT: exportsvg
74 # ===========================================================================
75  
76 sub exportsvg ($self, $gcout = undef) {
77 if (!$gcout) { die 'exportsvg: output filename not provided' }
78 my $op = $EMPTY_STR;
79 my $xn = $EMPTY_STR;
80 my $yn = $EMPTY_STR;
81 my $maxx = 0.0;
82 my $maxy = 0.0;
83 my $minx = $BBMAX;
84 my $miny = $BBMAX;
85 my $linecount = 0;
86 my ( $x, $y, $line, $st );
87 $self->_flushPsegments();
88 my $limit = scalar @{ $self->{currentpage} };
89 if ( !$limit ) {
90 croak "exportsvg: $gcout: empty queue. Aborting.";
91 return 0;
92 }
93 open( my $out, '>', $gcout ) or croak "exportsvg: cannot open output file $gcout";
94 # Skip the gcode header, stopping at the first pen-up command
95 HEADER:
96 while (1) {
97 $linecount++;
98 $line = $self->{currentpage}[ $linecount - 1 ];
99 last HEADER if $line eq $self->{penupcmd};
100 }
101 # Collect SVG path data and compute bounding box in one pass
102 $st = $EMPTY_STR;
103 while ( $linecount < $limit ) {
104 $linecount++;
105 $line = $self->{currentpage}[ $linecount - 1 ];
106 ( $op, $xn, $yn ) = $self->_parse($line); # coords in inches
107 if ( $op eq $G00 || $op eq $G01 ) {
108 $x = 0.0 + $xn;
109 $y = 0.0 + $yn;
110 if ( $x > $maxx ) { $maxx = $x }
111 if ( $y > $maxy ) { $maxy = $y }
112 if ( $x < $minx ) { $minx = $x }
113 if ( $y < $miny ) { $miny = $y }
114 }
115 if ( $op eq $G01 ) {
116 $st .= 'L' . ($xn * $I2P) . $SPACE . ($yn * $I2P) . $SPACE;
117 }
118 elsif ( $op eq $G00 ) {
119 $st .= 'M' . ($xn * $I2P) . $SPACE . ($yn * $I2P) . $SPACE;
120 }
121 # PU and PD are ignored
122 }
123 # Write SVG header
124 my $hdr = "<svg" . $EOL;
125 $hdr .= "xmlns='http://www.w3.org/2000/svg'>" . $EOL;
126 $hdr .= "<path style='fill:white; fill-opacity:0; stroke:black; " . $EOL;
127 $hdr .= "stroke-opacity:1; stroke-width: 0.5'" . $EOL;
128 $hdr .= "d=\"";
129 print {$out} $hdr;
130 # Write path data, wrapping long lines at word boundaries
131 my $max_length = 120;
132 while ( length($st) > $max_length ) {
133 my $chunk = substr( $st, 0, $max_length );
134 my $break_point = rindex( $chunk, ' ' );
135 $break_point = $max_length if $break_point == -1;
136 my $line = substr( $st, 0, $break_point, '' );
137 print {$out} $line, $EOL;
138 $st =~ s/^\s+//;
139 }
140 print {$out} $st, $EOL if $st;
141 # Write SVG trailer
142 print {$out} "\"/></svg> " . $EOL;
143 close $out;
144 # Convert bounding box to points and optionally report it
145 $minx *= $I2P;
146 $miny *= $I2P;
147 $maxx *= $I2P;
148 $maxy *= $I2P;
149 if ( $self->{check} ) {
150 print STDOUT "exportsvg: $gcout: bounding box = ($minx,$miny)pt ($maxx,$maxy)pt" . $EOL;
151 }
152 return ( $minx, $miny, $maxx, $maxy );
153 }
154  
155 # ===========================================================================
156 # PUBLIC ENTRY POINT: importsvg
157 # ===========================================================================
158  
159 sub importsvg ($self, $file) {
160 eval { require XML::LibXML; XML::LibXML->import(); 1 } or do {
161 $self->_croak("XML::LibXML is required to import SVG files: $@");
162 };
163  
164 my $parser = XML::LibXML->new();
165 my $doc;
166 eval { $doc = $parser->load_xml( location => $file ); 1 } or do {
167 $self->_croak("XML parse error in $file: $@");
168 };
169  
170 # Reset module-level state for this import
171 %_svg_defs = ();
172 @_svg_style_stack = ();
173 %_svg_css_rules = ();
174  
175 if ($self->{check}) {
176 print STDOUT "$file:$EOL";
177 }
178  
179 $self->gsave();
180  
181 my $root = $doc->documentElement();
182  
183 # Pass 1: collect <defs> and <style> before rendering, so that
184 # forward references from <use> resolve correctly.
185 _svg_collect_defs($self, $root);
186  
187 # Pass 2: render.
188 # Route the root <svg> through _handle_svg so its viewBox/width/height
189 # attributes are applied. (_traverse only processes children, so the
190 # root element's own attributes would otherwise be silently ignored.)
191 my %root_attr = _collect_attrs($root);
192 my %root_eff = _svg_effective_style($self, \%root_attr);
193 _handle_svg($self, $root, \%root_attr, \%root_eff);
194  
195 $self->grestore();
196 return 1;
197 }
198  
199  
200 # ===========================================================================
201 # PASS 1: collect defs and CSS
202 # ===========================================================================
203  
204 sub _svg_collect_defs ($self, $node) {
205 for my $child ($node->childNodes) {
206 next unless $child->nodeType == 1;
207 my $tag = lc $child->localname;
208  
209 if ($tag eq 'defs' || $tag eq 'symbol') {
210 _svg_index_ids($child);
211 _svg_collect_defs($self, $child);
212 }
213 elsif ($tag eq 'style') {
214 _css_parse_block( $child->textContent // '' );
215 }
216 else {
217 _svg_index_ids($child);
218 _svg_collect_defs($self, $child);
219 }
220 }
221 }
222  
223 sub _svg_index_ids ($node) {
224 my $id = $node->getAttribute('id') // $node->getAttribute('xml:id');
225 if (defined $id && $id ne '') {
226 $_svg_defs{$id} = $node;
227 }
228 for my $child ($node->childNodes) {
229 next unless $child->nodeType == 1;
230 _svg_index_ids($child);
231 }
232 }
233  
234  
235 # ===========================================================================
236 # PASS 2: recursive traversal
237 # ===========================================================================
238  
239 sub _traverse ($self, $node) {
240 return unless $node;
241 for my $child ($node->childNodes) {
242 next unless $child->nodeType == 1;
243 my %attr = _collect_attrs($child);
244 my $tag = lc $child->localname;
245  
246 my %eff = _svg_effective_style($self, \%attr);
247  
248 next if ($eff{display} // '') eq 'none';
249 next if ($eff{visibility} // '') eq 'hidden';
250  
251 _handle_element($self, $child, $tag, \%attr, \%eff);
252 }
253 }
254  
255 sub _collect_attrs ($node) {
256 my %attr;
257 for my $a ($node->attributes) {
258 my $name = $a->nodeName;
259 $name =~ s/^xlink://; # xlink:href -> href
260 $attr{$name} = $a->value;
261 }
262 return %attr;
263 }
264  
265  
266 # ===========================================================================
267 # ELEMENT DISPATCHER
268 # ===========================================================================
269  
270 sub _handle_element ($self, $node, $tag, $attr, $eff) {
271  
272 # --- Container / structural elements --------------------------------
273  
274 if ($tag eq 'svg') {
275 _handle_svg($self, $node, $attr, $eff);
276 return;
277 }
278  
279 if ($tag eq 'g' || $tag eq 'a' || $tag eq 'switch') {
280 $self->gsave();
281 _apply_transform($self, $attr->{transform});
282 _traverse($self, $node);
283 $self->grestore();
284 return;
285 }
286  
287 if ($tag eq 'defs' || $tag eq 'symbol') {
288 return; # rendered only when instantiated by <use>
289 }
290  
291 if ($tag eq 'use') {
292 _handle_use($self, $node, $attr, $eff);
293 return;
294 }
295  
296 # --- Metadata / non-geometric elements ------------------------------
297  
298 if ($tag =~ /\A(?:title|desc|metadata|style|script|animate.*|set|mpath)\z/) {
299 return;
300 }
301  
302 if ($tag eq 'image') {
303 if ($self->{check}) {
304 print STDOUT "importsvg: <image> ignored (raster, not plottable)$EOL";
305 }
306 return;
307 }
308  
309 if ($tag eq 'foreignobject') {
310 return;
311 }
312  
313 # --- Gradient / pattern / clip / marker definitions -----------------
314  
315 if ($tag =~ /\A(?:lineargradient|radialgradient|pattern|clippath|mask|filter|marker)\z/) {
316 return;
317 }
318  
319 # --- Geometric elements ---------------------------------------------
320  
321 $self->gsave();
322 _apply_transform($self, $attr->{transform});
323  
324 if ($tag eq 'path') { _handle_path ($self, $attr) }
325 elsif ($tag eq 'line') { _handle_line ($self, $attr) }
326 elsif ($tag eq 'rect') { _handle_rect ($self, $attr) }
327 elsif ($tag eq 'circle') { _handle_circle ($self, $attr) }
328 elsif ($tag eq 'ellipse') { _handle_ellipse ($self, $attr) }
329 elsif ($tag eq 'polyline') { _handle_polyline($self, $attr, 0) }
330 elsif ($tag eq 'polygon') { _handle_polyline($self, $attr, 1) }
331 elsif ($tag eq 'text') { _handle_text ($self, $node, $attr, $eff) }
332 elsif ($tag eq 'tspan') { _handle_tspan ($self, $node, $attr, $eff) }
333 else {
334 if ($self->{check}) {
335 print STDOUT "importsvg: unhandled element <$tag>$EOL";
336 }
337 }
338  
339 $self->grestore();
340 }
341  
342  
343 # ===========================================================================
344 # <svg> root and nested viewport
345 # ===========================================================================
346  
347 sub _handle_svg ($self, $node, $attr, $eff) {
348 $self->gsave();
349 if ($self->{check} && defined $attr->{width} && defined $attr->{height}) {
350 print STDOUT "SVG size: $attr->{width} x $attr->{height}$EOL";
351 }
352 _svg_viewbox_transform($self, $attr) if defined $attr->{viewBox};
353 _apply_transform($self, $attr->{transform});
354 _traverse($self, $node);
355 $self->grestore();
356 }
357  
358  
359 # ===========================================================================
360 # viewBox mapping
361 # ===========================================================================
362  
363 sub _svg_viewbox_transform ($self, $attr) {
364 my $vb = $attr->{viewBox} // return;
365 $vb =~ s/,/ /g;
366 my ($vbx, $vby, $vbw, $vbh) = split /\s+/, $vb;
367 return unless defined $vbw && $vbw > 0 && defined $vbh && $vbh > 0;
368  
369 my $vpw = defined $attr->{width} ? $self->_svgconvert($attr->{width}) : $self->{xsize};
370 my $vph = defined $attr->{height} ? $self->_svgconvert($attr->{height}) : $self->{ysize};
371 return unless defined $vpw && $vpw > 0 && defined $vph && $vph > 0;
372  
373 my $par = $attr->{preserveAspectRatio} // 'xMidYMid meet';
374  
375 my ($sx, $sy);
376 if ($par =~ /none/i) {
377 $sx = $vpw / $vbw;
378 $sy = $vph / $vbh;
379 }
380 else {
381 my $s = ($vpw / $vbw < $vph / $vbh) ? $vpw / $vbw : $vph / $vbh;
382 $sx = $sy = $s;
383 }
384  
385 $self->translate(-$vbx * $sx, -$vby * $sy);
386 $self->scale($sx, $sy);
387  
388 if ($self->{check}) {
389 printf STDOUT "SVG viewBox: (%g %g %g %g) -> scale (%g, %g)$EOL",
390 $vbx, $vby, $vbw, $vbh, $sx, $sy;
391 }
392 }
393  
394  
395 # ===========================================================================
396 # <use> -- symbol instantiation
397 # ===========================================================================
398  
399 sub _handle_use ($self, $node, $attr, $eff) {
400 my $href = $attr->{href} // $attr->{'xlink:href'} // '';
401 $href =~ s/^#//;
402  
403 unless (defined $_svg_defs{$href}) {
404 if ($self->{check}) {
405 print STDOUT "importsvg: <use> references unknown id '$href'$EOL";
406 }
407 return;
408 }
409  
410 my $target = $_svg_defs{$href};
411 my $ttag = lc $target->localname;
412  
413 $self->gsave();
414 _apply_transform($self, $attr->{transform});
415 my $ux = defined $attr->{x} ? $self->_svgconvert($attr->{x}) : 0;
416 my $uy = defined $attr->{y} ? $self->_svgconvert($attr->{y}) : 0;
417 $self->translate($ux, $uy) if ($ux || $uy);
418  
419 if ($ttag eq 'symbol') {
420 my %tattr = _collect_attrs($target);
421 $self->gsave();
422 _svg_viewbox_transform($self, \%tattr) if defined $tattr{viewBox};
423 _traverse($self, $target);
424 $self->grestore();
425 }
426 else {
427 my %tattr = _collect_attrs($target);
428 my %teff = _svg_effective_style($self, \%tattr);
429 _handle_element($self, $target, $ttag, \%tattr, \%teff);
430 }
431  
432 $self->grestore();
433 }
434  
435  
436 # ===========================================================================
437 # GEOMETRIC ELEMENT HANDLERS
438 # ===========================================================================
439  
440 sub _handle_path ($self, $attr) {
441 my $d = $attr->{d} // return;
442 $self->_dopath($d);
443 }
444  
445 sub _handle_line ($self, $attr) {
446 my $x1 = $self->_svgconvert($attr->{x1} // 0);
447 my $y1 = $self->_svgconvert($attr->{y1} // 0);
448 my $x2 = $self->_svgconvert($attr->{x2} // 0);
449 my $y2 = $self->_svgconvert($attr->{y2} // 0);
450 $self->line($x1, $y1, $x2, $y2);
451 }
452  
453 sub _handle_rect ($self, $attr) {
454 my $x = $self->_svgconvert($attr->{x} // 0);
455 my $y = $self->_svgconvert($attr->{y} // 0);
456 my $w = $self->_svgconvert($attr->{width} // 0);
457 my $h = $self->_svgconvert($attr->{height} // 0);
458 return if $w <= 0 || $h <= 0;
459  
460 my $rx = defined $attr->{rx} ? $self->_svgconvert($attr->{rx}) : undef;
461 my $ry = defined $attr->{ry} ? $self->_svgconvert($attr->{ry}) : undef;
462 $rx //= $ry;
463 $ry //= $rx;
464  
465 if ($rx) {
466 $rx = $w / 2 if $rx > $w / 2;
467 $ry = $h / 2 if $ry > $h / 2;
468 $self->boxround($x, $y, $x + $w, $y + $h, $rx);
469 }
470 else {
471 $self->box($x, $y, $x + $w, $y + $h);
472 }
473 }
474  
475 sub _handle_circle ($self, $attr) {
476 my $cx = $self->_svgconvert($attr->{cx} // 0);
477 my $cy = $self->_svgconvert($attr->{cy} // 0);
478 my $r = $self->_svgconvert($attr->{r} // 0);
479 return if $r <= 0;
480 $self->circle($cx, $cy, $r);
481 }
482  
483 sub _handle_ellipse ($self, $attr) {
484 my $cx = $self->_svgconvert($attr->{cx} // 0);
485 my $cy = $self->_svgconvert($attr->{cy} // 0);
486 my $rx = $self->_svgconvert($attr->{rx} // 0);
487 my $ry = $self->_svgconvert($attr->{ry} // 0);
488 return if $rx <= 0 || $ry <= 0;
489 $self->ellipse($cx, $cy, $rx, $ry);
490 }
491  
492 sub _handle_polyline ($self, $attr, $close) {
493 my $pts = $attr->{points} // return;
494 $pts =~ s/,/ /g;
495 $pts =~ s/\s+/ /g;
496 $pts =~ s/^\s+//;
497 my @c = map { $self->_svgconvert($_) } split / /, $pts;
498 return unless @c >= 4;
499 push @c, $c[0], $c[1] if $close;
500 $self->polygon(@c);
501 }
502  
503  
504 # ===========================================================================
505 # TEXT HANDLING
506 # ===========================================================================
507  
508 sub _handle_text ($self, $node, $attr, $eff) {
509 my $x = defined $attr->{x} ? $self->_svgconvert($attr->{x}) : 0;
510 my $y = defined $attr->{y} ? $self->_svgconvert($attr->{y}) : 0;
511 $self->gsave();
512 $self->translate($x, $y);
513 my $text = _collect_text_content($node);
514 _render_text_content($self, $text, $attr, $eff) if $text =~ /\S/;
515 $self->grestore();
516 }
517  
518 sub _handle_tspan ($self, $node, $attr, $eff) {
519 my $dx = defined $attr->{dx} ? $self->_svgconvert($attr->{dx}) : 0;
520 my $dy = defined $attr->{dy} ? $self->_svgconvert($attr->{dy}) : 0;
521 $self->gsave();
522 if (defined $attr->{x} && defined $attr->{y}) {
523 $self->translate($self->_svgconvert($attr->{x}),
524 $self->_svgconvert($attr->{y}));
525 }
526 elsif ($dx || $dy) {
527 my ($cx, $cy) = $self->currentpoint();
528 $self->translate($cx + $dx, $cy + $dy);
529 }
530 my $text = _collect_text_content($node);
531 _render_text_content($self, $text, $attr, $eff) if $text =~ /\S/;
532 $self->grestore();
533 }
534  
535 sub _collect_text_content ($node) {
536 my $text = '';
537 for my $child ($node->childNodes) {
538 if ($child->nodeType == 3) {
539 $text .= $child->data;
540 }
541 elsif ($child->nodeType == 1 && lc $child->localname eq 'tspan') {
542 $text .= _collect_text_content($child);
543 }
544 }
545 return $text;
546 }
547  
548 sub _render_text_content ($self, $text, $attr, $eff) {
549 my $fontsize = _css_property($eff, 'font-size')
550 // $attr->{'font-size'}
551 // $self->{fontsize}
552 // 12;
553 $fontsize =~ s/[a-z]+$//i;
554  
555 my $fontname = _css_property($eff, 'font-family')
556 // $attr->{'font-family'}
557 // $self->{fontname}
558 // '';
559  
560 if ($fontname && $fontsize) {
561 my $face = eval { $self->setfont($fontname, $fontsize) };
562 if ($face) { $self->stroketext($face, $text); return; }
563 }
564 if ($self->{fontname} && $self->{fontsize}) {
565 my $face = eval { $self->setfont($self->{fontname}, $self->{fontsize}) };
566 if ($face) { $self->stroketext($face, $text); return; }
567 }
568 if ($self->{check}) {
569 print STDOUT "importsvg: text '$text' skipped (no font set)$EOL";
570 }
571 }
572  
573  
574 # ===========================================================================
575 # TRANSFORM HANDLING
576 # The name _apply_transform is used internally; the public name
577 # _dotransform is aliased below for any legacy callers.
578 # ===========================================================================
579  
580 sub _apply_transform ($self, $t) {
581 return unless defined $t && $t ne '';
582  
583 my @calls;
584 while ($t =~ /(\w+)\s*\(([^)]*)\)/g) {
585 push @calls, { type => lc $1, params => [ split /[\s,]+/, $2 ] };
586 }
587  
588 for my $c (@calls) {
589 my @p = @{ $c->{params} };
590  
591 if ($c->{type} eq 'translate') {
592 my $tx = $self->_svgconvert($p[0] // 0);
593 my $ty = defined $p[1] ? $self->_svgconvert($p[1]) : 0;
594 $self->translate($tx, $ty);
595 }
596 elsif ($c->{type} eq 'scale') {
597 my $sx = $p[0] // 1;
598 my $sy = defined $p[1] ? $p[1] : $sx;
599 $self->scale($sx, $sy);
600 }
601 elsif ($c->{type} eq 'rotate') {
602 my $angle = $p[0] // 0;
603 if (defined $p[1] && defined $p[2]) {
604 # Use GcodeXY's 3-arg rotate directly -- the translate-based
605 # workaround used GcodeXY's non-standard translate() which
606 # replaces CTM[0][2]/[1][2] rather than post-multiplying,
607 # giving the wrong result for non-origin centres.
608 my $cx = $self->_svgconvert($p[1]);
609 my $cy = $self->_svgconvert($p[2]);
610 $self->rotate($angle, $cx, $cy);
611 }
612 else {
613 $self->rotate($angle);
614 }
615 }
616 elsif ($c->{type} eq 'skewx') { $self->skewX($p[0] // 0) }
617 elsif ($c->{type} eq 'skewy') { $self->skewY($p[0] // 0) }
618 elsif ($c->{type} eq 'matrix') {
619 # SVG matrix(a,b,c,d,e,f) is column-major: a-d are the 2x2
620 # linear part (dimensionless); e,f are translation and may carry units.
621 my ($a, $b, $c_, $d, $e, $f) = @p;
622 $e = $self->_svgconvert($e // 0);
623 $f = $self->_svgconvert($f // 0);
624 my @matrix = (
625 [ $a, $c_, $e ],
626 [ $b, $d, $f ],
627 [ 0, 0, 1 ],
628 );
629 $self->_premulmat(\@matrix, \@{ $self->{CTM} });
630 }
631 }
632 }
633  
634 # Legacy alias used by GcodeXY.pm internals if still present
635 *_dotransform = \&_apply_transform;
636  
637  
638 # ===========================================================================
639 # CSS STYLE HANDLING
640 # ===========================================================================
641  
642 sub _svg_effective_style ($self, $attr) {
643 my %eff;
644  
645 # 1. Class rules (lowest priority)
646 if (defined $attr->{class}) {
647 for my $cls (split /\s+/, $attr->{class}) {
648 my $rules = $_svg_css_rules{".$cls"} // {};
649 %eff = (%eff, %$rules);
650 }
651 }
652  
653 # 2. Presentation attributes
654 for my $prop (qw(display visibility font-family font-size font-weight)) {
655 $eff{$prop} = $attr->{$prop} if defined $attr->{$prop};
656 }
657  
658 # 3. Inline style (highest priority)
659 if (defined $attr->{style}) {
660 my %inline = _parse_style_attr($attr->{style});
661 %eff = (%eff, %inline);
662 }
663  
664 return %eff;
665 }
666  
667 sub _parse_style_attr ($style) {
668 my %props;
669 for my $decl (split /;/, $style) {
670 $decl =~ s/^\s+|\s+$//g;
671 next unless $decl =~ /:/;
672 my ($prop, $val) = split /:/, $decl, 2;
673 $prop =~ s/^\s+|\s+$//g;
674 $val =~ s/^\s+|\s+$//g;
675 $props{ lc $prop } = $val if defined $val;
676 }
677 return %props;
678 }
679  
680 sub _css_parse_block ($css) {
681 $css =~ s{/\*.*?\*/}{}gs;
682 while ($css =~ /([^{]+)\{([^}]*)\}/g) {
683 my ($sel_list, $decls) = ($1, $2);
684 my %props = _parse_style_attr($decls);
685 for my $sel (split /,/, $sel_list) {
686 $sel =~ s/^\s+|\s+$//g;
687 next unless $sel =~ /\A[\w.-]+\z/;
688 $_svg_css_rules{$sel} = { %{ $_svg_css_rules{$sel} // {} }, %props };
689 }
690 }
691 }
692  
693 sub _css_property ($eff, $prop) {
694 return $eff->{$prop} if defined $eff->{$prop};
695 (my $camel = $prop) =~ s/-([a-z])/uc($1)/ge;
696 return $eff->{$camel};
697 }
698  
699  
700 # ===========================================================================
701 # UNIT CONVERSION
702 # These replace _svg_value_to_inches and _svgconvert in GcodeXY.pm.
703 # Both methods should be REMOVED from GcodeXY.pm.
704 # ===========================================================================
705  
706 sub _svg_value_to_inches ($value) {
707 # Support negative values (e.g. x='-0.5in') and optional whitespace.
708 my ($num, $unit) = $value =~ /^\s*([+-]?[\d.]+)\s*(\D*)\s*$/;
709 return undef unless defined $num;
710 $num += 0;
711 return $num if !defined $unit || $unit eq ''; # bare number: SVG user units
712 $unit = lc $unit;
713 $unit = 'px' unless exists $unit_to_inches{$unit};
714 return $num * $unit_to_inches{$unit};
715 }
716  
717 sub _svgconvert ($self, $value) {
718 $self->_croak('svgconvert: no value provided') unless defined $value;
719 # Bare numbers are SVG user units. When a viewBox transform is active
720 # the CTM encodes the user-unit->GcodeXY mapping, so return them as-is.
721 # Applying px conversion (1/96) would break viewBox coordinate scaling.
722 return $value + 0 if $value =~ /^\s*[+-]?[\d.]+\s*$/;
723 my $inches = _svg_value_to_inches($value);
724 return undef unless defined $inches;
725 return $inches * $inches_to_unit{ $self->{units} };
726 }
727  
728  
729 # ===========================================================================
730 # PATH PROCESSING
731 # _dopath replaces the version in GcodeXY.pm (remove it from there).
732 # ===========================================================================
733  
734 sub _dopath ($self, $d) {
735 # SVG path data must be unitless per spec; strip any unit suffixes that
736 # may appear in hand-crafted or test SVGs (e.g. '1in' -> '1').
737 $d =~ s/(\d)\s*(?:in|mm|cm|px|pt|em|rem)\b/$1/gi;
738 my @r = extract_path_info( $d, { absolute => 1, no_smooth => 1 } );
739 my $x = undef;
740 my $y = undef;
741 my $curx = 0;
742 my $cury = 0;
743 my ($xa, $ya);
744  
745 for (@r) {
746 if ( $_->{svg_key} =~ m{\A[mM]\z}i ) {
747 $self->moveto( $_->{point}[0], $_->{point}[1] );
748 $x = $_->{point}[0];
749 $y = $_->{point}[1];
750 $curx = $_->{point}[0];
751 $cury = $_->{point}[1];
752 }
753 if ( $_->{svg_key} =~ m{\A[lL]\z}i ) {
754 $self->line( $_->{point}[0], $_->{point}[1] );
755 $curx = $_->{point}[0];
756 $cury = $_->{point}[1];
757 }
758 if ( $_->{svg_key} =~ m{\A[vV]\z}i ) {
759 $self->line( $curx, $_->{y} );
760 $cury = $_->{y};
761 }
762 if ( $_->{svg_key} =~ m{\A[hH]\z}i ) {
763 $self->line( $_->{x}, $cury );
764 $curx = $_->{x};
765 }
766 if ( $_->{svg_key} =~ m{\A[zZ]\z}i ) {
767 $self->line( $x, $y );
768 $curx = $x;
769 $cury = $y;
770 }
771 if ( $_->{svg_key} =~ m{\A[cC]\z}i ) {
772 ($xa, $ya) = $self->currentpoint();
773 $self->curve(
774 $xa, $ya,
775 $_->{control1}[0], $_->{control1}[1],
776 $_->{control2}[0], $_->{control2}[1],
777 $_->{end}[0], $_->{end}[1],
778 );
779 $curx = $_->{end}[0];
780 $cury = $_->{end}[1];
781 }
782 if ( $_->{svg_key} =~ m{\A[qQ]\z}i ) {
783 ($xa, $ya) = $self->currentpoint();
784 $self->curve(
785 $xa, $ya,
786 $_->{control}[0], $_->{control}[1],
787 $_->{end}[0], $_->{end}[1],
788 );
789 $curx = $_->{end}[0];
790 $cury = $_->{end}[1];
791 }
792 if ( $_->{svg_key} =~ m{\A[sS]\z}i ) {
793 if ($self->{check}) {
794 print STDOUT "path internal error: s or S command found$EOL";
795 }
796 }
797 if ( $_->{svg_key} =~ m{\A[tT]\z}i ) {
798 if ($self->{check}) {
799 print STDOUT "path internal error: t or T command found$EOL";
800 }
801 }
802 if ( $_->{svg_key} =~ m{\A[aA]\z}i ) {
803 ($xa, $ya) = $self->currentpoint();
804 $self->_a2c( $xa, $ya,
805 $_->{rx}, $_->{ry}, $_->{x_axis_rotation},
806 $_->{large_arc_flag}, $_->{sweep_flag},
807 $_->{x}, $_->{y} );
808 $curx = $_->{x};
809 $cury = $_->{y};
810 }
811 }
812 return 1;
813 }
814  
815  
816 # ===========================================================================
817 # ARC MATH
818 # These three functions and _a2c replace the versions in GcodeXY.pm.
819 # Remove the originals from GcodeXY.pm.
820 # ===========================================================================
821  
822 sub _unit_vector_angle ($ux, $uy, $vx, $vy) {
823 my $sign = ($ux * $vy - $uy * $vx < 0) ? -1 : 1;
824 my $dot = $ux * $vx + $uy * $vy;
825 $dot /= sqrt($ux*$ux + $uy*$uy) * sqrt($vx*$vx + $vy*$vy);
826 $dot = 1.0 if $dot > 1.0;
827 $dot = -1.0 if $dot < -1.0;
828 return $sign * acos($dot);
829 }
830  
831 sub _get_arc_center ($x1, $y1, $x2, $y2, $fa, $fs, $rx, $ry, $sin_phi, $cos_phi) {
832 my $x1p = $cos_phi * ($x1 - $x2) / 2 + $sin_phi * ($y1 - $y2) / 2;
833 my $y1p = -$sin_phi * ($x1 - $x2) / 2 + $cos_phi * ($y1 - $y2) / 2;
834 my $rx_sq = $rx * $rx;
835 my $ry_sq = $ry * $ry;
836 my $x1p_sq = $x1p * $x1p;
837 my $y1p_sq = $y1p * $y1p;
838 my $radicant = ($rx_sq * $ry_sq) - ($rx_sq * $y1p_sq) - ($ry_sq * $x1p_sq);
839 $radicant = 0 if $radicant < 0;
840 $radicant /= ($rx_sq * $y1p_sq) + ($ry_sq * $x1p_sq);
841 $radicant = sqrt($radicant) * ($fa == $fs ? -1 : 1);
842 my $cxp = $radicant * $rx / $ry * $y1p;
843 my $cyp = $radicant * -$ry / $rx * $x1p;
844 my $cx = $cos_phi * $cxp - $sin_phi * $cyp + ($x1 + $x2) / 2;
845 my $cy = $sin_phi * $cxp + $cos_phi * $cyp + ($y1 + $y2) / 2;
846 my $v1x = ( $x1p - $cxp) / $rx;
847 my $v1y = ( $y1p - $cyp) / $ry;
848 my $v2x = (-$x1p - $cxp) / $rx;
849 my $v2y = (-$y1p - $cyp) / $ry;
850 my $theta1 = _unit_vector_angle(1, 0, $v1x, $v1y);
851 my $delta_theta = _unit_vector_angle($v1x, $v1y, $v2x, $v2y);
852 $delta_theta -= $TWOPI if $fs == 0 && $delta_theta > 0;
853 $delta_theta += $TWOPI if $fs == 1 && $delta_theta < 0;
854 return ($cx, $cy, $theta1, $delta_theta);
855 }
856  
857 sub _approximate_unit_arc ($theta1, $delta_theta) {
858 my $alpha = 4 / 3 * tan($delta_theta / 4);
859 my $x1 = cos $theta1;
860 my $y1 = sin $theta1;
861 my $x2 = cos($theta1 + $delta_theta);
862 my $y2 = sin($theta1 + $delta_theta);
863 return (
864 $x1, $y1,
865 $x1 - $y1 * $alpha,
866 $y1 + $x1 * $alpha,
867 $x2 + $y2 * $alpha,
868 $y2 - $x2 * $alpha,
869 $x2, $y2,
870 );
871 }
872  
873 sub _a2c ($self, $x1, $y1, $rx, $ry, $phi, $fa, $fs, $x2, $y2) {
874 my $sin_phi = sin($phi * $TWOPI / 360);
875 my $cos_phi = cos($phi * $TWOPI / 360);
876 my $x1p = $cos_phi * ($x1 - $x2) / 2 + $sin_phi * ($y1 - $y2) / 2;
877 my $y1p = -$sin_phi * ($x1 - $x2) / 2 + $cos_phi * ($y1 - $y2) / 2;
878 return 0 if $x1p == 0 && $y1p == 0;
879 return 0 if $rx == 0 || $ry == 0;
880 $rx = abs $rx;
881 $ry = abs $ry;
882 my $lambda = ($x1p * $x1p) / ($rx * $rx) + ($y1p * $y1p) / ($ry * $ry);
883 if ($lambda > 1) { $rx *= sqrt $lambda; $ry *= sqrt $lambda; }
884 my @cc = _get_arc_center($x1, $y1, $x2, $y2, $fa, $fs,
885 $rx, $ry, $sin_phi, $cos_phi);
886 my $theta1 = $cc[2];
887 my $delta_theta = $cc[3];
888 my $segments = max(ceil(abs($delta_theta) / ($TWOPI / 4)), 1);
889 $delta_theta /= $segments;
890 for (my $i = 0; $i < $segments; $i++) {
891 my @curve = _approximate_unit_arc($theta1, $delta_theta);
892 for (my $j = 0; $j < scalar @curve; $j += 2) {
893 my $x = $curve[$j] * $rx;
894 my $y = $curve[$j+1] * $ry;
895 my $xp = $cos_phi * $x - $sin_phi * $y;
896 my $yp = $sin_phi * $x + $cos_phi * $y;
897 $curve[$j] = $xp + $cc[0];
898 $curve[$j+1] = $yp + $cc[1];
899 }
900 $self->curve(@curve);
901 $theta1 += $delta_theta;
902 }
903 return 1;
904 }
905  
906  
907 1;
908  
909 __END__