mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 22:14:30 +00:00
Merge pull request #1602 from storytold/codex/svg-neutral-document
Share streaming SVG primitives and drawing output
This commit is contained in:
Generated
+1
@@ -2711,6 +2711,7 @@ dependencies = [
|
||||
"data-url",
|
||||
"flate2",
|
||||
"kurbo 0.13.1",
|
||||
"quick-xml 0.41.0",
|
||||
"resvg 0.48.1",
|
||||
"roxmltree 0.21.2",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
@@ -12,6 +12,7 @@ workspace = true
|
||||
|
||||
[dependencies]
|
||||
craft-xml = { workspace = true }
|
||||
quick-xml = { version = "0.41", default-features = false }
|
||||
craft-image-codecs = { workspace = true }
|
||||
# SVGZ (gzip), pure-Rust backend.
|
||||
flate2 = { version = "1", default-features = false, features = ["rust_backend"] }
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
//! SVG polyline and triangle path attributes for display-list exporters.
|
||||
use crate::write::num;
|
||||
use std::fmt::{self, Display};
|
||||
|
||||
/// A fixed-precision polyline attribute streamed into an SVG writer.
|
||||
pub struct Points<I> {
|
||||
iter: I,
|
||||
decimals: usize,
|
||||
}
|
||||
/// Format points without allocating an intermediate attribute string. Precision is capped at 32.
|
||||
pub fn points<I: Iterator<Item = [f64; 2]> + Clone>(iter: I, decimals: usize) -> Points<I> {
|
||||
Points { iter, decimals: decimals.min(32) }
|
||||
}
|
||||
impl<I: Iterator<Item = [f64; 2]> + Clone> Display for Points<I> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
for [x, y] in self.iter.clone() {
|
||||
write!(f, "{},{} ", num(x, self.decimals), num(y, self.decimals))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// A fixed-precision sequence of closed triangle subpaths.
|
||||
pub struct Triangles<I> {
|
||||
iter: I,
|
||||
decimals: usize,
|
||||
}
|
||||
/// Format independent triangles without allocating an intermediate attribute string. Precision is capped at 32.
|
||||
pub fn triangles<I: Iterator<Item = [[f64; 2]; 3]> + Clone>(iter: I, decimals: usize) -> Triangles<I> {
|
||||
Triangles { iter, decimals: decimals.min(32) }
|
||||
}
|
||||
impl<I: Iterator<Item = [[f64; 2]; 3]> + Clone> Display for Triangles<I> {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
for [[ax, ay], [bx, by], [cx, cy]] in self.iter.clone() {
|
||||
write!(
|
||||
f,
|
||||
"M{} {}L{} {}L{} {}Z",
|
||||
num(ax, self.decimals),
|
||||
num(ay, self.decimals),
|
||||
num(bx, self.decimals),
|
||||
num(by, self.decimals),
|
||||
num(cx, self.decimals),
|
||||
num(cy, self.decimals)
|
||||
)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn fixed_precision_attributes_keep_independent_triangles() {
|
||||
assert_eq!(points([[1.0, 2.0], [3.0, 4.0]].into_iter(), 2).to_string(), "1.00,2.00 3.00,4.00 ");
|
||||
assert_eq!(triangles([[[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]].into_iter(), 1).to_string(), "M1.0 2.0L3.0 4.0L5.0 6.0Z");
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,10 @@
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
pub mod color;
|
||||
pub mod drawing_write;
|
||||
pub mod guard;
|
||||
pub mod neutral_document;
|
||||
pub mod path_data;
|
||||
pub mod paths;
|
||||
pub mod preflight;
|
||||
pub mod sniff;
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
//! A bounded SVG document walk that preserves geometric primitive kinds for CAD import.
|
||||
//!
|
||||
//! Coordinates remain in SVG user units. Each shape carries the composed transform into
|
||||
//! millimetres with the page Y axis pointing up; consumers map shapes into their own model.
|
||||
use crate::path_data::{self, Point, Subpath};
|
||||
use quick_xml::events::{BytesStart, Event as XmlEvent};
|
||||
use quick_xml::{Reader, XmlVersion};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
const MAX_DEPTH: usize = 64;
|
||||
const MAX_SHAPES: usize = 500_000;
|
||||
const MAX_POINTS: usize = 8_000_000;
|
||||
const MAX_POLY_POINTS: usize = 100_001;
|
||||
const SKIP: &[&[u8]] = &[
|
||||
b"defs",
|
||||
b"symbol",
|
||||
b"clipPath",
|
||||
b"mask",
|
||||
b"pattern",
|
||||
b"marker",
|
||||
b"linearGradient",
|
||||
b"radialGradient",
|
||||
b"filter",
|
||||
b"style",
|
||||
b"text",
|
||||
b"image",
|
||||
b"title",
|
||||
b"desc",
|
||||
b"metadata",
|
||||
];
|
||||
const CONTAINERS: &[&[u8]] = &[b"g", b"svg", b"a", b"switch"];
|
||||
|
||||
/// Input failure or resource bound.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{0}")]
|
||||
pub struct Error(pub String);
|
||||
/// A shape's original geometry before its affine transform.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Primitive {
|
||||
Rect { x: f64, y: f64, width: f64, height: f64 },
|
||||
Circle { center: Point, radius: f64 },
|
||||
Ellipse { center: Point, rx: f64, ry: f64 },
|
||||
Line { a: Point, b: Point },
|
||||
Polyline { points: Vec<Point>, closed: bool },
|
||||
Path(Vec<Subpath>),
|
||||
}
|
||||
/// A primitive with its layer and SVG affine matrix `[a,b,c,d,e,f]`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Shape {
|
||||
pub primitive: Primitive,
|
||||
pub transform: [f64; 6],
|
||||
pub layer: String,
|
||||
}
|
||||
/// The shapes, encountered layer names, and skipped-feature counts. `visit` streams shapes
|
||||
/// to its sink, so its returned `shapes` is empty; `import` collects them.
|
||||
#[derive(Debug, Default, PartialEq)]
|
||||
pub struct Document {
|
||||
pub shapes: Vec<Shape>,
|
||||
pub layers: Vec<String>,
|
||||
pub skipped: BTreeMap<Skipped, usize>,
|
||||
}
|
||||
/// Features left out by this geometry-only import.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum Skipped {
|
||||
Text,
|
||||
Image,
|
||||
Use,
|
||||
Style,
|
||||
RoundedCorners,
|
||||
}
|
||||
|
||||
fn attr(e: &BytesStart<'_>, name: &[u8]) -> Option<String> {
|
||||
for a in e.attributes() {
|
||||
let Ok(a) = a else { return None };
|
||||
if a.key.into_inner() == name {
|
||||
return a.normalized_value(XmlVersion::Explicit1_0).ok().map(|v| v.into_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
fn hidden(e: &BytesStart<'_>) -> bool {
|
||||
attr(e, b"display").as_deref() == Some("none") || attr(e, b"style").is_some_and(|s| s.replace(' ', "").contains("display:none"))
|
||||
}
|
||||
fn length(s: &str) -> Option<f64> {
|
||||
let s = s.trim();
|
||||
let cut = s.find(|c: char| !(c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E'))).unwrap_or(s.len());
|
||||
let (n, unit) = s.split_at(cut);
|
||||
let v: f64 = n.trim().parse().ok()?;
|
||||
if !v.is_finite() {
|
||||
return None;
|
||||
}
|
||||
Some(
|
||||
v * match unit.trim() {
|
||||
"" | "px" | "mm" => 1.0,
|
||||
"cm" => 10.0,
|
||||
"in" => 25.4,
|
||||
"pt" => 25.4 / 72.0,
|
||||
"pc" => 25.4 / 6.0,
|
||||
_ => 25.4 / 96.0,
|
||||
},
|
||||
)
|
||||
}
|
||||
fn num(e: &BytesStart<'_>, name: &[u8], default: f64) -> f64 {
|
||||
attr(e, name).as_deref().and_then(length).unwrap_or(default)
|
||||
}
|
||||
const ID: [f64; 6] = [1., 0., 0., 1., 0., 0.];
|
||||
fn mul(a: [f64; 6], b: [f64; 6]) -> [f64; 6] {
|
||||
[
|
||||
a[0] * b[0] + a[2] * b[1],
|
||||
a[1] * b[0] + a[3] * b[1],
|
||||
a[0] * b[2] + a[2] * b[3],
|
||||
a[1] * b[2] + a[3] * b[3],
|
||||
a[0] * b[4] + a[2] * b[5] + a[4],
|
||||
a[1] * b[4] + a[3] * b[5] + a[5],
|
||||
]
|
||||
}
|
||||
fn translate(x: f64, y: f64) -> [f64; 6] {
|
||||
[1., 0., 0., 1., x, y]
|
||||
}
|
||||
fn scale(x: f64, y: f64) -> [f64; 6] {
|
||||
[x, 0., 0., y, 0., 0.]
|
||||
}
|
||||
fn rotate(a: f64) -> [f64; 6] {
|
||||
let (s, c) = a.to_radians().sin_cos();
|
||||
[c, s, -s, c, 0., 0.]
|
||||
}
|
||||
fn numbers(s: &str) -> impl Iterator<Item = f64> + '_ {
|
||||
path_data::Numbers::new(s)
|
||||
}
|
||||
fn transform(s: &str) -> Option<[f64; 6]> {
|
||||
let mut out = None;
|
||||
let mut rest = s.trim();
|
||||
while !rest.is_empty() {
|
||||
let open = rest.find('(')?;
|
||||
let name = rest[..open].trim();
|
||||
let close = rest[open..].find(')')? + open;
|
||||
// No transform function accepts more than six arguments.
|
||||
let args: Vec<_> = numbers(&rest[open + 1..close]).take(7).collect();
|
||||
let m = match (name, args.as_slice()) {
|
||||
("matrix", [a, b, c, d, e, f]) => [*a, *b, *c, *d, *e, *f],
|
||||
("translate", [x]) => translate(*x, 0.),
|
||||
("translate", [x, y]) => translate(*x, *y),
|
||||
("scale", [x]) => scale(*x, *x),
|
||||
("scale", [x, y]) => scale(*x, *y),
|
||||
("rotate", [a]) => rotate(*a),
|
||||
("rotate", [a, x, y]) => mul(mul(translate(*x, *y), rotate(*a)), translate(-x, -y)),
|
||||
("skewX", [a]) => [1., 0., a.to_radians().tan(), 1., 0., 0.],
|
||||
("skewY", [a]) => [1., a.to_radians().tan(), 0., 1., 0., 0.],
|
||||
_ => return None,
|
||||
};
|
||||
out = Some(out.map_or(m, |prev| mul(prev, m)));
|
||||
rest = rest[close + 1..].trim_start_matches(|c: char| c == ',' || c.is_whitespace());
|
||||
}
|
||||
out
|
||||
}
|
||||
fn viewport(e: &BytesStart<'_>) -> [f64; 6] {
|
||||
let vb = attr(e, b"viewBox").and_then(|raw| {
|
||||
let n: Vec<_> = numbers(&raw).take(5).collect();
|
||||
match n.as_slice() {
|
||||
[x, y, w, h] if *w > 0. && *h > 0. => Some((*x, *y, *w, *h)),
|
||||
_ => None,
|
||||
}
|
||||
});
|
||||
let root = |name: &[u8]| {
|
||||
let raw = attr(e, name)?;
|
||||
let mm = length(&raw)?;
|
||||
let unit = raw.trim().trim_start_matches(|c: char| c.is_ascii_digit() || matches!(c, '.' | '-' | '+' | 'e' | 'E')).trim();
|
||||
Some(if matches!(unit, "" | "px") { mm * 25.4 / 96. } else { mm })
|
||||
};
|
||||
let unit = match (vb, root(b"width"), root(b"height")) {
|
||||
(Some((_, _, w, _)), Some(x), _) if x > 0. => x / w,
|
||||
(Some((_, _, _, h)), _, Some(y)) if y > 0. => y / h,
|
||||
_ => 25.4 / 96.,
|
||||
};
|
||||
let (x, y, h) = vb.map_or((0., 0., 0.), |(x, y, _, h)| (x, y, h));
|
||||
[unit, 0., 0., -unit, -x * unit, (y + h) * unit]
|
||||
}
|
||||
fn layer_name(raw: &str) -> String {
|
||||
let s: String = raw.trim().chars().map(|c| if c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '$') { c } else { '_' }).take(128).collect();
|
||||
let s = s.trim_matches('_');
|
||||
if s.is_empty() { "SVG".into() } else { s.into() }
|
||||
}
|
||||
/// A layer declaration or a drawable primitive in document order.
|
||||
pub enum Event {
|
||||
Layer(String),
|
||||
Shape(Shape),
|
||||
}
|
||||
|
||||
struct Walker<'a> {
|
||||
doc: Document,
|
||||
stack: Vec<[f64; 6]>,
|
||||
layer: String,
|
||||
skip: usize,
|
||||
points: usize,
|
||||
shapes: usize,
|
||||
sink: &'a mut dyn FnMut(Event) -> Result<(), Error>,
|
||||
}
|
||||
impl Walker<'_> {
|
||||
fn current(&self) -> [f64; 6] {
|
||||
self.stack.last().copied().unwrap_or(ID)
|
||||
}
|
||||
fn note(&mut self, what: Skipped) {
|
||||
*self.doc.skipped.entry(what).or_default() += 1;
|
||||
}
|
||||
fn skipped(name: &[u8]) -> Option<Skipped> {
|
||||
match name {
|
||||
b"text" => Some(Skipped::Text),
|
||||
b"image" => Some(Skipped::Image),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
fn start(&mut self, name: &[u8], e: &BytesStart<'_>) -> Result<(), Error> {
|
||||
if name == b"style" {
|
||||
self.note(Skipped::Style);
|
||||
}
|
||||
if self.skip > 0 {
|
||||
self.skip += 1;
|
||||
return Ok(());
|
||||
}
|
||||
if hidden(e) {
|
||||
self.skip = 1;
|
||||
return Ok(());
|
||||
}
|
||||
if SKIP.contains(&name) {
|
||||
if let Some(s) = Self::skipped(name) {
|
||||
self.note(s);
|
||||
}
|
||||
self.skip = 1;
|
||||
return Ok(());
|
||||
}
|
||||
if !CONTAINERS.contains(&name) {
|
||||
return self.element(name, e);
|
||||
}
|
||||
if name == b"svg"
|
||||
&& self.stack.len() == 1
|
||||
&& let Some(root) = self.stack.first_mut()
|
||||
{
|
||||
*root = viewport(e);
|
||||
}
|
||||
if name == b"g"
|
||||
&& attr(e, b"inkscape:groupmode").as_deref() == Some("layer")
|
||||
&& let Some(raw) = attr(e, b"inkscape:label").or_else(|| attr(e, b"id"))
|
||||
{
|
||||
let layer = layer_name(&raw);
|
||||
if layer == "0" || self.doc.layers.contains(&layer) {
|
||||
self.layer = layer;
|
||||
} else if self.doc.layers.len() < 255 {
|
||||
self.doc.layers.push(layer.clone());
|
||||
(self.sink)(Event::Layer(layer.clone()))?;
|
||||
self.layer = layer;
|
||||
}
|
||||
}
|
||||
if self.stack.len() >= MAX_DEPTH {
|
||||
return Err(Error(format!("SVG: more than {MAX_DEPTH} nested groups")));
|
||||
}
|
||||
let next = attr(e, b"transform").as_deref().and_then(transform).map_or(self.current(), |t| mul(self.current(), t));
|
||||
self.stack.push(next);
|
||||
Ok(())
|
||||
}
|
||||
fn element(&mut self, name: &[u8], e: &BytesStart<'_>) -> Result<(), Error> {
|
||||
if self.skip > 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if SKIP.contains(&name) || hidden(e) {
|
||||
if !hidden(e)
|
||||
&& let Some(s) = Self::skipped(name)
|
||||
{
|
||||
self.note(s);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let p = |x, y| Point::new(num(e, x, 0.), num(e, y, 0.));
|
||||
let primitive = match name {
|
||||
b"use" => {
|
||||
self.note(Skipped::Use);
|
||||
return Ok(());
|
||||
}
|
||||
b"rect" => {
|
||||
let (x, y, w, h) = (num(e, b"x", 0.), num(e, b"y", 0.), num(e, b"width", 0.), num(e, b"height", 0.));
|
||||
if w <= 0. || h <= 0. {
|
||||
return Ok(());
|
||||
}
|
||||
if num(e, b"rx", 0.) > 0. || num(e, b"ry", 0.) > 0. {
|
||||
self.note(Skipped::RoundedCorners);
|
||||
}
|
||||
Primitive::Rect { x, y, width: w, height: h }
|
||||
}
|
||||
b"circle" => {
|
||||
let r = num(e, b"r", 0.);
|
||||
if r <= 0. {
|
||||
return Ok(());
|
||||
}
|
||||
Primitive::Circle { center: p(b"cx", b"cy"), radius: r }
|
||||
}
|
||||
b"ellipse" => {
|
||||
let (rx, ry) = (num(e, b"rx", 0.), num(e, b"ry", 0.));
|
||||
if rx <= 0. || ry <= 0. {
|
||||
return Ok(());
|
||||
}
|
||||
Primitive::Ellipse { center: p(b"cx", b"cy"), rx, ry }
|
||||
}
|
||||
b"line" => Primitive::Line { a: p(b"x1", b"y1"), b: p(b"x2", b"y2") },
|
||||
b"polyline" | b"polygon" => {
|
||||
let Some(raw) = attr(e, b"points") else { return Ok(()) };
|
||||
let n: Vec<_> = numbers(&raw).take(MAX_POLY_POINTS * 2).collect();
|
||||
let pts: Vec<_> = n.as_chunks::<2>().0.iter().map(|[x, y]| Point::new(*x, *y)).collect();
|
||||
if pts.len() < 2 {
|
||||
return Ok(());
|
||||
}
|
||||
Primitive::Polyline { points: pts, closed: name == b"polygon" }
|
||||
}
|
||||
b"path" => {
|
||||
let Some(raw) = attr(e, b"d") else { return Ok(()) };
|
||||
Primitive::Path(path_data::parse_path(&raw).map_err(|e| Error(e.to_string()))?)
|
||||
}
|
||||
_ => return Ok(()),
|
||||
};
|
||||
let cost = match &primitive {
|
||||
Primitive::Polyline { points, .. } => points.len(),
|
||||
Primitive::Path(paths) => paths.iter().map(|p| p.segs.len()).sum(),
|
||||
_ => 1,
|
||||
};
|
||||
self.points = self.points.checked_add(cost).filter(|n| *n <= MAX_POINTS).ok_or_else(|| Error("SVG: too much generated geometry".into()))?;
|
||||
if self.shapes >= MAX_SHAPES {
|
||||
return Err(Error(format!("SVG: more than {MAX_SHAPES} elements")));
|
||||
}
|
||||
let matrix = attr(e, b"transform").as_deref().and_then(transform).map_or(self.current(), |t| mul(self.current(), t));
|
||||
self.shapes += 1;
|
||||
(self.sink)(Event::Shape(Shape { primitive, transform: matrix, layer: self.layer.clone() }))
|
||||
}
|
||||
}
|
||||
/// Walk supported SVG geometry without retaining a second copy of the document's shapes.
|
||||
/// The sink receives each layer before its first shape and each shape in input order.
|
||||
pub fn visit(text: &str, sink: &mut dyn FnMut(Event) -> Result<(), Error>) -> Result<Document, Error> {
|
||||
let mut walker = Walker { doc: Document::default(), stack: vec![ID], layer: "0".into(), skip: 0, points: 0, shapes: 0, sink };
|
||||
let mut reader = Reader::from_str(text);
|
||||
reader.config_mut().trim_text(true);
|
||||
loop {
|
||||
match reader.read_event().map_err(|e| Error(format!("SVG: {e}")))? {
|
||||
XmlEvent::Start(e) => walker.start(e.name().into_inner(), &e)?,
|
||||
XmlEvent::Empty(e) => walker.element(e.name().into_inner(), &e)?,
|
||||
XmlEvent::End(e) => {
|
||||
if walker.skip > 0 {
|
||||
walker.skip -= 1;
|
||||
} else if CONTAINERS.contains(&e.name().into_inner()) && walker.stack.len() > 1 {
|
||||
walker.stack.pop();
|
||||
}
|
||||
}
|
||||
XmlEvent::Eof => break,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(walker.doc)
|
||||
}
|
||||
/// Read the supported geometry into an owned document.
|
||||
pub fn import(text: &str) -> Result<Document, Error> {
|
||||
let mut shapes = Vec::new();
|
||||
let mut doc = visit(text, &mut |event| {
|
||||
if let Event::Shape(shape) = event {
|
||||
shapes.push(shape);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
doc.shapes = shapes;
|
||||
Ok(doc)
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn keeps_primitives_transform_layers_and_skips() {
|
||||
let svg = r##"<svg width="20mm" height="10mm" viewBox="0 0 20 10"><g inkscape:groupmode="layer" inkscape:label="cut" transform="translate(2,1)"><circle cx="3" cy="4" r="2"/><ellipse cx="1" cy="2" rx="3" ry="1"/><path d="M0 0 A1 1 0 011 1"/></g><text>x</text><use href="#x"/></svg>"##;
|
||||
let d = import(svg).unwrap();
|
||||
assert_eq!(d.layers, ["cut"]);
|
||||
assert_eq!(d.shapes.len(), 3);
|
||||
assert_eq!(d.shapes[0].primitive, Primitive::Circle { center: Point::new(3., 4.), radius: 2. });
|
||||
assert_eq!(d.shapes[0].transform, [1., 0., 0., -1., 2., 9.]);
|
||||
assert!(matches!(d.shapes[1].primitive, Primitive::Ellipse { .. }));
|
||||
assert!(matches!(&d.shapes[2].primitive,Primitive::Path(p) if matches!(p[0].segs[0],path_data::Segment::Arc { .. })));
|
||||
assert_eq!(d.skipped.get(&Skipped::Text), Some(&1));
|
||||
assert_eq!(d.skipped.get(&Skipped::Use), Some(&1));
|
||||
}
|
||||
#[test]
|
||||
fn streaming_delivers_layers_before_shapes_and_stops_on_error() {
|
||||
let s = r#"<svg><g inkscape:groupmode="layer" inkscape:label="cut"><circle r="1"/><circle r="2"/></g></svg>"#;
|
||||
let mut events = Vec::new();
|
||||
let result = visit(s, &mut |event| {
|
||||
match event {
|
||||
Event::Layer(name) => events.push(name),
|
||||
Event::Shape(_) => {
|
||||
events.push("shape".into());
|
||||
return Err(Error("stop".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
assert!(result.is_err());
|
||||
assert_eq!(events, ["cut", "shape"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_excessive_nesting() {
|
||||
let s = format!("<svg>{}{}</svg>", "<g>".repeat(100), "</g>".repeat(100));
|
||||
assert!(import(&s).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
//! SVG path data as neutral line, cubic and elliptical arc segments.
|
||||
//!
|
||||
//! Relative commands and smooth controls are resolved, while arcs remain arcs.
|
||||
//! The caller chooses how to map the result to its own geometry model.
|
||||
use std::ops::{Add, Mul, Sub};
|
||||
|
||||
/// A point in the path's original user coordinate system.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Point {
|
||||
/// Horizontal coordinate.
|
||||
pub x: f64,
|
||||
/// Vertical coordinate.
|
||||
pub y: f64,
|
||||
}
|
||||
impl Point {
|
||||
/// The origin.
|
||||
pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
|
||||
/// Construct a point.
|
||||
pub const fn new(x: f64, y: f64) -> Self {
|
||||
Self { x, y }
|
||||
}
|
||||
}
|
||||
impl Add for Point {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self {
|
||||
Self::new(self.x + rhs.x, self.y + rhs.y)
|
||||
}
|
||||
}
|
||||
impl Sub for Point {
|
||||
type Output = Self;
|
||||
fn sub(self, rhs: Self) -> Self {
|
||||
Self::new(self.x - rhs.x, self.y - rhs.y)
|
||||
}
|
||||
}
|
||||
impl Mul<f64> for Point {
|
||||
type Output = Self;
|
||||
fn mul(self, rhs: f64) -> Self {
|
||||
Self::new(self.x * rhs, self.y * rhs)
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalid or oversized path data.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
#[error("{0}")]
|
||||
pub struct Error(pub String);
|
||||
type Result<T> = std::result::Result<T, Error>;
|
||||
const MAX_PATH_SEGMENTS: usize = 100_000;
|
||||
const MAX_CURVE_POINTS: usize = 100_001;
|
||||
|
||||
pub(crate) struct Numbers<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
}
|
||||
|
||||
impl<'a> Numbers<'a> {
|
||||
pub(crate) fn new(s: &'a str) -> Self {
|
||||
Self { s: s.as_bytes(), i: 0 }
|
||||
}
|
||||
fn skip_seps(&mut self) {
|
||||
while matches!(self.s.get(self.i), Some(b' ' | b'\t' | b'\r' | b'\n' | b',')) {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn next_num(&mut self) -> Option<f64> {
|
||||
self.skip_seps();
|
||||
let start = self.i;
|
||||
if matches!(self.s.get(self.i), Some(b'+' | b'-')) {
|
||||
self.i += 1;
|
||||
}
|
||||
let mut digits = 0;
|
||||
let mut dot = false;
|
||||
let mut exp = false;
|
||||
while let Some(c) = self.s.get(self.i) {
|
||||
match c {
|
||||
b'0'..=b'9' => {
|
||||
digits += 1;
|
||||
self.i += 1;
|
||||
}
|
||||
b'.' if !dot && !exp => {
|
||||
dot = true;
|
||||
self.i += 1;
|
||||
}
|
||||
b'e' | b'E' if !exp && digits > 0 => {
|
||||
exp = true;
|
||||
self.i += 1;
|
||||
if matches!(self.s.get(self.i), Some(b'+' | b'-')) {
|
||||
self.i += 1;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
if digits == 0 {
|
||||
self.i = start;
|
||||
return None;
|
||||
}
|
||||
std::str::from_utf8(&self.s[start..self.i]).ok()?.parse::<f64>().ok().filter(|v| v.is_finite())
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for Numbers<'_> {
|
||||
type Item = f64;
|
||||
fn next(&mut self) -> Option<f64> {
|
||||
self.next_num()
|
||||
}
|
||||
}
|
||||
|
||||
/// One `M …` run of a `d` attribute.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Subpath {
|
||||
/// Start point.
|
||||
pub start: Point,
|
||||
/// Segments in drawing order.
|
||||
pub segs: Vec<Segment>,
|
||||
/// Whether a close-path command closed this subpath.
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// A path segment; arc values retain the SVG endpoint parameterization.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Segment {
|
||||
Line(Point),
|
||||
Cubic(Point, Point, Point),
|
||||
Arc { rx: f64, ry: f64, rot: f64, large: bool, sweep: bool, end: Point },
|
||||
}
|
||||
|
||||
/// Tokens of a `d` attribute: command letters and numbers, in order.
|
||||
enum Tok {
|
||||
Cmd(u8),
|
||||
Num(f64),
|
||||
}
|
||||
|
||||
struct Tokenizer<'a> {
|
||||
s: &'a [u8],
|
||||
i: usize,
|
||||
/// Start of the most recently returned token.
|
||||
tok_start: usize,
|
||||
}
|
||||
|
||||
impl<'a> Tokenizer<'a> {
|
||||
fn new(s: &'a str) -> Self {
|
||||
Tokenizer { s: s.as_bytes(), i: 0, tok_start: 0 }
|
||||
}
|
||||
|
||||
/// Read an arc flag: a single `0` or `1` character, which needs no separator after it.
|
||||
fn next_flag(&mut self) -> Option<f64> {
|
||||
let mut nums = Numbers { s: self.s, i: self.i };
|
||||
nums.skip_seps();
|
||||
let v = match self.s.get(nums.i)? {
|
||||
b'0' => 0.0,
|
||||
b'1' => 1.0,
|
||||
_ => return None,
|
||||
};
|
||||
self.i = nums.i + 1;
|
||||
Some(v)
|
||||
}
|
||||
|
||||
fn next_tok(&mut self) -> Option<Tok> {
|
||||
let mut nums = Numbers { s: self.s, i: self.i };
|
||||
nums.skip_seps();
|
||||
self.i = nums.i;
|
||||
self.tok_start = self.i;
|
||||
let c = self.s.get(self.i).copied()?;
|
||||
if c.is_ascii_alphabetic() {
|
||||
self.i += 1;
|
||||
return Some(Tok::Cmd(c));
|
||||
}
|
||||
let tok = nums.next_num().map(Tok::Num);
|
||||
self.i = nums.i;
|
||||
tok
|
||||
}
|
||||
}
|
||||
|
||||
/// Split `d` into subpaths, resolving relative commands and the S/T control reflections.
|
||||
pub fn parse_path(d: &str) -> Result<Vec<Subpath>> {
|
||||
let mut tk = Tokenizer::new(d);
|
||||
let mut lookahead: Option<Tok> = None;
|
||||
let mut cmd = 0u8;
|
||||
let mut cur = Point::ZERO;
|
||||
let mut start = Point::ZERO;
|
||||
let mut segs: Vec<Segment> = Vec::new();
|
||||
let mut out: Vec<Subpath> = Vec::new();
|
||||
let closed = false;
|
||||
let mut prev_cubic: Option<Point> = None;
|
||||
let mut prev_quad: Option<Point> = None;
|
||||
let mut segments = 0usize;
|
||||
|
||||
let next_num = |tk: &mut Tokenizer, look: &mut Option<Tok>| -> Result<f64> {
|
||||
match look.take() {
|
||||
Some(Tok::Num(v)) => Ok(v),
|
||||
Some(other @ Tok::Cmd(_)) => {
|
||||
*look = Some(other);
|
||||
Err(Error("SVG: path command is missing coordinates".into()))
|
||||
}
|
||||
None => match tk.next_tok() {
|
||||
Some(Tok::Num(v)) => Ok(v),
|
||||
Some(other @ Tok::Cmd(_)) => {
|
||||
*look = Some(other);
|
||||
Err(Error("SVG: path command is missing coordinates".into()))
|
||||
}
|
||||
None => Err(Error("SVG: path command is missing coordinates".into())),
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
while let Some(tok) = lookahead.take().or_else(|| tk.next_tok()) {
|
||||
let rel = match tok {
|
||||
Tok::Cmd(c) => {
|
||||
if c.eq_ignore_ascii_case(&b'z') {
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed: true });
|
||||
segs = Vec::new();
|
||||
}
|
||||
cur = start;
|
||||
cmd = 0;
|
||||
continue;
|
||||
}
|
||||
cmd = c;
|
||||
c.is_ascii_lowercase()
|
||||
}
|
||||
tok @ Tok::Num(_) => {
|
||||
if cmd == 0 {
|
||||
return Err(Error("SVG: path data does not start with a command".into()));
|
||||
}
|
||||
lookahead = Some(tok);
|
||||
cmd.is_ascii_lowercase()
|
||||
}
|
||||
};
|
||||
let abs = cmd.to_ascii_uppercase();
|
||||
let count = match abs {
|
||||
b'M' | b'L' | b'T' => 2,
|
||||
b'H' | b'V' => 1,
|
||||
b'C' => 6,
|
||||
b'S' | b'Q' => 4,
|
||||
b'A' => 7,
|
||||
_ => return Err(Error(format!("SVG: unknown path command `{}`", cmd as char))),
|
||||
};
|
||||
let mut args = [0.0f64; 7];
|
||||
for (idx, slot) in args.iter_mut().enumerate().take(count) {
|
||||
if abs == b'A' && (idx == 3 || idx == 4) {
|
||||
// Flags are single characters; re-scan a pending number token from its start.
|
||||
if matches!(lookahead, Some(Tok::Num(_))) {
|
||||
lookahead = None;
|
||||
tk.i = tk.tok_start;
|
||||
}
|
||||
if lookahead.is_none() {
|
||||
*slot = tk.next_flag().ok_or_else(|| Error("SVG: path command is missing coordinates".into()))?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
*slot = next_num(&mut tk, &mut lookahead)?;
|
||||
}
|
||||
let point = |x: f64, y: f64| if rel { cur + Point::new(x, y) } else { Point::new(x, y) };
|
||||
match abs {
|
||||
b'M' => {
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed: false });
|
||||
segs = Vec::new();
|
||||
}
|
||||
cur = point(args[0], args[1]);
|
||||
start = cur;
|
||||
cmd = if rel { b'l' } else { b'L' };
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'L' => {
|
||||
cur = point(args[0], args[1]);
|
||||
segs.push(Segment::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'H' => {
|
||||
cur = Point::new(if rel { cur.x + args[0] } else { args[0] }, cur.y);
|
||||
segs.push(Segment::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'V' => {
|
||||
cur = Point::new(cur.x, if rel { cur.y + args[0] } else { args[0] });
|
||||
segs.push(Segment::Line(cur));
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
b'C' => {
|
||||
let (c1, c2, p) = (point(args[0], args[1]), point(args[2], args[3]), point(args[4], args[5]));
|
||||
segs.push(Segment::Cubic(c1, c2, p));
|
||||
prev_cubic = Some(c2);
|
||||
prev_quad = None;
|
||||
cur = p;
|
||||
}
|
||||
b'S' => {
|
||||
let c1 = prev_cubic.map_or(cur, |c2| cur * 2.0 - c2);
|
||||
let (c2, p) = (point(args[0], args[1]), point(args[2], args[3]));
|
||||
segs.push(Segment::Cubic(c1, c2, p));
|
||||
prev_cubic = Some(c2);
|
||||
prev_quad = None;
|
||||
cur = p;
|
||||
}
|
||||
b'Q' => {
|
||||
let (q, p) = (point(args[0], args[1]), point(args[2], args[3]));
|
||||
segs.push(Segment::Cubic(cur + (q - cur) * (2.0 / 3.0), p + (q - p) * (2.0 / 3.0), p));
|
||||
prev_quad = Some(q);
|
||||
prev_cubic = None;
|
||||
cur = p;
|
||||
}
|
||||
b'T' => {
|
||||
let reflect = prev_quad.map_or(cur, |q| cur * 2.0 - q);
|
||||
let p = point(args[0], args[1]);
|
||||
segs.push(Segment::Cubic(cur + (reflect - cur) * (2.0 / 3.0), p + (reflect - p) * (2.0 / 3.0), p));
|
||||
prev_quad = Some(reflect);
|
||||
prev_cubic = None;
|
||||
cur = p;
|
||||
}
|
||||
b'A' => {
|
||||
let end = point(args[5], args[6]);
|
||||
segs.push(Segment::Arc { rx: args[0].abs(), ry: args[1].abs(), rot: args[2], large: args[3] != 0.0, sweep: args[4] != 0.0, end });
|
||||
cur = end;
|
||||
prev_cubic = None;
|
||||
prev_quad = None;
|
||||
}
|
||||
_ => return Err(Error("SVG: unsupported path command".into())),
|
||||
}
|
||||
segments += 1;
|
||||
if segments > MAX_PATH_SEGMENTS {
|
||||
return Err(Error("SVG: path has too many segments".into()));
|
||||
}
|
||||
if segs.len() > MAX_CURVE_POINTS {
|
||||
return Err(Error("SVG: path has too many segments".into()));
|
||||
}
|
||||
}
|
||||
if !segs.is_empty() {
|
||||
out.push(Subpath { start, segs, closed });
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// The centre and signed sweep of a circular arc from `p0` to `p1` in a Y-up frame, per the
|
||||
/// SVG endpoint parameterisation (F.6.5). Radii that cannot span the chord are scaled up,
|
||||
/// as the specification requires.
|
||||
pub fn arc_center_circular(p0: Point, p1: Point, r: f64, large: bool, sweep: bool) -> Option<(Point, f64)> {
|
||||
if r <= 0.0 || !r.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let d = p1 - p0;
|
||||
let dist = d.x.hypot(d.y);
|
||||
let r = if dist > 2.0 * r { dist / 2.0 } else { r };
|
||||
if dist <= f64::EPSILON {
|
||||
return None;
|
||||
}
|
||||
let mid = (p0 + p1) * 0.5;
|
||||
let h = (r * r - (dist * dist) / 4.0).max(0.0).sqrt();
|
||||
let n = Point::new(-d.y / dist, d.x / dist);
|
||||
let sign = if large != sweep { 1.0 } else { -1.0 };
|
||||
let center = mid + n * (h * sign);
|
||||
let a0 = (p0.y - center.y).atan2(p0.x - center.x);
|
||||
let a1 = (p1.y - center.y).atan2(p1.x - center.x);
|
||||
let ccw = (a1 - a0).rem_euclid(std::f64::consts::TAU);
|
||||
Some((center, pick_sweep(ccw, large, sweep)))
|
||||
}
|
||||
|
||||
/// The signed sweep (CCW positive) for a chord sweep `ccw` in `[0, 2π)`: the centre is
|
||||
/// already chosen so that the magnitude matches `large`, so only the direction is left.
|
||||
fn pick_sweep(ccw: f64, large: bool, sweep: bool) -> f64 {
|
||||
let tau = std::f64::consts::TAU;
|
||||
let eps = f64::EPSILON;
|
||||
if sweep {
|
||||
if ccw <= eps { if large { tau } else { eps } } else { ccw }
|
||||
} else if ccw >= tau - eps {
|
||||
if large { -tau } else { -eps }
|
||||
} else {
|
||||
ccw - tau
|
||||
}
|
||||
}
|
||||
|
||||
/// Endpoint → centre parameterisation for a rotated elliptical arc (SVG F.6.5), in the
|
||||
/// frame the points are given in. Returns the centre, the start parameter and the signed
|
||||
/// sweep.
|
||||
pub fn elliptical_params(p0: Point, p1: Point, rx: f64, ry: f64, phi: f64, large: bool, sweep: bool) -> Option<(Point, f64, f64)> {
|
||||
if rx <= 0.0 || ry <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let (sphi, cphi) = phi.sin_cos();
|
||||
let dx = (p0.x - p1.x) / 2.0;
|
||||
let dy = (p0.y - p1.y) / 2.0;
|
||||
let x1 = cphi * dx + sphi * dy;
|
||||
let y1 = -sphi * dx + cphi * dy;
|
||||
let (rx, ry) = {
|
||||
let lambda = x1 * x1 / (rx * rx) + y1 * y1 / (ry * ry);
|
||||
if lambda > 1.0 {
|
||||
let s = lambda.sqrt();
|
||||
(rx * s, ry * s)
|
||||
} else {
|
||||
(rx, ry)
|
||||
}
|
||||
};
|
||||
let num = rx * rx * ry * ry - rx * rx * y1 * y1 - ry * ry * x1 * x1;
|
||||
let den = rx * rx * y1 * y1 + ry * ry * x1 * x1;
|
||||
let coef = if sweep != large { 1.0 } else { -1.0 } * (num.max(0.0) / den.max(f64::MIN_POSITIVE)).sqrt();
|
||||
let cxp = coef * rx * y1 / ry;
|
||||
let cyp = -coef * ry * x1 / rx;
|
||||
let center = Point::new(cphi * cxp - sphi * cyp + (p0.x + p1.x) / 2.0, sphi * cxp + cphi * cyp + (p0.y + p1.y) / 2.0);
|
||||
let angle = |ux: f64, uy: f64, vx: f64, vy: f64| {
|
||||
let dot = ux * vx + uy * vy;
|
||||
let det = ux * vy - uy * vx;
|
||||
let denom = (ux.hypot(uy) * vx.hypot(vy)).max(f64::MIN_POSITIVE);
|
||||
(dot / denom).clamp(-1.0, 1.0).acos().copysign(det)
|
||||
};
|
||||
let (ux, uy) = ((x1 - cxp) / rx, (y1 - cyp) / ry);
|
||||
let (vx, vy) = ((-x1 - cxp) / rx, (-y1 - cyp) / ry);
|
||||
let theta = angle(1.0, 0.0, ux, uy);
|
||||
let ccw = angle(ux, uy, vx, vy).rem_euclid(std::f64::consts::TAU);
|
||||
Some((center, theta, pick_sweep(ccw, large, sweep)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn resolves_relative_and_smooth_commands_without_flattening_arcs() {
|
||||
let paths = parse_path("M1 2 l3 4 C5 6 7 8 9 10 s2 3 4 5 A6 7 30 0110 12 z").unwrap();
|
||||
assert_eq!(paths.len(), 1);
|
||||
assert!(paths[0].closed);
|
||||
assert_eq!(paths[0].start, Point::new(1.0, 2.0));
|
||||
assert_eq!(paths[0].segs[0], Segment::Line(Point::new(4.0, 6.0)));
|
||||
assert_eq!(paths[0].segs[2], Segment::Cubic(Point::new(11.0, 12.0), Point::new(11.0, 13.0), Point::new(13.0, 15.0)));
|
||||
assert_eq!(paths[0].segs[3], Segment::Arc { rx: 6.0, ry: 7.0, rot: 30.0, large: false, sweep: true, end: Point::new(10.0, 12.0) });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smooth_quadratic_consumes_both_coordinates() {
|
||||
let paths = parse_path("M0 0 Q3 3 6 0 T12 0").unwrap();
|
||||
assert_eq!(paths[0].segs[1], Segment::Cubic(Point::new(8.0, -2.0), Point::new(10.0, -2.0), Point::new(12.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arc_centers_keep_radius_correction_and_sweep() {
|
||||
let (center, delta) = arc_center_circular(Point::new(0.0, 0.0), Point::new(10.0, 0.0), 2.0, false, true).unwrap();
|
||||
assert!((center.x - 5.0).abs() < 1e-10);
|
||||
assert!(center.y.abs() < 1e-10);
|
||||
assert!((delta - std::f64::consts::PI).abs() < 1e-10);
|
||||
let (center, start, sweep) = elliptical_params(Point::new(0.0, 0.0), Point::new(10.0, 0.0), 2.0, 1.0, 0.0, false, true).unwrap();
|
||||
assert!((center.x - 5.0).abs() < 1e-10);
|
||||
assert!(center.y.abs() < 1e-10 && start.is_finite());
|
||||
assert!((sweep - std::f64::consts::PI).abs() < 1e-10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_flags_and_limits_segments() {
|
||||
assert!(parse_path("M0 0 A1 1 0 5 1 2 2").is_err());
|
||||
assert!(parse_path("M0 0 L").is_err());
|
||||
let excessive = format!("M0 0{}", " L1 1".repeat(MAX_PATH_SEGMENTS));
|
||||
assert!(parse_path(&excessive).is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user