mirror of
https://github.com/storytold/AniCraft.git
synced 2026-11-19 09:01:29 +01:00
refactor(svg): read SVG text and path data through craft-svg (#386)
* refactor(svg): read SVG text and path data through craft-svg SVG import now decodes its bytes with craft-svg (SVGZ, UTF-16 and Latin-1, within the shared size limit) and refuses entity bombs, very wide elements and deep nesting with craft-svg's guards before anicraft_xml builds a tree. Path data (SVG import, the path.d and motion path commands, the interface icons) is read by craft_svg::path_data. anicraft-geom keeps only the elliptical-arc-to-cubic geometry; its own tokenizer is removed. craft-svg is pinned to craft-libs main 57288eda. Refs storytold/craft-libs#778, storytold/craft-libs#789 * refactor(svg): pin craft-svg to #1848 and parse colours through it craft-svg is now at craft-libs main b836a718 (#1848), with default features off, so the lock no longer pulls vectorcraft or the image codecs. Colours go through parse_color_alpha; transparent stays in the app because the shared parser rejects it. Percentage rgb channels follow the shared parser's 8-bit rounding (50% is 128/255). * fix(svg): clip out-of-range rgb() and bound decoded text parse_color_alpha rejects rgb(300,0,0); CSS clips that to red, and so did the previous local parser. If the shared parser fails, clip rgb() channels and try once more. Also refuse text that grows past the 64 MiB limit after Latin-1 or UTF-16 decoding, which svgz::text does not count. * refactor(svg): pin craft-svg to #1878 craft-svg is now at craft-libs main c7a872e2 (#1878), which bounds the entity-declaration scan and resets smooth-control history after Z. default-features stays false. The other craft-libs pins are unchanged. * fix(svg): bound rgb() components and emit integer channels clipped_rgb now stops at a fifth component instead of collecting an unbounded comma list, and number-form channels are retried as integers so a value such as 127.5 is accepted by the shared parser. * fix(svg): finish parser routing and reject missing moveto Route the newer Continue Path entry point through the shared adapter. Require an initial moveto and assert precise preflight refusal variants. Focused geom/SVG tests: 137 + 31 passed. Quadratic gradient parity remains a separate merge blocker. --------- Co-authored-by: Dylan M. Taylor <dylan@dylanmtaylor.com>
This commit is contained in:
1 parent
5f94e2de20
commit
4a75c49e3b
11 files changed
+372
-314
No files matched your search
Generated
+33
@@ -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"
|
||||
|
||||
@@ -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"] }
|
||||
|
||||
@@ -276,7 +276,7 @@ fn set_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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));
|
||||
|
||||
@@ -81,7 +81,7 @@ fn draw_path(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> {
|
||||
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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
+24
-213
@@ -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<u8> {
|
||||
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<f64, String> {
|
||||
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<bool, String> {
|
||||
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<Path, String> {
|
||||
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<P>, Option<P>) = (None, None);
|
||||
let mut cmd: Option<u8> = 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<P, String> { 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<Vec2> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
+119
-95
@@ -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<SvgImport, SvgEr
|
||||
}
|
||||
|
||||
fn import_from(bytes: &[u8], fonts: Option<&Fonts>) -> Result<SvgImport, SvgError> {
|
||||
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<SvgImport, SvgErro
|
||||
Ok(SvgImport { width: w, height: h, layers, report: b.report })
|
||||
}
|
||||
|
||||
/// The document as UTF-8 text: SVGZ unpacked and UTF-16 or Latin-1 decoded within the shared
|
||||
/// size limit, and hostile markup (entity bombs, very wide elements, deep nesting) refused before
|
||||
/// the XML reader builds a tree. The XML itself is left to `anicraft_xml`, which accepts what
|
||||
/// drawing tools write loosely (an undeclared `xlink:` prefix).
|
||||
fn svg_text(bytes: &[u8]) -> Result<std::borrow::Cow<'_, str>, 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<u32> {
|
||||
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<Rgba> {
|
||||
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::<String>();
|
||||
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<f32> {
|
||||
match p.strip_suffix('%') {
|
||||
Some(pc) => pc.parse::<f32>().ok().map(|x| x / 100.0),
|
||||
None => p.parse::<f32>().ok().map(|x| x / 255.0),
|
||||
}
|
||||
.filter(|x| x.is_finite())
|
||||
.map(|x| x.clamp(0.0, 1.0))
|
||||
};
|
||||
let alpha = |p: &str| -> Option<f32> {
|
||||
match p.strip_suffix('%') {
|
||||
Some(pc) => pc.parse::<f32>().ok().map(|x| x / 100.0),
|
||||
None => p.parse::<f32>().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<Rgba> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
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 ------------------------------------------------------------------------------------
|
||||
|
||||
@@ -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<Path, String> {
|
||||
// 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<Vec2> {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
-1
@@ -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##"<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10"><rect width="4" height="4" fill="#123456"/></svg>"##;
|
||||
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<u8> = [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("<?xml version=\"1.0\"?><!DOCTYPE svg [<!ENTITY a \"aaaaaaaaaa\">");
|
||||
let mut prev = 'a';
|
||||
for name in ['b', 'c', 'd', 'e', 'f', 'g', 'h'] {
|
||||
bomb.push_str(&format!("<!ENTITY {name} \"{}\">", format!("&{prev};").repeat(10)));
|
||||
prev = name;
|
||||
}
|
||||
bomb.push_str("]><svg xmlns=\"http://www.w3.org/2000/svg\"><text>&h;</text></svg>");
|
||||
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!("<svg xmlns=\"http://www.w3.org/2000/svg\">{}{}</svg>", "<g>".repeat(5000), "</g>".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());
|
||||
|
||||
+2
-2
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user