diff --git a/Cargo.lock b/Cargo.lock index 032e5ead..322f1df1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -401,6 +401,7 @@ dependencies = [ "anicraft-geom", "anicraft-text", "anicraft-xml", + "craft-svg", "thiserror 2.0.21", ] @@ -1380,6 +1381,19 @@ name = "craft-palette" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=de97c35f2b2af01c62371647e57a6affeab456fd#de97c35f2b2af01c62371647e57a6affeab456fd" +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=221efe1b01c6e2d1108204a200f0b094abdffba1#221efe1b01c6e2d1108204a200f0b094abdffba1" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=221efe1b01c6e2d1108204a200f0b094abdffba1)", + "flate2", + "kurbo", + "quick-xml 0.41.0", + "roxmltree", + "thiserror 2.0.21", +] + [[package]] name = "craft-tiff" version = "0.1.0" @@ -1451,6 +1465,16 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=221efe1b01c6e2d1108204a200f0b094abdffba1#221efe1b01c6e2d1108204a200f0b094abdffba1" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + [[package]] name = "craft-xml" version = "0.1.0" @@ -4156,6 +4180,15 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + [[package]] name = "rustc-hash" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 797f2c8c..6396ae98 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ anicraft-audio = { path = "crates/audio" } anicraft-gpu = { path = "crates/gpu" } anicraft-guide = { path = "crates/guide" } craft-anicraft-format = { git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } +craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "221efe1b01c6e2d1108204a200f0b094abdffba1", default-features = false } craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18" } craft-html = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "f0f4758c01581d79577b9bf5046c06f4e77b1f18", default-features = false } craft-audio = { git = "https://github.com/storytold/craft-libs", rev = "e2bf53f2bdba4828e21097774a568ed9c74b0004", default-features = false, features = ["decode", "pcm-encode"] } diff --git a/crates/engine/src/cmds_motion.rs b/crates/engine/src/cmds_motion.rs index de6c0abe..75a52d1a 100644 --- a/crates/engine/src/cmds_motion.rs +++ b/crates/engine/src/cmds_motion.rs @@ -276,7 +276,7 @@ fn set_path(s: &mut Session, p: &Value) -> Result { if d.len() > MAX_PATH_DATA { return Err(EngineError::Param("param 'd' is too long".into())); } - let path = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; + let path = anicraft_svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; let (kf, _) = motion_span(s, p)?; let base = base_of(kf)?; let (start, last) = (kf.start, kf.duration.saturating_sub(1)); diff --git a/crates/engine/src/cmds_path.rs b/crates/engine/src/cmds_path.rs index 32c86369..24a01c68 100644 --- a/crates/engine/src/cmds_path.rs +++ b/crates/engine/src/cmds_path.rs @@ -81,7 +81,7 @@ fn draw_path(s: &mut Session, p: &Value) -> Result { return Err(EngineError::Param("param 'd' is too long".into())); } // Full SVG path data: relative commands, H/V, S/T shorthands and arcs too. - let path = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; + let path = anicraft_svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; add_path(s, "path", path, p) } @@ -305,7 +305,7 @@ fn extend(s: &mut Session, p: &Value) -> Result { if d.len() > 4_000_000 { return Err(EngineError::Param("param 'd' is too long".into())); } - let piece = anicraft_geom::svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; + let piece = anicraft_svg::parse_path_data(d).map_err(|e| EngineError::Param(format!("param 'd': {e}")))?; let at_start = match opt_str(p, "end")?.unwrap_or("end") { "end" => false, "start" => true, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1ca775cd..0d0fe531 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -90,6 +90,7 @@ pub use anicraft_plugins as plugins; pub use anicraft_text as text; pub use anicraft_geom as geom; pub use anicraft_render as render; +pub use anicraft_svg as svg; /// Whether a path is an Animate document (`.fla`, `.xfl`, or an XFL folder) that `file.open` /// imports. pub use cmds_file::is_animate; diff --git a/crates/geom/src/svg.rs b/crates/geom/src/svg.rs index 505d13d5..b94217df 100644 --- a/crates/geom/src/svg.rs +++ b/crates/geom/src/svg.rs @@ -1,93 +1,15 @@ -//! Full SVG path data (SVG 1.1 §8.3 / SVG 2 "paths"): every command in absolute and relative -//! form (M L H V C S Q T A Z), implicit repeats, packed numbers and arc flags. +//! SVG geometry that AniCraft's path model needs: elliptical arcs as cubic Béziers, using the +//! endpoint-to-centre conversion of the SVG implementation notes (W3C SVG 1.1 Appendix F.6, +//! Royalty-Free Patent Policy), at most a quarter turn per cubic. //! -//! [`crate::Path::from_svg`] stays the strict parser for AniCraft's own file format; this one -//! reads SVG written by other tools (icon sets now, SVG import later). Elliptical arcs become -//! cubic Béziers using the endpoint-to-centre conversion of the SVG implementation notes -//! (W3C SVG 1.1 Appendix F.6, Royalty-Free Patent Policy), at most a quarter turn per cubic. -//! Never panics; non-finite numbers and oversized paths are errors. +//! Reading path data (`d`) is craft-svg's job; `anicraft_svg::parse_path_data` maps what it +//! reads onto a [`Path`] with this. [`crate::Path::from_svg`] stays the strict parser for +//! AniCraft's own file format. -use crate::path::MAX_PATH_CMDS; use crate::{Path, Vec2}; -struct Cursor<'a> { - s: &'a [u8], - i: usize, -} - -impl Cursor<'_> { - fn skip(&mut self) { - while self.s.get(self.i).is_some_and(|c| c.is_ascii_whitespace() || *c == b',') { - self.i += 1; - } - } - fn letter(&mut self) -> Option { - self.skip(); - self.s.get(self.i).copied().filter(u8::is_ascii_alphabetic).filter(|c| !matches!(c, b'e' | b'E')) - } - fn number(&mut self) -> Result { - self.skip(); - let start = self.i; - let at = |i: usize| self.s.get(i).copied(); - let mut i = self.i; - if matches!(at(i), Some(b'+' | b'-')) { - i += 1; - } - let mut digits = false; - while at(i).is_some_and(|c| c.is_ascii_digit()) { - i += 1; - digits = true; - } - if at(i) == Some(b'.') { - i += 1; - while at(i).is_some_and(|c| c.is_ascii_digit()) { - i += 1; - digits = true; - } - } - if !digits { - return Err(format!("expected a number at byte {start}")); - } - if matches!(at(i), Some(b'e' | b'E')) { - let mut j = i + 1; - if matches!(at(j), Some(b'+' | b'-')) { - j += 1; - } - if at(j).is_some_and(|c| c.is_ascii_digit()) { - while at(j).is_some_and(|c| c.is_ascii_digit()) { - j += 1; - } - i = j; - } - } - let tok = std::str::from_utf8(self.s.get(start..i).unwrap_or_default()).unwrap_or(""); - let v: f64 = tok.parse().map_err(|_| format!("bad number '{tok}'"))?; - if !v.is_finite() { - return Err(format!("number '{tok}' is not finite")); - } - self.i = i; - Ok(v) - } - /// An arc flag: a single `0` or `1`, which may be packed against the next number. - fn flag(&mut self) -> Result { - self.skip(); - match self.s.get(self.i) { - Some(b'0') => { - self.i += 1; - Ok(false) - } - Some(b'1') => { - self.i += 1; - Ok(true) - } - _ => Err(format!("expected an arc flag (0 or 1) at byte {}", self.i)), - } - } - fn done(&mut self) -> bool { - self.skip(); - self.i >= self.s.len() - } -} +/// Most commands one path may hold. +pub use crate::path::MAX_PATH_CMDS; #[derive(Clone, Copy)] struct P(f64, f64); @@ -98,100 +20,11 @@ impl P { } } -/// Parses SVG path data (`d` attribute) into a [`Path`]. -pub fn parse_path_data(d: &str) -> Result { - let mut c = Cursor { s: d.as_bytes(), i: 0 }; - let mut path = Path::new(); - let (mut cur, mut start) = (P(0.0, 0.0), P(0.0, 0.0)); - // The last control point of a C/S (for S) or Q/T (for T), for reflection. - let (mut last_cubic, mut last_quad): (Option

