Skip to main content

aylis_core/
path.rs

1//! Caminhos vetoriais: retas, curvas e arcos, para ícones, cabos,
2//! gráficos e formas livres. Lê o atributo `d` do SVG.
3
4use crate::geometry::{PointF, RectF};
5
6/// Um comando do caminho (coordenadas absolutas).
7#[derive(Clone, Copy, Debug, PartialEq)]
8pub enum PathCmd {
9    MoveTo(PointF),
10    LineTo(PointF),
11    QuadTo(PointF, PointF),
12    CubicTo(PointF, PointF, PointF),
13    Close,
14}
15
16/// Um caminho: uma ou mais figuras, abertas ou fechadas.
17#[derive(Clone, Debug, Default, PartialEq)]
18pub struct Path {
19    pub cmds: Vec<PathCmd>,
20    /// Regra de preenchimento "par-ímpar" (`fill-rule="evenodd"` do SVG); o padrão é
21    /// "não zero".
22    pub even_odd: bool,
23}
24
25fn pt(x: f32, y: f32) -> PointF {
26    PointF::new(x, y)
27}
28
29impl Path {
30    pub fn new() -> Self {
31        Self::default()
32    }
33
34    pub fn is_empty(&self) -> bool {
35        self.cmds.is_empty()
36    }
37
38    pub fn move_to(&mut self, x: f32, y: f32) -> &mut Self {
39        self.cmds.push(PathCmd::MoveTo(pt(x, y)));
40        self
41    }
42
43    pub fn line_to(&mut self, x: f32, y: f32) -> &mut Self {
44        self.cmds.push(PathCmd::LineTo(pt(x, y)));
45        self
46    }
47
48    pub fn quad_to(&mut self, cx: f32, cy: f32, x: f32, y: f32) -> &mut Self {
49        self.cmds.push(PathCmd::QuadTo(pt(cx, cy), pt(x, y)));
50        self
51    }
52
53    pub fn cubic_to(&mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) -> &mut Self {
54        self.cmds.push(PathCmd::CubicTo(pt(c1x, c1y), pt(c2x, c2y), pt(x, y)));
55        self
56    }
57
58    pub fn close(&mut self) -> &mut Self {
59        self.cmds.push(PathCmd::Close);
60        self
61    }
62
63    /// O contorno de `r` com um raio por canto, na ordem do CSS em `c`: `left` = cima-esquerda,
64    /// `top` = cima-direita, `right` = baixo-direita, `bottom` = baixo-esquerda (o `radius: [8,
65    /// 8, 0, 0]` do JSON). Raio negativo curva o canto **para fora** do retângulo, em direção ao
66    /// lado de cima ou de baixo (a aba que se funde no painel, como as do navegador): o desenho
67    /// passa do retângulo nesse tanto.
68    pub fn corners(r: crate::RectF, c: crate::Bounds) -> Path {
69        let (x0, y0, x1, y1) = (r.x, r.y, r.right(), r.bottom());
70        let limit = (r.width.min(r.height) / 2.0).max(0.0);
71        // Para dentro, no máximo metade do lado menor; para fora, até 64.
72        let clamp = |v: f32| if v > 0.0 { v.min(limit) } else { v.max(-64.0) };
73        let (tl, tr, br, bl) = (clamp(c.left), clamp(c.top), clamp(c.right), clamp(c.bottom));
74        let mut p = Path::new();
75        // Cima-esquerda.
76        if tl > 0.0 {
77            p.move_to(x0, y0 + tl);
78            p.arc(pt(x0 + tl, y0 + tl), tl, tl, 180.0, 90.0);
79        } else if tl < 0.0 {
80            let a = -tl;
81            p.move_to(x0, y0 + a);
82            p.arc(pt(x0 - a, y0 + a), a, a, 0.0, -90.0);
83        } else {
84            p.move_to(x0, y0);
85        }
86        // Cima-direita.
87        if tr > 0.0 {
88            p.line_to(x1 - tr, y0);
89            p.arc(pt(x1 - tr, y0 + tr), tr, tr, 270.0, 90.0);
90        } else if tr < 0.0 {
91            let a = -tr;
92            p.line_to(x1 + a, y0);
93            p.arc(pt(x1 + a, y0 + a), a, a, 270.0, -90.0);
94        } else {
95            p.line_to(x1, y0);
96        }
97        // Baixo-direita.
98        if br > 0.0 {
99            p.line_to(x1, y1 - br);
100            p.arc(pt(x1 - br, y1 - br), br, br, 0.0, 90.0);
101        } else if br < 0.0 {
102            let a = -br;
103            p.line_to(x1, y1 - a);
104            p.arc(pt(x1 + a, y1 - a), a, a, 180.0, -90.0);
105        } else {
106            p.line_to(x1, y1);
107        }
108        // Baixo-esquerda.
109        if bl > 0.0 {
110            p.line_to(x0 + bl, y1);
111            p.arc(pt(x0 + bl, y1 - bl), bl, bl, 90.0, 90.0);
112        } else if bl < 0.0 {
113            let a = -bl;
114            p.line_to(x0 - a, y1);
115            p.arc(pt(x0 - a, y1 - a), a, a, 90.0, -90.0);
116        } else {
117            p.line_to(x0, y1);
118        }
119        p.close();
120        p
121    }
122
123    /// Arco de elipse em volta de `center`, de `start` a `start + sweep` (graus; 0 aponta
124    /// para a direita e o ângulo cresce no sentido horário, como na tela). Liga com uma
125    /// reta ao ponto atual (ou começa uma figura, se o caminho estiver vazio).
126    pub fn arc(&mut self, center: PointF, rx: f32, ry: f32, start: f32, sweep: f32) -> &mut Self {
127        let (a0, da) = (start.to_radians(), sweep.to_radians());
128        let first = pt(center.x + rx * a0.cos(), center.y + ry * a0.sin());
129        if self.current().is_none() {
130            self.cmds.push(PathCmd::MoveTo(first));
131        } else {
132            self.cmds.push(PathCmd::LineTo(first));
133        }
134        self.arc_segments(center, rx, ry, 0.0, a0, da);
135        self
136    }
137
138    /// Retângulo (de cantos arredondados com `radius` > 0).
139    pub fn rect(&mut self, r: RectF, radius: f32) -> &mut Self {
140        let radius = radius.min(r.width / 2.0).min(r.height / 2.0).max(0.0);
141        if radius <= 0.0 {
142            self.move_to(r.x, r.y).line_to(r.right(), r.y).line_to(r.right(), r.bottom()).line_to(r.x, r.bottom()).close();
143            return self;
144        }
145        let k = radius * 0.552_284_8;
146        let (l, t, rr, b) = (r.x, r.y, r.right(), r.bottom());
147        self.move_to(l + radius, t)
148            .line_to(rr - radius, t)
149            .cubic_to(rr - radius + k, t, rr, t + radius - k, rr, t + radius)
150            .line_to(rr, b - radius)
151            .cubic_to(rr, b - radius + k, rr - radius + k, b, rr - radius, b)
152            .line_to(l + radius, b)
153            .cubic_to(l + radius - k, b, l, b - radius + k, l, b - radius)
154            .line_to(l, t + radius)
155            .cubic_to(l, t + radius - k, l + radius - k, t, l + radius, t)
156            .close()
157    }
158
159    /// Elipse inscrita no retângulo.
160    pub fn ellipse(&mut self, r: RectF) -> &mut Self {
161        let (cx, cy, rx, ry) = (r.x + r.width / 2.0, r.y + r.height / 2.0, r.width / 2.0, r.height / 2.0);
162        let (kx, ky) = (rx * 0.552_284_8, ry * 0.552_284_8);
163        self.move_to(cx + rx, cy)
164            .cubic_to(cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry)
165            .cubic_to(cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy)
166            .cubic_to(cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry)
167            .cubic_to(cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy)
168            .close()
169    }
170
171    /// Polígono (ou linha quebrada, se `closed` for falso).
172    pub fn polygon(&mut self, points: &[PointF], closed: bool) -> &mut Self {
173        for (i, p) in points.iter().enumerate() {
174            if i == 0 { self.move_to(p.x, p.y) } else { self.line_to(p.x, p.y) };
175        }
176        if closed && !points.is_empty() {
177            self.close();
178        }
179        self
180    }
181
182    /// Último ponto do caminho.
183    pub fn current(&self) -> Option<PointF> {
184        let mut start = None;
185        let mut cur = None;
186        for c in &self.cmds {
187            match *c {
188                PathCmd::MoveTo(p) => {
189                    start = Some(p);
190                    cur = Some(p);
191                }
192                PathCmd::LineTo(p) | PathCmd::QuadTo(_, p) | PathCmd::CubicTo(_, _, p) => cur = Some(p),
193                PathCmd::Close => cur = start,
194            }
195        }
196        cur
197    }
198
199    /// Arcos em pedaços de no máximo 90°, cada um como uma curva cúbica.
200    fn arc_segments(&mut self, c: PointF, rx: f32, ry: f32, phi: f32, a0: f32, da: f32) {
201        let n = (da.abs() / std::f32::consts::FRAC_PI_2).ceil().max(1.0) as usize;
202        let step = da / n as f32;
203        let k = 4.0 / 3.0 * (step / 4.0).tan();
204        let (sp, cp) = phi.sin_cos();
205        let map = |x: f32, y: f32| pt(c.x + x * rx * cp - y * ry * sp, c.y + x * rx * sp + y * ry * cp);
206        let mut a = a0;
207        for _ in 0..n {
208            let b = a + step;
209            let (sa, ca) = a.sin_cos();
210            let (sb, cb) = b.sin_cos();
211            let p1 = map(ca - k * sa, sa + k * ca);
212            let p2 = map(cb + k * sb, sb - k * cb);
213            let p3 = map(cb, sb);
214            self.cmds.push(PathCmd::CubicTo(p1, p2, p3));
215            a = b;
216        }
217    }
218
219    /// Lê o atributo `d` do SVG (`M L H V C S Q T A Z`, maiúsculas e minúsculas).
220    /// `None` se estiver mal formado.
221    pub fn from_svg(d: &str) -> Option<Path> {
222        let mut path = Path::new();
223        let mut tokens = SvgTokens { s: d.as_bytes(), i: 0 };
224        let mut cmd = b'M';
225        let mut cur = pt(0.0, 0.0);
226        let mut start = cur;
227        // Último ponto de controle (para S e T).
228        let mut last_cubic: Option<PointF> = None;
229        let mut last_quad: Option<PointF> = None;
230        loop {
231            tokens.skip_separators();
232            if tokens.done() {
233                break;
234            }
235            if let Some(c) = tokens.command() {
236                cmd = c;
237            } else if cmd == b'Z' || cmd == b'z' {
238                return None; // números depois de Z
239            }
240            let rel = cmd.is_ascii_lowercase();
241            let base = if rel { cur } else { pt(0.0, 0.0) };
242            let mut num = || tokens.number();
243            match cmd.to_ascii_uppercase() {
244                b'M' => {
245                    let p = pt(base.x + num()?, base.y + num()?);
246                    path.cmds.push(PathCmd::MoveTo(p));
247                    cur = p;
248                    start = p;
249                    // Pares seguintes são retas.
250                    cmd = if rel { b'l' } else { b'L' };
251                    last_cubic = None;
252                    last_quad = None;
253                }
254                b'L' => {
255                    let p = pt(base.x + num()?, base.y + num()?);
256                    path.cmds.push(PathCmd::LineTo(p));
257                    cur = p;
258                    last_cubic = None;
259                    last_quad = None;
260                }
261                b'H' => {
262                    let x = num()? + if rel { cur.x } else { 0.0 };
263                    cur = pt(x, cur.y);
264                    path.cmds.push(PathCmd::LineTo(cur));
265                    last_cubic = None;
266                    last_quad = None;
267                }
268                b'V' => {
269                    let y = num()? + if rel { cur.y } else { 0.0 };
270                    cur = pt(cur.x, y);
271                    path.cmds.push(PathCmd::LineTo(cur));
272                    last_cubic = None;
273                    last_quad = None;
274                }
275                b'C' => {
276                    let c1 = pt(base.x + num()?, base.y + num()?);
277                    let c2 = pt(base.x + num()?, base.y + num()?);
278                    let p = pt(base.x + num()?, base.y + num()?);
279                    path.cmds.push(PathCmd::CubicTo(c1, c2, p));
280                    last_cubic = Some(c2);
281                    last_quad = None;
282                    cur = p;
283                }
284                b'S' => {
285                    let c1 = last_cubic.map_or(cur, |c| pt(2.0 * cur.x - c.x, 2.0 * cur.y - c.y));
286                    let c2 = pt(base.x + num()?, base.y + num()?);
287                    let p = pt(base.x + num()?, base.y + num()?);
288                    path.cmds.push(PathCmd::CubicTo(c1, c2, p));
289                    last_cubic = Some(c2);
290                    last_quad = None;
291                    cur = p;
292                }
293                b'Q' => {
294                    let c = pt(base.x + num()?, base.y + num()?);
295                    let p = pt(base.x + num()?, base.y + num()?);
296                    path.cmds.push(PathCmd::QuadTo(c, p));
297                    last_quad = Some(c);
298                    last_cubic = None;
299                    cur = p;
300                }
301                b'T' => {
302                    let c = last_quad.map_or(cur, |q| pt(2.0 * cur.x - q.x, 2.0 * cur.y - q.y));
303                    let p = pt(base.x + num()?, base.y + num()?);
304                    path.cmds.push(PathCmd::QuadTo(c, p));
305                    last_quad = Some(c);
306                    last_cubic = None;
307                    cur = p;
308                }
309                b'A' => {
310                    let (rx, ry, rot) = (num()?, num()?, num()?);
311                    let large = tokens.flag()?;
312                    let sweep = tokens.flag()?;
313                    let p = pt(base.x + tokens.number()?, base.y + tokens.number()?);
314                    path.svg_arc(cur, p, rx, ry, rot, large, sweep);
315                    last_cubic = None;
316                    last_quad = None;
317                    cur = p;
318                }
319                b'Z' => {
320                    path.cmds.push(PathCmd::Close);
321                    cur = start;
322                    last_cubic = None;
323                    last_quad = None;
324                }
325                _ => return None,
326            }
327        }
328        Some(path)
329    }
330
331    /// Arco do SVG (por pontas) convertido para o centro e daí para cúbicas.
332    #[allow(clippy::too_many_arguments)]
333    fn svg_arc(&mut self, from: PointF, to: PointF, rx: f32, ry: f32, rotation: f32, large: bool, sweep: bool) {
334        let (mut rx, mut ry) = (rx.abs(), ry.abs());
335        if rx == 0.0 || ry == 0.0 || from == to {
336            self.cmds.push(PathCmd::LineTo(to));
337            return;
338        }
339        let phi = rotation.to_radians();
340        let (sp, cp) = phi.sin_cos();
341        let dx = (from.x - to.x) / 2.0;
342        let dy = (from.y - to.y) / 2.0;
343        let x1 = cp * dx + sp * dy;
344        let y1 = -sp * dx + cp * dy;
345        let lambda = (x1 * x1) / (rx * rx) + (y1 * y1) / (ry * ry);
346        if lambda > 1.0 {
347            rx *= lambda.sqrt();
348            ry *= lambda.sqrt();
349        }
350        let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
351        let den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
352        let mut coef = (num / den).max(0.0).sqrt();
353        if large == sweep {
354            coef = -coef;
355        }
356        let cx1 = coef * rx * y1 / ry;
357        let cy1 = -coef * ry * x1 / rx;
358        let center = pt(cp * cx1 - sp * cy1 + (from.x + to.x) / 2.0, sp * cx1 + cp * cy1 + (from.y + to.y) / 2.0);
359        let angle = |ux: f32, uy: f32, vx: f32, vy: f32| {
360            let a = (ux * vy - uy * vx).atan2(ux * vx + uy * vy);
361            if a.is_nan() { 0.0 } else { a }
362        };
363        let a0 = angle(1.0, 0.0, (x1 - cx1) / rx, (y1 - cy1) / ry);
364        let mut da = angle((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry);
365        let tau = std::f32::consts::TAU;
366        if !sweep && da > 0.0 {
367            da -= tau;
368        } else if sweep && da < 0.0 {
369            da += tau;
370        }
371        self.arc_segments(center, rx, ry, phi, a0, da);
372        // Garante a ponta exata.
373        if let Some(PathCmd::CubicTo(_, _, p)) = self.cmds.last_mut() {
374            *p = to;
375        }
376    }
377
378    /// O mesmo caminho escalado e deslocado (`p * scale + offset`).
379    pub fn transformed(&self, scale: f32, offset: PointF) -> Path {
380        self.map_points(|p| pt(p.x * scale + offset.x, p.y * scale + offset.y))
381    }
382
383    /// Acrescenta as figuras de outro caminho.
384    pub fn append(&mut self, other: &Path) -> &mut Self {
385        self.cmds.extend_from_slice(&other.cmds);
386        self
387    }
388
389    /// O mesmo caminho com cada ponto passado por `f` (uma transformação qualquer).
390    pub fn map_points(&self, f: impl Fn(PointF) -> PointF) -> Path {
391        let cmds = self
392            .cmds
393            .iter()
394            .map(|c| match *c {
395                PathCmd::MoveTo(p) => PathCmd::MoveTo(f(p)),
396                PathCmd::LineTo(p) => PathCmd::LineTo(f(p)),
397                PathCmd::QuadTo(a, p) => PathCmd::QuadTo(f(a), f(p)),
398                PathCmd::CubicTo(a, b, p) => PathCmd::CubicTo(f(a), f(b), f(p)),
399                PathCmd::Close => PathCmd::Close,
400            })
401            .collect();
402        Path { cmds, even_odd: self.even_odd }
403    }
404
405    /// Retângulo que contém todos os pontos (inclusive os de controle).
406    pub fn bounds(&self) -> RectF {
407        let mut min = pt(f32::MAX, f32::MAX);
408        let mut max = pt(f32::MIN, f32::MIN);
409        let mut add = |p: PointF| {
410            min = pt(min.x.min(p.x), min.y.min(p.y));
411            max = pt(max.x.max(p.x), max.y.max(p.y));
412        };
413        for c in &self.cmds {
414            match *c {
415                PathCmd::MoveTo(p) | PathCmd::LineTo(p) => add(p),
416                PathCmd::QuadTo(a, p) => {
417                    add(a);
418                    add(p);
419                }
420                PathCmd::CubicTo(a, b, p) => {
421                    add(a);
422                    add(b);
423                    add(p);
424                }
425                PathCmd::Close => {}
426            }
427        }
428        if min.x > max.x {
429            return RectF::default();
430        }
431        RectF::new(min.x, min.y, max.x - min.x, max.y - min.y)
432    }
433
434    /// As figuras como linhas quebradas (curvas divididas em `segments` retas cada):
435    /// `(pontos, fechada)`. Usado por canvases sem curvas e para testes de clique.
436    pub fn flatten(&self, segments: usize) -> Vec<(Vec<PointF>, bool)> {
437        let segments = segments.max(1);
438        let mut out: Vec<(Vec<PointF>, bool)> = Vec::new();
439        let mut cur: Vec<PointF> = Vec::new();
440        let mut last = pt(0.0, 0.0);
441        for c in &self.cmds {
442            match *c {
443                PathCmd::MoveTo(p) => {
444                    if cur.len() > 1 {
445                        out.push((std::mem::take(&mut cur), false));
446                    }
447                    cur = vec![p];
448                    last = p;
449                }
450                PathCmd::LineTo(p) => {
451                    if cur.is_empty() {
452                        cur.push(last);
453                    }
454                    cur.push(p);
455                    last = p;
456                }
457                PathCmd::QuadTo(a, p) => {
458                    if cur.is_empty() {
459                        cur.push(last);
460                    }
461                    for i in 1..=segments {
462                        let t = i as f32 / segments as f32;
463                        let u = 1.0 - t;
464                        cur.push(pt(u * u * last.x + 2.0 * u * t * a.x + t * t * p.x, u * u * last.y + 2.0 * u * t * a.y + t * t * p.y));
465                    }
466                    last = p;
467                }
468                PathCmd::CubicTo(a, b, p) => {
469                    if cur.is_empty() {
470                        cur.push(last);
471                    }
472                    for i in 1..=segments {
473                        let t = i as f32 / segments as f32;
474                        let u = 1.0 - t;
475                        let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
476                        cur.push(pt(
477                            w0 * last.x + w1 * a.x + w2 * b.x + w3 * p.x,
478                            w0 * last.y + w1 * a.y + w2 * b.y + w3 * p.y,
479                        ));
480                    }
481                    last = p;
482                }
483                PathCmd::Close => {
484                    if let Some(&first) = cur.first() {
485                        last = first;
486                        out.push((std::mem::take(&mut cur), true));
487                    }
488                }
489            }
490        }
491        if cur.len() > 1 {
492            out.push((cur, false));
493        }
494        out
495    }
496
497    /// O caminho como o atributo `d` do SVG (coordenadas absolutas, até 2 casas).
498    pub fn to_svg(&self) -> String {
499        let n = |v: f32| {
500            let t = format!("{:.2}", v);
501            let t = t.trim_end_matches('0').trim_end_matches('.');
502            if t == "-0" { "0".to_string() } else { t.to_string() }
503        };
504        let mut out = String::new();
505        for c in &self.cmds {
506            let part = match *c {
507                PathCmd::MoveTo(p) => format!("M{} {}", n(p.x), n(p.y)),
508                PathCmd::LineTo(p) => format!("L{} {}", n(p.x), n(p.y)),
509                PathCmd::QuadTo(a, p) => format!("Q{} {} {} {}", n(a.x), n(a.y), n(p.x), n(p.y)),
510                PathCmd::CubicTo(a, b, p) => format!("C{} {} {} {} {} {}", n(a.x), n(a.y), n(b.x), n(b.y), n(p.x), n(p.y)),
511                PathCmd::Close => "Z".to_string(),
512            };
513            out.push_str(&part);
514        }
515        out
516    }
517
518    /// O ponto está dentro da área preenchida (regra não zero, a do `fill_path`)? As
519    /// figuras abertas contam como fechadas, como no preenchimento.
520    pub fn contains(&self, p: PointF) -> bool {
521        let mut winding = 0i32;
522        for (points, _) in self.flatten(16) {
523            let n = points.len();
524            if n < 3 {
525                continue;
526            }
527            for i in 0..n {
528                let (a, b) = (points[i], points[(i + 1) % n]);
529                let cross = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
530                if a.y <= p.y {
531                    if b.y > p.y && cross > 0.0 {
532                        winding += 1;
533                    }
534                } else if b.y <= p.y && cross < 0.0 {
535                    winding -= 1;
536                }
537            }
538        }
539        winding != 0
540    }
541
542    /// Distância de um ponto até o caminho (como linha), para clicar em cabos e traços.
543    pub fn distance_to(&self, p: PointF) -> f32 {
544        let mut best = f32::MAX;
545        for (points, closed) in self.flatten(16) {
546            let n = points.len();
547            let count = if closed { n } else { n.saturating_sub(1) };
548            for i in 0..count {
549                let (a, b) = (points[i], points[(i + 1) % n]);
550                best = best.min(segment_distance(p, a, b));
551            }
552        }
553        best
554    }
555}
556
557fn segment_distance(p: PointF, a: PointF, b: PointF) -> f32 {
558    let (dx, dy) = (b.x - a.x, b.y - a.y);
559    let len2 = dx * dx + dy * dy;
560    let t = if len2 == 0.0 { 0.0 } else { (((p.x - a.x) * dx + (p.y - a.y) * dy) / len2).clamp(0.0, 1.0) };
561    let (x, y) = (a.x + t * dx - p.x, a.y + t * dy - p.y);
562    (x * x + y * y).sqrt()
563}
564
565struct SvgTokens<'a> {
566    s: &'a [u8],
567    i: usize,
568}
569
570impl SvgTokens<'_> {
571    fn done(&self) -> bool {
572        self.i >= self.s.len()
573    }
574
575    fn skip_separators(&mut self) {
576        while self.i < self.s.len() && (self.s[self.i].is_ascii_whitespace() || self.s[self.i] == b',') {
577            self.i += 1;
578        }
579    }
580
581    fn command(&mut self) -> Option<u8> {
582        let c = *self.s.get(self.i)?;
583        if c.is_ascii_alphabetic() && c != b'e' && c != b'E' {
584            self.i += 1;
585            Some(c)
586        } else {
587            None
588        }
589    }
590
591    /// Bandeira do arco: `0` ou `1`, que pode vir colada no próximo número.
592    fn flag(&mut self) -> Option<bool> {
593        self.skip_separators();
594        let c = *self.s.get(self.i)?;
595        self.i += 1;
596        match c {
597            b'0' => Some(false),
598            b'1' => Some(true),
599            _ => None,
600        }
601    }
602
603    fn number(&mut self) -> Option<f32> {
604        self.skip_separators();
605        let start = self.i;
606        let s = self.s;
607        if self.i < s.len() && (s[self.i] == b'-' || s[self.i] == b'+') {
608            self.i += 1;
609        }
610        let mut dot = false;
611        while self.i < s.len() {
612            match s[self.i] {
613                b'0'..=b'9' => self.i += 1,
614                b'.' if !dot => {
615                    dot = true;
616                    self.i += 1;
617                }
618                b'e' | b'E' => {
619                    self.i += 1;
620                    if self.i < s.len() && (s[self.i] == b'-' || s[self.i] == b'+') {
621                        self.i += 1;
622                    }
623                }
624                _ => break,
625            }
626        }
627        std::str::from_utf8(&s[start..self.i]).ok()?.parse().ok()
628    }
629}
630
631#[cfg(test)]
632mod tests {
633    use super::*;
634
635    #[test]
636    fn reads_svg_paths() {
637        let p = Path::from_svg("M10 20 L30 20 h10 v-5 Z").unwrap();
638        assert_eq!(p.cmds.len(), 5);
639        assert_eq!(p.current(), Some(pt(10.0, 20.0)), "Z volta ao começo");
640        // pares depois do M são retas; números colados com sinal
641        let p = Path::from_svg("m1 1 2 2-1-1").unwrap();
642        assert_eq!(p.cmds[1], PathCmd::LineTo(pt(3.0, 3.0)));
643        assert_eq!(p.cmds[2], PathCmd::LineTo(pt(2.0, 2.0)));
644        // arco termina no ponto pedido, com bandeiras coladas
645        let p = Path::from_svg("M2 12a10 10 0 1012 0").unwrap();
646        assert_eq!(p.current(), Some(pt(14.0, 12.0)));
647        assert!(Path::from_svg("M1 x").is_none());
648    }
649
650    #[test]
651    fn bounds_and_distance() {
652        let mut p = Path::new();
653        p.rect(RectF::new(0.0, 0.0, 10.0, 10.0), 0.0);
654        assert_eq!(p.bounds(), RectF::new(0.0, 0.0, 10.0, 10.0));
655        assert!(p.distance_to(pt(5.0, 1.0)) < 1.01);
656        assert!(p.distance_to(pt(5.0, 5.0)) > 4.9);
657    }
658
659    #[test]
660    fn every_builtin_icon_parses() {
661        let names = crate::icons::builtin_names();
662        assert!(names.len() > 70);
663        for n in names {
664            let icon = crate::icons::builtin(n).unwrap();
665            assert!(!icon.stroke.is_empty() || !icon.fill.is_empty(), "{n}");
666            let b = icon.stroke.bounds();
667            assert!(b.x >= -1.0 && b.right() <= 25.0, "{n} fora da grade: {b:?}");
668        }
669    }
670}