1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
use crate::plugins::Plugin;
use crate::tree::{Document, Node};
pub struct ConvertPathData {
pub float_precision: usize,
pub leading_zero: bool,
// Add more opts as needed
}
impl Default for ConvertPathData {
fn default() -> Self {
Self {
float_precision: 3,
leading_zero: true,
}
}
}
impl Plugin for ConvertPathData {
fn apply(&self, doc: &mut Document) {
process_paths(&mut doc.root, self);
}
}
fn process_paths(nodes: &mut Vec<Node>, opts: &ConvertPathData) {
for node in nodes {
if let Node::Element(elem) = node {
if elem.name == "path" {
if let Some(d) = elem.attributes.get_mut("d") {
let new_d = optimize_path_data(d, opts);
*d = new_d;
}
}
process_paths(&mut elem.children, opts);
}
}
}
fn optimize_path_data(d: &str, opts: &ConvertPathData) -> String {
let commands = parse_path_data(d);
stringify_optimized(&commands, opts)
}
#[derive(Debug, Clone, PartialEq)]
enum Command {
// We store minimal data, usually absolute for analysis?
// Actually, to choose best representation, let's store Absolute coordinates internally
// and decide Rel/Abs at stringify time.
Move(f64, f64),
Line(f64, f64),
Horiz(f64),
Vert(f64),
Curve(f64, f64, f64, f64, f64, f64), // x1 y1 x2 y2 x y
SmoothCurve(f64, f64, f64, f64), // x2 y2 x y
Quad(f64, f64, f64, f64), // x1 y1 x y
SmoothQuad(f64, f64), // x y
Arc(f64, f64, f64, bool, bool, f64, f64),
Close,
}
// Struct removed. Using PathLexer below.
// ... Lexer implementation ...
// To be robust, let's maintain the decent lexer from previous step but adapt output to Normalized Commands (Absolute).
// Converting everything to absolute simplifies optimization logic (L vs H vs V).
fn parse_path_data(d: &str) -> Vec<Command> {
// Current pen position
let mut cur_x = 0.0;
let mut cur_y = 0.0;
// Previous control point for S/T (absolute)
// If previous was C/S, ctrl point is second control point. Else current point (reflection).
// Actually we don't need to track prev control point during parsing if we just convert rel->abs.
// Rel just adds to cur_x/cur_y.
let mut commands = Vec::new();
// Reuse the lexer logic from previous step efficiently
let mut lexer = PathLexer::new(d);
let mut current_cmd_char = None;
loop {
lexer.skip_ws_comma();
let c_opt = lexer.peek_char();
if c_opt.is_none() {
break;
}
let c = c_opt.unwrap();
let cmd_char = if c.is_ascii_alphabetic() {
lexer.read_char().unwrap()
} else {
// Implicit
if let Some(cmd) = current_cmd_char {
if cmd == 'M' {
'L'
} else if cmd == 'm' {
'l'
} else {
cmd
}
} else {
break;
}
};
current_cmd_char = Some(cmd_char);
match cmd_char {
'M' => {
while let (Some(x), Some(y)) = (lexer.read_number(), lexer.read_number()) {
commands.push(Command::Move(x, y));
cur_x = x;
cur_y = y;
current_cmd_char = Some('L'); // Subsequent are Line
}
}
'm' => {
while let (Some(dx), Some(dy)) = (lexer.read_number(), lexer.read_number()) {
let nx = cur_x + dx;
let ny = cur_y + dy;
commands.push(Command::Move(nx, ny));
cur_x = nx;
cur_y = ny;
current_cmd_char = Some('l');
}
}
'L' => {
while let (Some(x), Some(y)) = (lexer.read_number(), lexer.read_number()) {
commands.push(Command::Line(x, y));
cur_x = x;
cur_y = y;
}
}
'l' => {
while let (Some(dx), Some(dy)) = (lexer.read_number(), lexer.read_number()) {
let nx = cur_x + dx;
let ny = cur_y + dy;
commands.push(Command::Line(nx, ny));
cur_x = nx;
cur_y = ny;
}
}
'H' => {
while let Some(x) = lexer.read_number() {
commands.push(Command::Horiz(x));
cur_x = x;
}
}
'h' => {
while let Some(dx) = lexer.read_number() {
let nx = cur_x + dx;
commands.push(Command::Horiz(nx));
cur_x = nx;
}
}
'V' => {
while let Some(y) = lexer.read_number() {
commands.push(Command::Vert(y));
cur_y = y;
}
}
'v' => {
while let Some(dy) = lexer.read_number() {
let ny = cur_y + dy;
commands.push(Command::Vert(ny));
cur_y = ny;
}
}
'Z' | 'z' => {
commands.push(Command::Close);
// No args.
// Need start point of subpath? For Z calculation?
// Z closes to most recent Move.
// But for next command, pos is subpath start.
// Tracking subpath start is needed for correct pen pos after Z.
}
'C' => {
while let (Some(x1), Some(y1), Some(x2), Some(y2), Some(x), Some(y)) = (
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
) {
commands.push(Command::Curve(x1, y1, x2, y2, x, y));
cur_x = x;
cur_y = y;
}
}
'c' => {
while let (Some(dx1), Some(dy1), Some(dx2), Some(dy2), Some(dx), Some(dy)) = (
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
) {
let nx = cur_x + dx;
let ny = cur_y + dy;
commands.push(Command::Curve(
cur_x + dx1,
cur_y + dy1,
cur_x + dx2,
cur_y + dy2,
nx,
ny,
));
cur_x = nx;
cur_y = ny;
}
}
'S' => {
while let (Some(x2), Some(y2), Some(x), Some(y)) = (
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
) {
commands.push(Command::SmoothCurve(x2, y2, x, y));
cur_x = x;
cur_y = y;
}
}
's' => {
while let (Some(dx2), Some(dy2), Some(dx), Some(dy)) = (
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
) {
let nx = cur_x + dx;
let ny = cur_y + dy;
commands.push(Command::SmoothCurve(cur_x + dx2, cur_y + dy2, nx, ny));
cur_x = nx;
cur_y = ny;
}
}
'Q' => {
while let (Some(x1), Some(y1), Some(x), Some(y)) = (
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
) {
commands.push(Command::Quad(x1, y1, x, y));
cur_x = x;
cur_y = y;
}
}
'q' => {
while let (Some(dx1), Some(dy1), Some(dx), Some(dy)) = (
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
lexer.read_number(),
) {
let nx = cur_x + dx;
let ny = cur_y + dy;
commands.push(Command::Quad(cur_x + dx1, cur_y + dy1, nx, ny));
cur_x = nx;
cur_y = ny;
}
}
'T' => {
while let (Some(x), Some(y)) = (lexer.read_number(), lexer.read_number()) {
commands.push(Command::SmoothQuad(x, y));
cur_x = x;
cur_y = y;
}
}
't' => {
while let (Some(dx), Some(dy)) = (lexer.read_number(), lexer.read_number()) {
let nx = cur_x + dx;
let ny = cur_y + dy;
commands.push(Command::SmoothQuad(nx, ny));
cur_x = nx;
cur_y = ny;
}
}
'A' => loop {
let rx = lexer.read_number();
if rx.is_none() {
break;
}
let ry = lexer.read_number();
if ry.is_none() {
break;
}
let rot = lexer.read_number();
if rot.is_none() {
break;
}
let la = lexer.read_flag();
if la.is_none() {
break;
}
let sf = lexer.read_flag();
if sf.is_none() {
break;
}
let x = lexer.read_number();
if x.is_none() {
break;
}
let y = lexer.read_number();
if y.is_none() {
break;
}
let rx = rx.unwrap();
let ry = ry.unwrap();
let rot = rot.unwrap();
let la = la.unwrap();
let sf = sf.unwrap();
let x = x.unwrap();
let y = y.unwrap();
commands.push(Command::Arc(rx, ry, rot, la, sf, x, y));
cur_x = x;
cur_y = y;
},
'a' => loop {
let rx = lexer.read_number();
if rx.is_none() {
break;
}
let ry = lexer.read_number();
if ry.is_none() {
break;
}
let rot = lexer.read_number();
if rot.is_none() {
break;
}
let la = lexer.read_flag();
if la.is_none() {
break;
}
let sf = lexer.read_flag();
if sf.is_none() {
break;
}
let dx = lexer.read_number();
if dx.is_none() {
break;
}
let dy = lexer.read_number();
if dy.is_none() {
break;
}
let rx = rx.unwrap();
let ry = ry.unwrap();
let rot = rot.unwrap();
let la = la.unwrap();
let sf = sf.unwrap();
let dx = dx.unwrap();
let dy = dy.unwrap();
let nx = cur_x + dx;
let ny = cur_y + dy;
commands.push(Command::Arc(rx, ry, rot, la, sf, nx, ny));
cur_x = nx;
cur_y = ny;
},
_ => {
break;
}
}
}
// Fix Close Z/z position tracking
// Parsing Z should implicitly move pen to start of subpath.
// For exact tracking we need to store start_x/y of last Move.
// Simplifying for now - Z does not produce coords.
commands
}
fn format_num(n: f64, p: usize) -> String {
let factor = 10u32.pow(p as u32) as f64;
let rounded = (n * factor).round() / factor;
// Remove leading zeros etc.
let s = rounded.to_string();
if s.starts_with("0.") {
s[1..].to_string()
} else if s.starts_with("-0.") {
format!("-{}", &s[2..])
} else {
s
}
}
fn stringify_optimized(commands: &[Command], opts: &ConvertPathData) -> String {
let mut s = String::new();
let p = opts.float_precision;
// State for optimization
let mut cur_x = 0.0;
let mut cur_y = 0.0;
let mut subpath_start_x = 0.0;
let mut subpath_start_y = 0.0;
for cmd in commands {
match cmd {
Command::Move(x, y) => {
// Always M? Or m?
// M is usually safest/clearest for start.
// relative m is only relative to (0,0) if first, or prev command.
let abs_str = format!("M{} {}", format_num(*x, p), format_num(*y, p));
let rel_str = format!(
"m{} {}",
format_num(*x - cur_x, p),
format_num(*y - cur_y, p)
);
if rel_str.len() < abs_str.len() {
s.push_str(&rel_str);
} else {
s.push_str(&abs_str);
}
cur_x = *x;
cur_y = *y;
subpath_start_x = *x;
subpath_start_y = *y;
}
Command::Line(x, y) => {
let abs_x_s = format_num(*x, p);
let abs_y_s = format_num(*y, p);
let rel_x_s = format_num(*x - cur_x, p);
let rel_y_s = format_num(*y - cur_y, p);
// Candidates:
// L x y
// l dx dy
// H x (if y == cur_y)
// h dx (if y == cur_y)
// V y (if x == cur_x)
// v dy (if x == cur_x)
let mut best_str = format!("L{} {}", abs_x_s, abs_y_s);
let rel_l = format!("l{} {}", rel_x_s, rel_y_s);
if rel_l.len() < best_str.len() {
best_str = rel_l;
}
// H/h check (check rounded values to be safe?)
// Effectively we check if diff is close to 0.
if (y - cur_y).abs() < f64::EPSILON {
let abs_h = format!("H{}", abs_x_s);
let rel_h = format!("h{}", rel_x_s);
if abs_h.len() < best_str.len() {
best_str = abs_h;
}
if rel_h.len() < best_str.len() {
best_str = rel_h;
}
}
if (x - cur_x).abs() < f64::EPSILON {
let abs_v = format!("V{}", abs_y_s);
let rel_v = format!("v{}", rel_y_s);
if abs_v.len() < best_str.len() {
best_str = abs_v;
}
if rel_v.len() < best_str.len() {
best_str = rel_v;
}
}
s.push_str(&best_str);
cur_x = *x;
cur_y = *y;
}
Command::Horiz(x) => {
// Just optimize to H/h
let abs_s = format!("H{}", format_num(*x, p));
let rel_s = format!("h{}", format_num(*x - cur_x, p));
if rel_s.len() < abs_s.len() {
s.push_str(&rel_s);
} else {
s.push_str(&abs_s);
}
cur_x = *x;
}
Command::Vert(y) => {
let abs_s = format!("V{}", format_num(*y, p));
let rel_s = format!("v{}", format_num(*y - cur_y, p));
if rel_s.len() < abs_s.len() {
s.push_str(&rel_s);
} else {
s.push_str(&abs_s);
}
cur_y = *y;
}
Command::Close => {
s.push('z');
cur_x = subpath_start_x;
cur_y = subpath_start_y;
}
// ... Implement others (Curve, Quad, Arc) similar way
Command::Curve(x1, y1, x2, y2, x, y) => {
let abs_coords = format!(
"{} {} {} {} {} {}",
format_num(*x1, p),
format_num(*y1, p),
format_num(*x2, p),
format_num(*y2, p),
format_num(*x, p),
format_num(*y, p)
);
let rel_coords = format!(
"{} {} {} {} {} {}",
format_num(*x1 - cur_x, p),
format_num(*y1 - cur_y, p),
format_num(*x2 - cur_x, p),
format_num(*y2 - cur_y, p),
format_num(*x - cur_x, p),
format_num(*y - cur_y, p)
);
let abs_s = format!("C{}", abs_coords);
let rel_s = format!("c{}", rel_coords);
if rel_s.len() < abs_s.len() {
s.push_str(&rel_s);
} else {
s.push_str(&abs_s);
}
cur_x = *x;
cur_y = *y;
}
Command::SmoothCurve(x2, y2, x, y) => {
let abs_coords = format!(
"{} {} {} {}",
format_num(*x2, p),
format_num(*y2, p),
format_num(*x, p),
format_num(*y, p)
);
let rel_coords = format!(
"{} {} {} {}",
format_num(*x2 - cur_x, p),
format_num(*y2 - cur_y, p),
format_num(*x - cur_x, p),
format_num(*y - cur_y, p)
);
let abs_s = format!("S{}", abs_coords);
let rel_s = format!("s{}", rel_coords);
if rel_s.len() < abs_s.len() {
s.push_str(&rel_s);
} else {
s.push_str(&abs_s);
}
cur_x = *x;
cur_y = *y;
}
Command::Quad(x1, y1, x, y) => {
let abs_coords = format!(
"{} {} {} {}",
format_num(*x1, p),
format_num(*y1, p),
format_num(*x, p),
format_num(*y, p)
);
let rel_coords = format!(
"{} {} {} {}",
format_num(*x1 - cur_x, p),
format_num(*y1 - cur_y, p),
format_num(*x - cur_x, p),
format_num(*y - cur_y, p)
);
let abs_s = format!("Q{}", abs_coords);
let rel_s = format!("q{}", rel_coords);
if rel_s.len() < abs_s.len() {
s.push_str(&rel_s);
} else {
s.push_str(&abs_s);
}
cur_x = *x;
cur_y = *y;
}
Command::SmoothQuad(x, y) => {
let abs_coords = format!("{} {}", format_num(*x, p), format_num(*y, p));
let rel_coords = format!(
"{} {}",
format_num(*x - cur_x, p),
format_num(*y - cur_y, p)
);
let abs_s = format!("T{}", abs_coords);
let rel_s = format!("t{}", rel_coords);
if rel_s.len() < abs_s.len() {
s.push_str(&rel_s);
} else {
s.push_str(&abs_s);
}
cur_x = *x;
cur_y = *y;
}
Command::Arc(rx, ry, rot, la, sf, x, y) => {
// Formatting arc flags: 0 or 1
let la_s = if *la { "1" } else { "0" };
let sf_s = if *sf { "1" } else { "0" };
let abs_coords = format!(
"{} {} {} {} {} {} {}",
format_num(*rx, p),
format_num(*ry, p),
format_num(*rot, p),
la_s,
sf_s,
format_num(*x, p),
format_num(*y, p)
);
let rel_coords = format!(
"{} {} {} {} {} {} {}",
format_num(*rx, p),
format_num(*ry, p),
format_num(*rot, p),
la_s,
sf_s,
format_num(*x - cur_x, p),
format_num(*y - cur_y, p)
);
let abs_s = format!("A{}", abs_coords);
let rel_s = format!("a{}", rel_coords);
if rel_s.len() < abs_s.len() {
s.push_str(&rel_s);
} else {
s.push_str(&abs_s);
}
cur_x = *x;
cur_y = *y;
}
}
}
s
}
// Reuse PathLexer from previous tool call (need to duplicate code here as I'm overwriting file)
struct PathLexer<'a> {
input: &'a str,
pos: usize,
}
impl<'a> PathLexer<'a> {
fn new(input: &'a str) -> Self {
Self { input, pos: 0 }
}
fn skip_ws_comma(&mut self) {
while self.pos < self.input.len() {
let c = self.input.as_bytes()[self.pos] as char;
if c.is_whitespace() || c == ',' {
self.pos += 1;
} else {
break;
}
}
}
fn peek_char(&self) -> Option<char> {
if self.pos >= self.input.len() {
None
} else {
Some(self.input.as_bytes()[self.pos] as char)
}
}
fn read_char(&mut self) -> Option<char> {
if self.pos >= self.input.len() {
None
} else {
let c = self.input.as_bytes()[self.pos] as char;
self.pos += 1;
Some(c)
}
}
fn read_number(&mut self) -> Option<f64> {
self.skip_ws_comma();
if self.pos >= self.input.len() {
return None;
}
let start = self.pos;
let mut seen_dot = false;
let mut seen_exp = false;
if self.peek_char() == Some('+') || self.peek_char() == Some('-') {
self.pos += 1;
}
while self.pos < self.input.len() {
let c = self.input.as_bytes()[self.pos] as char;
if c.is_ascii_digit() {
self.pos += 1;
} else if c == '.' && !seen_dot && !seen_exp {
seen_dot = true;
self.pos += 1;
} else if (c == 'e' || c == 'E') && !seen_exp {
seen_exp = true;
self.pos += 1;
if self.peek_char() == Some('+') || self.peek_char() == Some('-') {
self.pos += 1;
}
} else {
break;
}
}
let sub = &self.input[start..self.pos];
sub.parse::<f64>().ok()
}
fn read_flag(&mut self) -> Option<bool> {
self.skip_ws_comma();
match self.read_char() {
Some('0') => Some(false),
Some('1') => Some(true),
_ => None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_optimize_line_rel() {
// M 10 10 L 11 11
// L 11 11 (7 chars)
// l 1 1 (5 chars) -> Wins
let input = "M 10 10 L 11 11";
let out = optimize_path_data(input, &ConvertPathData::default());
assert_eq!(out, "M10 10l1 1");
}
#[test]
fn test_optimize_line_hz() {
// M 10 10 L 20 10
// L 20 10 (7)
// l 10 0 (6)
// H 20 (3) -> Wins
let input = "M 10 10 L 20 10";
let out = optimize_path_data(input, &ConvertPathData::default());
assert_eq!(out, "M10 10H20");
}
#[test]
fn test_optimize_arc() {
// Circle path from convert_shape_to_path
let input = "M0 50A50 50 0 1 0 100 50A50 50 0 1 0 0 50z";
let out = optimize_path_data(input, &ConvertPathData::default());
println!("Optimized Arc: '{}'", out);
// Should not lose the arcs!
assert!(
out.contains("A") || out.contains("a"),
"Output was: {}",
out
);
}
}