Files
Pictor-public/crates/doc/src/path.rs
T

277 lines
9.3 KiB
Rust

//! Path data: the subset of SVG path syntax Pictor writes and reads (M L H V C Q Z, absolute or relative; numbers in
//! plain or exponent form). Parsed into absolute segments; arcs are not accepted (SVG import turns them into curves).
use std::fmt::Write;
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Seg {
Move(f32, f32),
Line(f32, f32),
Quad(f32, f32, f32, f32),
Cubic(f32, f32, f32, f32, f32, f32),
Close,
}
#[derive(Debug, thiserror::Error, PartialEq)]
#[error("path data is not understood at {at}: {why}")]
pub struct PathError {
pub at: usize,
pub why: &'static str,
}
/// The most segments one path may have (a hostile document could otherwise ask for any amount of work).
pub const MAX_SEGMENTS: usize = 200_000;
pub fn parse(d: &str) -> Result<Vec<Seg>, PathError> {
let b = d.as_bytes();
let mut i = 0;
let mut out = Vec::new();
let (mut cx, mut cy, mut sx, mut sy) = (0f32, 0f32, 0f32, 0f32);
let mut cmd = 0u8;
let skip = |i: &mut usize| {
while *i < b.len() && (b[*i].is_ascii_whitespace() || b[*i] == b',') {
*i += 1;
}
};
let num = |i: &mut usize| -> Result<f32, PathError> {
skip(i);
let start = *i;
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
*i += 1;
}
let mut dot = false;
let mut digits = false;
while *i < b.len() && (b[*i].is_ascii_digit() || (b[*i] == b'.' && !dot)) {
if b[*i] == b'.' {
dot = true;
} else {
digits = true;
}
*i += 1;
}
if *i < b.len() && (b[*i] == b'e' || b[*i] == b'E') && digits {
*i += 1;
if *i < b.len() && (b[*i] == b'-' || b[*i] == b'+') {
*i += 1;
}
while *i < b.len() && b[*i].is_ascii_digit() {
*i += 1;
}
}
if !digits {
return Err(PathError { at: start, why: "a number was expected" });
}
let v: f32 = d[start..*i].parse().map_err(|_| PathError { at: start, why: "a number was expected" })?;
if !v.is_finite() {
return Err(PathError { at: start, why: "the number is too large" });
}
Ok(v)
};
loop {
skip(&mut i);
if i >= b.len() {
break;
}
if b[i].is_ascii_alphabetic() {
cmd = b[i];
i += 1;
if cmd == b'Z' || cmd == b'z' {
out.push(Seg::Close);
cx = sx;
cy = sy;
cmd = 0;
continue;
}
} else if cmd == 0 {
return Err(PathError { at: i, why: "a command was expected" });
}
let rel = cmd.is_ascii_lowercase();
let (ox, oy) = if rel { (cx, cy) } else { (0.0, 0.0) };
match cmd.to_ascii_uppercase() {
b'M' => {
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
out.push(Seg::Move(x, y));
(cx, cy, sx, sy) = (x, y, x, y);
cmd = if rel { b'l' } else { b'L' };
}
b'L' => {
let (x, y) = (num(&mut i)? + ox, num(&mut i)? + oy);
out.push(Seg::Line(x, y));
(cx, cy) = (x, y);
}
b'H' => {
let x = num(&mut i)? + ox;
out.push(Seg::Line(x, cy));
cx = x;
}
b'V' => {
let y = num(&mut i)? + oy;
out.push(Seg::Line(cx, y));
cy = y;
}
b'C' => {
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
let s = Seg::Cubic(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy, v[4] + ox, v[5] + oy);
out.push(s);
(cx, cy) = (v[4] + ox, v[5] + oy);
}
b'Q' => {
let v = [num(&mut i)?, num(&mut i)?, num(&mut i)?, num(&mut i)?];
out.push(Seg::Quad(v[0] + ox, v[1] + oy, v[2] + ox, v[3] + oy));
(cx, cy) = (v[2] + ox, v[3] + oy);
}
_ => return Err(PathError { at: i.saturating_sub(1), why: "only M L H V C Q Z are allowed" }),
}
if out.len() > MAX_SEGMENTS {
return Err(PathError { at: i, why: "the path has too many segments" });
}
if !matches!(out.first(), Some(Seg::Move(..))) {
return Err(PathError { at: 0, why: "a path starts with M" });
}
}
Ok(out)
}
/// Writes segments as compact absolute path data.
pub fn write(segs: &[Seg]) -> String {
let mut s = String::new();
let n = |v: f32| -> String {
let r = (v * 1000.0).round() / 1000.0;
if r == r.trunc() { format!("{}", r as i64) } else { format!("{r}") }
};
for seg in segs {
if !s.is_empty() {
s.push(' ');
}
let _ = match *seg {
Seg::Move(x, y) => write!(s, "M{} {}", n(x), n(y)),
Seg::Line(x, y) => write!(s, "L{} {}", n(x), n(y)),
Seg::Quad(a, b, x, y) => write!(s, "Q{} {} {} {}", n(a), n(b), n(x), n(y)),
Seg::Cubic(a, b, c, d, x, y) => write!(s, "C{} {} {} {} {} {}", n(a), n(b), n(c), n(d), n(x), n(y)),
Seg::Close => write!(s, "Z"),
};
}
s
}
/// The control-point box (contains the curve).
pub fn bounds(segs: &[Seg]) -> Option<[f32; 4]> {
let mut b: Option<[f32; 4]> = None;
let mut add = |x: f32, y: f32| {
b = Some(match b {
None => [x, y, x, y],
Some([a, c, d, e]) => [a.min(x), c.min(y), d.max(x), e.max(y)],
})
};
for s in segs {
match *s {
Seg::Move(x, y) | Seg::Line(x, y) => add(x, y),
Seg::Quad(a, c, x, y) => {
add(a, c);
add(x, y)
}
Seg::Cubic(a, c, d, e, x, y) => {
add(a, c);
add(d, e);
add(x, y)
}
Seg::Close => {}
}
}
b
}
pub fn to_skia(segs: &[Seg]) -> Option<tiny_skia::Path> {
let mut pb = tiny_skia::PathBuilder::new();
for s in segs {
match *s {
Seg::Move(x, y) => pb.move_to(x, y),
Seg::Line(x, y) => pb.line_to(x, y),
Seg::Quad(a, b, x, y) => pb.quad_to(a, b, x, y),
Seg::Cubic(a, b, c, d, x, y) => pb.cubic_to(a, b, c, d, x, y),
Seg::Close => pb.close(),
}
}
pb.finish()
}
/// Bézier constant for a quarter circle.
const K: f32 = 0.552_284_8;
pub fn rect(w: f32, h: f32, radius: f32) -> Vec<Seg> {
let r = radius.max(0.0).min(w.abs() / 2.0).min(h.abs() / 2.0);
if r <= 0.0 {
return vec![Seg::Move(0.0, 0.0), Seg::Line(w, 0.0), Seg::Line(w, h), Seg::Line(0.0, h), Seg::Close];
}
let k = r * (1.0 - K);
vec![
Seg::Move(r, 0.0),
Seg::Line(w - r, 0.0),
Seg::Cubic(w - k, 0.0, w, k, w, r),
Seg::Line(w, h - r),
Seg::Cubic(w, h - k, w - k, h, w - r, h),
Seg::Line(r, h),
Seg::Cubic(k, h, 0.0, h - k, 0.0, h - r),
Seg::Line(0.0, r),
Seg::Cubic(0.0, k, k, 0.0, r, 0.0),
Seg::Close,
]
}
pub fn ellipse(w: f32, h: f32) -> Vec<Seg> {
let (rx, ry) = (w / 2.0, h / 2.0);
let (cx, cy) = (rx, ry);
let (kx, ky) = (rx * K, ry * K);
vec![
Seg::Move(cx + rx, cy),
Seg::Cubic(cx + rx, cy + ky, cx + kx, cy + ry, cx, cy + ry),
Seg::Cubic(cx - kx, cy + ry, cx - rx, cy + ky, cx - rx, cy),
Seg::Cubic(cx - rx, cy - ky, cx - kx, cy - ry, cx, cy - ry),
Seg::Cubic(cx + kx, cy - ry, cx + rx, cy - ky, cx + rx, cy),
Seg::Close,
]
}
/// An arrow head at (x2, y2) pointing away from (x1, y1), for a line of width `w`.
pub fn arrow_head(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> Vec<Seg> {
let (dx, dy) = (x2 - x1, y2 - y1);
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
let (ux, uy) = (dx / len, dy / len);
let size = (w * 4.0).max(8.0);
let (bx, by) = (x2 - ux * size, y2 - uy * size);
let (px, py) = (-uy * size * 0.5, ux * size * 0.5);
vec![Seg::Move(x2, y2), Seg::Line(bx + px, by + py), Seg::Line(bx - px, by - py), Seg::Close]
}
/// Where a line meets its arrow head (so the stroke stops under the head instead of poking through its tip).
pub fn shorten(x1: f32, y1: f32, x2: f32, y2: f32, w: f32) -> (f32, f32) {
let (dx, dy) = (x2 - x1, y2 - y1);
let len = (dx * dx + dy * dy).sqrt().max(1e-3);
let size = (w * 4.0).max(8.0) * 0.8;
let t = (size / len).min(1.0);
(x2 - dx * t, y2 - dy * t)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_relative_and_writes_absolute() {
let s = parse("m10 10 l5 0 h5 v-5 c1 1 2 2 3 3 q1 1 2 2 z").unwrap();
assert_eq!(s[0], Seg::Move(10.0, 10.0));
assert_eq!(s[1], Seg::Line(15.0, 10.0));
assert_eq!(s[2], Seg::Line(20.0, 10.0));
assert_eq!(s[3], Seg::Line(20.0, 5.0));
assert_eq!(s[4], Seg::Cubic(21.0, 6.0, 22.0, 7.0, 23.0, 8.0));
assert_eq!(write(&parse(&write(&s)).unwrap()), write(&s));
}
#[test]
fn refuses_arcs_garbage_and_huge_numbers() {
assert!(parse("M0 0 A 5 5 0 0 1 10 10").is_err());
assert!(parse("M0 0 L x 1").is_err());
assert!(parse("L 1 1").is_err());
assert!(parse("M 1e39 0").is_err());
}
}