, Option

) = (None, None); - let mut cmd: Option = None; - while !c.done() { - if let Some(l) = c.letter() { - c.i += 1; - cmd = Some(l); - } - let Some(k) = cmd else { return Err("path data must start with a command".into()) }; - let rel = k.is_ascii_lowercase(); - let off = |p: P, cur: P| if rel { P(p.0 + cur.0, p.1 + cur.1) } else { p }; - let pt = |c: &mut Cursor| -> Result { Ok(P(c.number()?, c.number()?)) }; - let (mut nc, mut nq) = (None, None); - match k.to_ascii_uppercase() { - b'M' => { - let p = off(pt(&mut c)?, cur); - path.move_to(p.v()); - cur = p; - start = p; - // Further pairs after a moveto are linetos. - cmd = Some(if rel { b'l' } else { b'L' }); - } - b'L' => { - cur = off(pt(&mut c)?, cur); - path.line_to(cur.v()); - } - b'H' => { - let x = c.number()?; - cur = P(if rel { cur.0 + x } else { x }, cur.1); - path.line_to(cur.v()); - } - b'V' => { - let y = c.number()?; - cur = P(cur.0, if rel { cur.1 + y } else { y }); - path.line_to(cur.v()); - } - b'C' => { - let (c1, c2, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur), off(pt(&mut c)?, cur)); - path.cubic_to(c1.v(), c2.v(), p.v()); - nc = Some(c2); - cur = p; - } - b'S' => { - let c1 = last_cubic.map_or(cur, |l| P(2.0 * cur.0 - l.0, 2.0 * cur.1 - l.1)); - let (c2, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur)); - path.cubic_to(c1.v(), c2.v(), p.v()); - nc = Some(c2); - cur = p; - } - b'Q' => { - let (q, p) = (off(pt(&mut c)?, cur), off(pt(&mut c)?, cur)); - path.quad_to(q.v(), p.v()); - nq = Some(q); - cur = p; - } - b'T' => { - let q = last_quad.map_or(cur, |l| P(2.0 * cur.0 - l.0, 2.0 * cur.1 - l.1)); - let p = off(pt(&mut c)?, cur); - path.quad_to(q.v(), p.v()); - nq = Some(q); - cur = p; - } - b'A' => { - let (rx, ry, rot) = (c.number()?, c.number()?, c.number()?); - let (large, sweep) = (c.flag()?, c.flag()?); - let p = off(pt(&mut c)?, cur); - arc_to(&mut path, cur, rx, ry, rot, large, sweep, p); - cur = p; - } - b'Z' => { - path.close(); - cur = start; - // Numbers may not follow Z without a new command. - cmd = None; - } - other => return Err(format!("unknown path command '{}'", other as char)), - } - last_cubic = nc; - last_quad = nq; - if path.cmds.len() > MAX_PATH_CMDS { - return Err(format!("path has more than {MAX_PATH_CMDS} commands")); - } - } - Ok(path) -} - -/// Appends the SVG elliptical arc from `p0` to `p1` as cubics (F.6.5 / F.6.6). +/// Appends the SVG elliptical arc from `from` to `to` as cubics (F.6.5 / F.6.6): radii, the +/// x-axis rotation in degrees and the two flags as path data writes them. #[allow(clippy::too_many_arguments)] -fn arc_to(path: &mut Path, p0: P, rx: f64, ry: f64, rot_deg: f64, large: bool, sweep: bool, p1: P) { +pub fn arc_to(path: &mut Path, from: [f64; 2], rx: f64, ry: f64, rot_deg: f64, large: bool, sweep: bool, to: [f64; 2]) { + let (p0, p1) = (P(from[0], from[1]), P(to[0], to[1])); if (p0.0 - p1.0).abs() < 1e-12 && (p0.1 - p1.1).abs() < 1e-12 { return; } @@ -251,52 +84,30 @@ fn arc_to(path: &mut Path, p0: P, rx: f64, ry: f64, rot_deg: f64, large: bool, s #[cfg(test)] mod tests { use super::*; - use crate::PathCmd; - - fn ends(p: &Path) -> Vec { - p.anchors().into_iter().map(|(_, a)| a).collect() - } - - #[test] - fn relative_and_shorthand_commands() { - let p = parse_path_data("m10 10 h5 v5 H10 z m 1,1 l2-2").unwrap(); - assert_eq!(ends(&p), vec![Vec2::new(10.0, 10.0), Vec2::new(15.0, 10.0), Vec2::new(15.0, 15.0), Vec2::new(10.0, 15.0), Vec2::new(11.0, 11.0), Vec2::new(13.0, 9.0)]); - assert!(matches!(p.cmds[4], PathCmd::Close)); - // Implicit lineto after moveto, packed negative numbers. - let q = parse_path_data("M0 0 10 0-5.5.5").unwrap(); - assert_eq!(ends(&q), vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(-5.5, 0.5)]); - // S reflects the previous control point. - let s = parse_path_data("M0 0 C 0 10 10 10 10 0 S 20 -10 20 0").unwrap(); - assert!(matches!(s.cmds[2], PathCmd::CubicTo(c1, _, _) if (c1 - Vec2::new(10.0, -10.0)).length() < 1e-5)); - } #[test] fn arcs_land_on_the_ellipse() { // A half circle of radius 5 from (0,0) to (10,0), sweeping through (5,-5) or (5,5). - for (sweep, mid_y) in [("1", -5.0), ("0", 5.0)] { - let p = parse_path_data(&format!("M0 0 A5 5 0 0 {sweep} 10 0")).unwrap(); + for (sweep, mid_y) in [(true, -5.0), (false, 5.0)] { + let mut p = Path::new(); + p.move_to(Vec2::ZERO); + arc_to(&mut p, [0.0, 0.0], 5.0, 5.0, 0.0, false, sweep, [10.0, 0.0]); let lines = p.flatten(&crate::Affine::IDENTITY, 0.01); let pts = &lines[0].points; assert!(pts.iter().all(|q| (q.distance(Vec2::new(5.0, 0.0)) - 5.0).abs() < 0.05), "on the circle"); assert!(pts.iter().any(|q| (q.y - mid_y).abs() < 0.05), "through the right side ({sweep})"); assert_eq!(pts.last().copied(), Some(Vec2::new(10.0, 0.0))); } - // Packed flags as icon sets write them, and radii too small get scaled up. - let p = parse_path_data("M2 2a1 1 0 011 1a.1.1 0 0 0 4 0").unwrap(); - assert_eq!(ends(&p).last().copied(), Some(Vec2::new(7.0, 3.0))); - // A real icon outline (rounded square corner arcs). - let lock = parse_path_data("M7 11V7a5 5 0 0 1 10 0v4").unwrap(); - assert_eq!(ends(&lock).last().copied(), Some(Vec2::new(17.0, 11.0))); } #[test] - fn bad_input_is_an_error() { - for bad in ["", "10 10", "M", "M 1", "M0 0 A1 1 0 2 0 3 3", "M0 0 Z 4 4", "M0 0 L1e999 0", "M0 0 X1 1"] { - if bad.is_empty() { - assert!(parse_path_data(bad).unwrap().is_empty()); - continue; - } - assert!(parse_path_data(bad).is_err(), "{bad}"); - } + fn degenerate_arcs() { + // No distance: nothing. Zero radius: a straight line. + let mut p = Path::new(); + p.move_to(Vec2::ZERO); + arc_to(&mut p, [0.0, 0.0], 5.0, 5.0, 0.0, false, true, [0.0, 0.0]); + assert_eq!(p.cmds.len(), 1); + arc_to(&mut p, [0.0, 0.0], 0.0, 5.0, 0.0, false, true, [3.0, 4.0]); + assert_eq!(p.cmds.len(), 2); } } diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index dd74fb6f..ac7f8c5e 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -11,6 +11,8 @@ repository.workspace = true anicraft-geom.workspace = true anicraft-doc.workspace = true anicraft-xml.workspace = true +# SVG text (SVGZ, encodings, pre-parse limits) and path data, shared by the Craft apps. +craft-svg.workspace = true # Lays imported text out with the fonts on this computer (ADR 0012, ADR 0021). anicraft-text.workspace = true thiserror.workspace = true diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 4eb53b66..06a73c71 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -27,7 +27,6 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] use anicraft_doc::{Cap, Dash, ElementKind, GradientStop, Join, Paint, Rgba, Shape, Spread, Stroke, StrokeStyle, MAX_FOCAL}; -use anicraft_geom::svg::parse_path_data; use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; use anicraft_text::{FaceMatch, Fonts}; use anicraft_xml::Element as X; @@ -36,8 +35,11 @@ use std::rc::Rc; use std::sync::Arc; mod clip; +mod path_data; mod text; +pub use path_data::parse_path_data; + #[cfg(test)] mod clip_tests; #[cfg(test)] @@ -59,6 +61,10 @@ pub enum SvgError { Xml(#[from] anicraft_xml::XmlError), #[error("this is not an SVG drawing (its root element is <{0}>)")] NotSvg(String), + /// The bytes could not be read as SVG text within the shared limits (SVGZ unpacking, text + /// encoding, entity expansion, nesting, attributes). + #[error(transparent)] + Preflight(#[from] craft_svg::preflight::Error), } /// What could not come across, by kind ("2 images"), and the fonts the text asks for that @@ -167,7 +173,8 @@ pub fn import_with_fonts(bytes: &[u8], fonts: &Fonts) -> Result) -> Result { - let root = anicraft_xml::parse_mixed(bytes, TEXT_CONTENT)?; + let text = svg_text(bytes)?; + let root = anicraft_xml::parse_mixed(text.as_bytes(), TEXT_CONTENT)?; if local(&root.name) != "svg" { return Err(SvgError::NotSvg(root.name.clone())); } @@ -198,6 +205,32 @@ fn import_from(bytes: &[u8], fonts: Option<&Fonts>) -> Result Result, SvgError> { + use craft_svg::guard; + use craft_svg::preflight::{Error, Limits}; + let limits = Limits::default(); + let text = craft_svg::svgz::text(bytes, limits.bytes).map_err(Error::from)?; + // svgz::text limits the source or inflated bytes, not the UTF-8 length after Latin-1 + // (or UTF-16) decoding. A 40 MiB Latin-1 file of non-ASCII would become ~80 MiB here. + if text.len() > limits.bytes { + return Err(Error::Text(craft_svg::svgz::Error::TooLarge(limits.bytes)).into()); + } + if guard::entities_expand_past(&text, limits.entity_bytes) { + return Err(Error::Entities.into()); + } + if guard::too_wide(&text, limits.attributes, limits.attribute_work) { + return Err(Error::TooWide(limits.attributes).into()); + } + if guard::deeper_than(&text, limits.depth) { + return Err(Error::TooDeep(limits.depth).into()); + } + Ok(text) +} + /// The element's `id`, as an element name. fn name_of(el: &X) -> String { el.attr("id").unwrap_or("").chars().take(128).collect() @@ -325,103 +358,94 @@ fn transform(s: &str) -> Affine { if m.is_finite() { m } else { Affine::IDENTITY } } -fn named(name: &str) -> Option { - Some(match name { - "black" => 0x000000, - "white" => 0xffffff, - "red" => 0xff0000, - "lime" => 0x00ff00, - "green" => 0x008000, - "blue" => 0x0000ff, - "yellow" => 0xffff00, - "cyan" | "aqua" => 0x00ffff, - "magenta" | "fuchsia" => 0xff00ff, - "gray" | "grey" => 0x808080, - "silver" => 0xc0c0c0, - "maroon" => 0x800000, - "olive" => 0x808000, - "purple" => 0x800080, - "teal" => 0x008080, - "navy" => 0x000080, - "orange" => 0xffa500, - "pink" => 0xffc0cb, - "brown" => 0xa52a2a, - "gold" => 0xffd700, - "indigo" => 0x4b0082, - "violet" => 0xee82ee, - "coral" => 0xff7f50, - "salmon" => 0xfa8072, - "tomato" => 0xff6347, - "crimson" => 0xdc143c, - "khaki" => 0xf0e68c, - "beige" => 0xf5f5dc, - "ivory" => 0xfffff0, - "tan" => 0xd2b48c, - "chocolate" => 0xd2691e, - "sienna" => 0xa0522d, - "turquoise" => 0x40e0d0, - "skyblue" => 0x87ceeb, - "steelblue" => 0x4682b4, - "royalblue" => 0x4169e1, - "darkblue" => 0x00008b, - "lightblue" => 0xadd8e6, - "darkgreen" => 0x006400, - "lightgreen" => 0x90ee90, - "forestgreen" => 0x228b22, - "darkred" => 0x8b0000, - "darkgray" | "darkgrey" => 0xa9a9a9, - "lightgray" | "lightgrey" => 0xd3d3d3, - "dimgray" | "dimgrey" => 0x696969, - "darkorange" => 0xff8c00, - "orchid" => 0xda70d6, - "plum" => 0xdda0dd, - "lavender" => 0xe6e6fa, - "slategray" | "slategrey" => 0x708090, - "whitesmoke" => 0xf5f5f5, - "gainsboro" => 0xdcdcdc, - _ => return None, - }) -} - -/// A CSS colour (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`, `rgba()`, a name). +/// A CSS colour (`#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb()`/`hsl()`, a name). +/// `transparent` stays here: the shared parser treats it as an error so callers that +/// need an opaque colour are not surprised. fn color(v: &str) -> Option { let v = v.trim(); - let lower = v.to_ascii_lowercase(); - if let Some(h) = lower.strip_prefix('#') { - let expand = |s: &str| s.chars().flat_map(|c| [c, c]).collect::(); - return match h.len() { - 3 | 4 => Rgba::parse_hex(&expand(h)), - 6 | 8 => Rgba::parse_hex(h), - _ => None, - }; - } - if let Some(args) = lower.strip_prefix("rgba(").or_else(|| lower.strip_prefix("rgb(")) { - let args = args.trim_end_matches(')'); - let parts: Vec<&str> = args.split([',', ' ', '/']).filter(|p| !p.is_empty()).collect(); - let chan = |p: &str| -> Option { - match p.strip_suffix('%') { - Some(pc) => pc.parse::().ok().map(|x| x / 100.0), - None => p.parse::().ok().map(|x| x / 255.0), - } - .filter(|x| x.is_finite()) - .map(|x| x.clamp(0.0, 1.0)) - }; - let alpha = |p: &str| -> Option { - match p.strip_suffix('%') { - Some(pc) => pc.parse::().ok().map(|x| x / 100.0), - None => p.parse::().ok(), - } - .filter(|x| x.is_finite()) - .map(|x| x.clamp(0.0, 1.0)) - }; - let (r, g, b) = (chan(parts.first()?)?, chan(parts.get(1)?)?, chan(parts.get(2)?)?); - let a = parts.get(3).map_or(Some(1.0), |p| alpha(p))?; - return Some(Rgba::new(r, g, b, a)); - } - if lower == "transparent" { + if v.eq_ignore_ascii_case("transparent") { return Some(Rgba::TRANSPARENT); } - named(&lower).map(Rgba::hex) + if let Some(rgba) = rgba_from_shared(v) { + return Some(rgba); + } + // CSS clips out-of-range rgb()/rgba() channels; the shared parser rejects them. Clip + // and try once more so `fill="rgb(300,0,0)"` still becomes red, as it did before the pin. + rgba_from_shared(&clipped_rgb(v)?) +} + +fn rgba_from_shared(v: &str) -> Option { + let (c, a) = craft_svg::color::parse_color_alpha(v).ok()?; + Some(Rgba::new(f32::from(c.r) / 255.0, f32::from(c.g) / 255.0, f32::from(c.b) / 255.0, a)) +} + +/// `rgb()`/`rgba()` with each channel clipped to its range (0–255, or 0%–100%). Other +/// colour forms are left alone so the shared parser's errors still stand. +/// +/// At most four components are collected, so a 60 MiB `rgb(0,0,0,0,0,…)` does not +/// allocate millions of slices before being rejected. Number-form channels are +/// emitted as integers: the shared parser rejects a decimal such as `127.5`. +fn clipped_rgb(v: &str) -> Option { + let lower = v.trim().to_ascii_lowercase(); + let (name, rest) = lower.split_once('(')?; + if name != "rgb" && name != "rgba" { + return None; + } + let body = rest.trim().strip_suffix(')')?; + let mut parts: Vec<&str> = Vec::with_capacity(4); + if body.contains(',') { + for p in body.split(',') { + if parts.len() >= 4 { + return None; + } + parts.push(p.trim()); + } + } else { + let (channels, alpha) = match body.split_once('/') { + Some((channels, alpha)) => (channels, Some(alpha.trim())), + None => (body, None), + }; + for p in channels.split_whitespace() { + if parts.len() >= 4 { + return None; + } + parts.push(p); + } + if let Some(alpha) = alpha { + if parts.len() >= 4 { + return None; + } + parts.push(alpha); + } + } + if parts.len() != 3 && parts.len() != 4 { + return None; + } + let clip_rgb = |p: &str| -> Option { + if let Some(pc) = p.strip_suffix('%') { + let n: f32 = pc.parse().ok().filter(|x: &f32| x.is_finite())?; + return Some(format!("{}%", n.clamp(0.0, 100.0))); + } + let n: f32 = p.parse().ok().filter(|x: &f32| x.is_finite())?; + // The shared parser rejects non-percentage decimals; CSS 8-bit channels are integers. + Some(format!("{}", n.clamp(0.0, 255.0).round() as u8)) + }; + let clip_alpha = |p: &str| -> Option { + if let Some(pc) = p.strip_suffix('%') { + let n: f32 = pc.parse().ok().filter(|x: &f32| x.is_finite())?; + return Some(format!("{}%", n.clamp(0.0, 100.0))); + } + let n: f32 = p.parse().ok().filter(|x: &f32| x.is_finite())?; + Some(format!("{}", n.clamp(0.0, 1.0))) + }; + let r = clip_rgb(parts[0])?; + let g = clip_rgb(parts[1])?; + let b = clip_rgb(parts[2])?; + if let Some(a) = parts.get(3) { + Some(format!("rgb({r}, {g}, {b}, {})", clip_alpha(a)?)) + } else { + Some(format!("rgb({r}, {g}, {b})")) + } } // ----- style ------------------------------------------------------------------------------------ diff --git a/crates/svg/src/path_data.rs b/crates/svg/src/path_data.rs new file mode 100644 index 00000000..cb083fa0 --- /dev/null +++ b/crates/svg/src/path_data.rs @@ -0,0 +1,147 @@ +//! SVG path data (the `d` attribute) as an AniCraft [`Path`]. +//! +//! craft-svg reads the data: every command in absolute and relative form (M L H V C S Q T A Z), +//! implicit repeats, packed numbers and arc flags, with the S/T reflections resolved and +//! quadratics raised to cubics. This module only maps its segments onto [`Path`], turning +//! elliptical arcs into cubics with [`anicraft_geom::svg::arc_to`]. Never panics; malformed, +//! non-finite and oversized path data are errors. + +use anicraft_geom::svg::{MAX_PATH_CMDS, arc_to}; +use anicraft_geom::{Path, PathCmd, Vec2}; +use craft_svg::path_data::{Point, Segment, parse_path}; + +fn v(p: Point) -> Vec2 { + Vec2::new(p.x as f32, p.y as f32) +} + +/// Parses SVG path data into a [`Path`]: icon outlines, `path.d` commands and SVG import. +pub fn parse_path_data(d: &str) -> Result { + // The shared geometry parser permits an implicit origin; SVG and command input must + // begin with moveto rather than manufacturing an anchor for malformed drawing commands. + if let Some(first) = d.bytes().find(|byte| !matches!(byte, b' ' | b'\t' | b'\r' | b'\n')) + && !matches!(first, b'M' | b'm') + { + return Err("path data must start with moveto".into()); + } + let subpaths = parse_path(d).map_err(|e| e.to_string())?; + let mut path = Path::new(); + for sub in subpaths { + path.move_to(v(sub.start)); + let mut cur = sub.start; + for seg in &sub.segs { + match *seg { + Segment::Line(p) => { + path.line_to(v(p)); + cur = p; + } + Segment::Cubic(c1, c2, p) => { + path.cubic_to(v(c1), v(c2), v(p)); + cur = p; + } + Segment::Arc { rx, ry, rot, large, sweep, end } => { + arc_to(&mut path, [cur.x, cur.y], rx, ry, rot, large, sweep, [end.x, end.y]); + cur = end; + } + } + if path.cmds.len() > MAX_PATH_CMDS { + return Err(format!("path has more than {MAX_PATH_CMDS} commands")); + } + } + if sub.closed { + path.close(); + } + } + if !path.cmds.iter().all(finite) { + return Err("path data has a number too large to draw".into()); + } + Ok(path) +} + +/// Whether every point of `cmd` fits an `f32` (a number past it would draw nothing). +fn finite(cmd: &PathCmd) -> bool { + match cmd { + PathCmd::MoveTo(p) | PathCmd::LineTo(p) => p.is_finite(), + PathCmd::QuadTo(c, p) => c.is_finite() && p.is_finite(), + PathCmd::CubicTo(a, b, p) => a.is_finite() && b.is_finite() && p.is_finite(), + PathCmd::Close => true, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ends(p: &Path) -> Vec { + p.anchors().into_iter().map(|(_, a)| a).collect() + } + + #[test] + fn nonempty_paths_require_an_initial_moveto() { + for data in ["L10 10", "H10", "V10", "C0 0 1 1 2 2", "Q1 1 2 2", "Z", " l10 10"] { + assert!(parse_path_data(data).is_err(), "accepted drawing command without moveto: {data}"); + } + for data in ["", " \t\r\n", "m1 2 l3 4", " M0 0 L1 1"] { + assert!(parse_path_data(data).is_ok(), "rejected valid path: {data:?}"); + } + } + + #[test] + fn malformed_tokens_do_not_import_a_truncated_path() { + for data in ["@", "M0 0 L1 1 @", "M0 0 L1 1 1e", "M0 0 L1 1 1e9999"] { + assert!(parse_path_data(data).is_err(), "accepted malformed path: {data}"); + } + assert!(parse_path_data("M0 0 L1 1 ").is_ok()); + } + + #[test] + fn relative_and_shorthand_commands() { + let p = parse_path_data("m10 10 h5 v5 H10 z m 1,1 l2-2").unwrap(); + assert_eq!( + ends(&p), + vec![ + Vec2::new(10.0, 10.0), + Vec2::new(15.0, 10.0), + Vec2::new(15.0, 15.0), + Vec2::new(10.0, 15.0), + Vec2::new(11.0, 11.0), + Vec2::new(13.0, 9.0) + ] + ); + assert!(matches!(p.cmds[4], PathCmd::Close)); + // Implicit lineto after moveto, packed negative numbers. + let q = parse_path_data("M0 0 10 0-5.5.5").unwrap(); + assert_eq!(ends(&q), vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(-5.5, 0.5)]); + // S reflects the previous control point. + let s = parse_path_data("M0 0 C 0 10 10 10 10 0 S 20 -10 20 0").unwrap(); + assert!(matches!(s.cmds[2], PathCmd::CubicTo(c1, _, _) if (c1 - Vec2::new(10.0, -10.0)).length() < 1e-5)); + // Q and T become cubics through the same curve. + let t = parse_path_data("M0 0 Q 5 10 10 0 T 20 0").unwrap(); + assert_eq!(ends(&t).last().copied(), Some(Vec2::new(20.0, 0.0))); + } + + #[test] + fn arcs_land_on_the_ellipse() { + for (sweep, mid_y) in [("1", -5.0), ("0", 5.0)] { + let p = parse_path_data(&format!("M0 0 A5 5 0 0 {sweep} 10 0")).unwrap(); + let lines = p.flatten(&anicraft_geom::Affine::IDENTITY, 0.01); + let pts = &lines[0].points; + assert!(pts.iter().all(|q| (q.distance(Vec2::new(5.0, 0.0)) - 5.0).abs() < 0.05), "on the circle"); + assert!(pts.iter().any(|q| (q.y - mid_y).abs() < 0.05), "through the right side ({sweep})"); + assert_eq!(pts.last().copied(), Some(Vec2::new(10.0, 0.0))); + } + // Packed flags as icon sets write them, and radii too small get scaled up. + let p = parse_path_data("M2 2a1 1 0 011 1a.1.1 0 0 0 4 0").unwrap(); + assert_eq!(ends(&p).last().copied(), Some(Vec2::new(7.0, 3.0))); + // A real icon outline (rounded square corner arcs). + let lock = parse_path_data("M7 11V7a5 5 0 0 1 10 0v4").unwrap(); + assert_eq!(ends(&lock).last().copied(), Some(Vec2::new(17.0, 11.0))); + } + + #[test] + fn bad_input_is_an_error() { + assert!(parse_path_data("").unwrap().is_empty()); + for bad in ["10 10", "M", "M 1", "M0 0 A1 1 0 2 0 3 3", "M0 0 Z 4 4", "M0 0 L1e999 0", "M0 0 L1e300 0", "M0 0 X1 1"] { + assert!(parse_path_data(bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index 53ea1703..c21a7fb4 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -200,9 +200,16 @@ fn colours() { assert_eq!(color("#f00"), Some(Rgba::hex(0xff0000))); assert_eq!(color("#ff000080").map(|c| (c.a * 255.0).round()), Some(128.0)); assert_eq!(color("rgba(255, 0, 0, 0.25)"), Some(Rgba::new(1.0, 0.0, 0.0, 0.25))); - assert_eq!(color("rgb(100%, 50%, 0%)"), Some(Rgba::new(1.0, 0.5, 0.0, 1.0))); + assert_eq!(color("rgb(100%, 50%, 0%)"), Some(Rgba::hex(0xff8000))); assert_eq!(color("SteelBlue"), Some(Rgba::hex(0x4682b4))); assert_eq!(color("transparent"), Some(Rgba::TRANSPARENT)); + assert_eq!(color("rgb(300, 0, 0)"), Some(Rgba::hex(0xff0000))); + assert_eq!(color("rgb(-20, 50%, 200%)"), Some(Rgba::hex(0x0080ff))); + // Fractional number-form channels are clipped and retried as integers (127.5 → 128). + assert_eq!(color("rgb(300, 127.5, 0)"), Some(Rgba::hex(0xff8000))); + // A fifth component is rejected without scanning the rest of a huge argument list. + let huge = format!("rgb(0,0,0,0{})", ",0".repeat(200_000)); + assert_eq!(color(&huge), None); for bad in ["", "#12", "rgb(1,2)", "notacolour", "#ééé"] { assert_eq!(color(bad), None, "{bad}"); } @@ -228,6 +235,38 @@ fn hostile_input_is_an_error_or_harmless() { assert!(i.report.skipped.contains_key("unreadable paths")); } +#[test] +fn svgz_and_other_encodings_are_read() { + let svg = r##""##; + let packed = craft_svg::svgz::compress(svg.as_bytes()); + let i = import_with_fonts(&packed, &Fonts::from_faces(Vec::new())).unwrap(); + assert_eq!(i.elements().count(), 1); + // UTF-16 with a byte order mark. + let utf16: Vec = [0xFF, 0xFE].into_iter().chain(svg.encode_utf16().flat_map(u16::to_le_bytes)).collect(); + let i = import_with_fonts(&utf16, &Fonts::from_faces(Vec::new())).unwrap(); + assert_eq!(i.elements().count(), 1); +} + +#[test] +fn hostile_markup_is_refused_before_parsing() { + let fonts = Fonts::from_faces(Vec::new()); + // Entities that expand a thousandfold at each level. + let mut bomb = String::from(""); + let mut prev = 'a'; + for name in ['b', 'c', 'd', 'e', 'f', 'g', 'h'] { + bomb.push_str(&format!("", format!("&{prev};").repeat(10))); + prev = name; + } + bomb.push_str("]>&h;"); + assert!(matches!(import_with_fonts(bomb.as_bytes(), &fonts), Err(SvgError::Preflight(craft_svg::preflight::Error::Entities)))); + // Groups nested far past any drawing. + let deep = format!("{}{}", "".repeat(5000), "".repeat(5000)); + assert!(matches!(import_with_fonts(deep.as_bytes(), &fonts), Err(SvgError::Preflight(craft_svg::preflight::Error::TooDeep(_))))); + // An unpacked SVGZ past the size limit. + let huge = craft_svg::svgz::compress(&vec![b' '; (64 << 20) + 1]); + assert!(matches!(import_with_fonts(&huge, &fonts), Err(SvgError::Preflight(craft_svg::preflight::Error::Text(craft_svg::svgz::Error::TooLarge(_)))))); +} + #[test] fn colour_rejects_multiple_leading_hashes() { assert!(color("#abc").is_some()); diff --git a/src/icons.rs b/src/icons.rs index adecf888..2a843ef1 100644 --- a/src/icons.rs +++ b/src/icons.rs @@ -2,11 +2,11 @@ //! //! Lucide icons are 24 × 24 outlines made of a few SVG shapes. Rather than pull in an SVG //! rasterizer, the shapes are parsed once with the engine's own SVG path reader -//! (`geom::svg`) and stroked as vectors at the exact on-screen size, so they stay crisp at any +//! (`anicraft_svg::parse_path_data`, on craft-svg) and stroked as vectors at the exact on-screen size, so they stay crisp at any //! interface scale and cost nothing in build size. Only icons the app uses are embedded; add a //! file to `assets/icons/` and a variant here to use another. -use anicraft_engine::geom::svg::parse_path_data; +use anicraft_engine::svg::parse_path_data; use anicraft_engine::geom::{Affine, Path, Vec2}; use egui::{Color32, Pos2, Rect, Stroke, pos2}; use std::collections::HashMap;