diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 22f5cf24..dd74fb6f 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "anicraft-svg" -description = "AniCraft SVG import: shapes, groups, transforms, styles and gradients into editable vector shapes" +description = "AniCraft SVG import: shapes, groups, transforms, styles, gradients, clip paths, masks and text into editable shapes, mask layers and text" version.workspace = true edition.workspace = true license.workspace = true @@ -11,6 +11,8 @@ repository.workspace = true anicraft-geom.workspace = true anicraft-doc.workspace = true anicraft-xml.workspace = true +# Lays imported text out with the fonts on this computer (ADR 0012, ADR 0021). +anicraft-text.workspace = true thiserror.workspace = true [lints] diff --git a/crates/svg/fixtures/clips-masks-text.svg b/crates/svg/fixtures/clips-masks-text.svg new file mode 100644 index 00000000..2f859612 --- /dev/null +++ b/crates/svg/fixtures/clips-masks-text.svg @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + Clipped & masked + AniCraft SVG import + + diff --git a/crates/svg/src/clip.rs b/crates/svg/src/clip.rs new file mode 100644 index 00000000..2917f2c9 --- /dev/null +++ b/crates/svg/src/clip.rs @@ -0,0 +1,412 @@ +//! Clip paths and masks → mask layers (ADR 0021). +//! +//! While the drawing is read, every drawn item collects the clip regions of the elements +//! around it: a `clipPath` (the union of its shapes' fills) or a `mask` whose content is +//! opaque (the union of its fills, cut to the mask's region). At the end, [`Builder::layers`] +//! resolves each item's regions: +//! * a convex region that contains the item cuts nothing and is dropped; a region that misses +//! it hides it (it is left out); +//! * one region left is the item's mask; several are intersected exactly when all but one are +//! convex polygons (`anicraft_geom::clip`), else one is kept and the report counts it; +//! * consecutive items with the same mask share one masked layer under one mask layer. + +use crate::{Builder, ImportedElement, ImportedLayer, ImportedMask, Item, PaintSpec, Report, Style, declarations, get, hidden, length, local, name_of, paint_spec, transform}; +use anicraft_doc::{ElementKind, Paint, Rgba, Shape}; +use anicraft_geom::clip::{clip_convex, convex_polygon}; +use anicraft_geom::{Affine, FillRule, Path, Rect, Vec2}; +use anicraft_xml::Element as X; +use std::collections::HashMap; +use std::rc::Rc; +use std::sync::Arc; + +/// Most mask layers one drawing makes; clips past these are drawn unclipped and reported. +pub const MAX_MASKS: usize = 250; +/// Deepest chain of clip paths and masks that refer to further ones. +const MAX_NESTING: usize = 8; + +/// A clip region in drawing space: the union of its parts' fills. +#[derive(Debug)] +pub(crate) struct Region { + /// Identifies the region: the clip element and the space it was used in. + key: String, + name: String, + parts: Vec, + /// The corners, when the region is one convex polygon. + convex: Option>, + /// Conservative drawing-space bounds. + bounds: Rect, +} + +/// Conservative drawing-space bounds of an element's artwork. +fn element_bounds(e: &ImportedElement) -> Rect { + match &e.kind { + ElementKind::Shape(s) => s.path.bounds().inflate(s.stroke.map_or(0.0, |st| st.width * 0.5)).transformed(&e.transform), + ElementKind::Text(t) => t.outline.bounds().union(&Rect::new(0.0, 0.0, t.box_width.max(0.0), t.box_height.max(0.0))).transformed(&e.transform), + ElementKind::Symbol { .. } => Rect::EMPTY, + } +} + +/// A fill-only shape for mask artwork (its colour doesn't matter: a mask is its fills' area). +fn mask_part(name: String, path: Path, transform: Affine, rule: FillRule) -> ImportedElement { + let shape = Shape { path: Arc::new(path), fill: Some(Paint::Solid(Rgba::BLACK)), stroke: None, fill_rule: rule }; + ImportedElement { name, transform, alpha: 1.0, kind: ElementKind::Shape(shape) } +} + +impl Region { + fn new(key: String, name: &str, parts: Vec) -> Rc { + let bounds = parts.iter().fold(Rect::EMPTY, |r, p| r.union(&element_bounds(p))); + let convex = match parts.as_slice() { + [ImportedElement { kind: ElementKind::Shape(s), transform, .. }] => convex_polygon(&s.path.transformed(transform)), + _ => None, + }; + Rc::new(Region { key, name: name.chars().take(128).collect(), parts, convex, bounds }) + } + + /// Whether the region is convex and holds all of `r`. + fn contains(&self, r: &Rect) -> bool { + let Some(poly) = &self.convex else { return false }; + if !(r.min.x <= r.max.x && r.min.y <= r.max.y) { + return false; + } + let n = poly.len(); + let area2: f32 = (0..n).map(|i| poly[i].cross(poly[(i + 1) % n])).sum(); + let s = area2.signum(); + let corners = [r.min, Vec2::new(r.max.x, r.min.y), r.max, Vec2::new(r.min.x, r.max.y)]; + (0..n).all(|i| { + let (a, b) = (poly[i], poly[(i + 1) % n]); + let tol = 1e-3 * (b - a).length(); + corners.iter().all(|p| s * (b - a).cross(*p - a) >= -tol) + }) + } + + /// This region cut to the convex region `other`, exactly. + fn intersect(&self, other: &Region) -> Rc { + let Some(poly) = &other.convex else { return Region::new(self.key.clone(), &self.name, self.parts.clone()) }; + let mut parts = Vec::new(); + for p in &self.parts { + let (path, rule) = match &p.kind { + ElementKind::Shape(s) => (s.path.transformed(&p.transform), s.fill_rule), + ElementKind::Text(t) => (t.outline.transformed(&p.transform), FillRule::NonZero), + ElementKind::Symbol { .. } => continue, + }; + let cut = clip_convex(&path, poly); + if !cut.is_empty() { + parts.push(mask_part(p.name.clone(), cut, Affine::IDENTITY, rule)); + } + } + Region::new(format!("{}&{}", self.key, other.key), &self.name, parts) + } +} + +/// What an item's clips come to. +enum Effective { + /// Nothing of it shows. + Hidden, + Unclipped, + Masked(Rc), +} + +/// The id in `url(#id)`. +fn url(v: &str) -> Option { + match paint_spec(v) { + Some(PaintSpec::Url(id, _)) => Some(id), + _ => None, + } +} + +/// A mask region attribute: a fraction or percentage of the bounding box. +fn fraction(v: Option<&str>, default: f32) -> f32 { + v.map(str::trim) + .and_then(|v| match v.strip_suffix('%') { + Some(p) => p.trim().parse::().ok().map(|p| p / 100.0), + None => v.parse::().ok(), + }) + .filter(|x| x.is_finite()) + .unwrap_or(default) +} + +impl<'a> Builder<'a> { + /// Applies an element's `clip-path` and `mask` to what it drew (`items[start..]`); `m` is its + /// user space. + pub(crate) fn clip(&mut self, d: &[(String, String)], m: &Affine, start: usize, depth: usize) { + let clip = get(d, "clip-path").filter(|v| *v != "none").map(str::to_string); + let mask = get(d, "mask").filter(|v| *v != "none").map(str::to_string); + if clip.is_none() && mask.is_none() { + return; + } + let bbox = self.user_bbox(start, m); + let mut regions: Vec> = Vec::new(); + if let Some(v) = clip { + match url(&v) { + Some(id) => match self.clip_path(&id, m, bbox) { + Some(r) => regions.extend(r), + None => self.report.skip("references to missing clip paths (drawn unclipped)"), + }, + None => self.report.skip("CSS clip shapes (drawn unclipped)"), + } + } + if let Some(v) = mask { + match url(&v) { + Some(id) => match self.mask(&id, m, bbox, depth) { + Some(r) => regions.extend(r), + None => self.report.skip("references to missing masks (drawn unmasked)"), + }, + None => self.report.skip("CSS mask images (drawn unmasked)"), + } + } + for it in self.items.iter_mut().skip(start) { + it.clips.extend(regions.iter().cloned()); + } + } + + /// The bounding box of `items[start..]` in the user space `m` maps from (the box + /// `objectBoundingBox` units refer to). + fn user_bbox(&self, start: usize, m: &Affine) -> Option { + let inv = m.inverse()?; + let mut r = Rect::EMPTY; + for it in self.items.iter().skip(start) { + let to_user = inv.mul(&it.el.transform); + match &it.el.kind { + ElementKind::Shape(s) => { + for line in s.path.flatten(&to_user, 0.05) { + for p in line.points { + r.include(p); + } + } + } + ElementKind::Text(t) => r = r.union(&Rect::new(0.0, 0.0, t.box_width, t.box_height).transformed(&to_user)), + ElementKind::Symbol { .. } => {} + } + } + (r.min.x <= r.max.x && r.min.y <= r.max.y).then_some(r) + } + + /// Whether `target` is already being read (a loop), or the chain is too long. Reports it. + fn looping(&mut self, target: &X) -> bool { + if self.resolving.iter().any(|r| std::ptr::eq(*r, target)) || self.resolving.len() >= MAX_NESTING { + self.report.skip("clip paths or masks that refer to themselves (ignored)"); + return true; + } + false + } + + /// The regions of `clipPath` `id` used in user space `m`: its own, and those of the clip + /// paths it is clipped by. `None` when there is no such clip path. + fn clip_path(&mut self, id: &str, m: &Affine, bbox: Option) -> Option>> { + let target = self.ids.get(id).copied().filter(|t| local(&t.name) == "clipPath")?; + if self.looping(target) { + return Some(Vec::new()); + } + let units = if target.attr("clipPathUnits") == Some("objectBoundingBox") { + match bbox { + Some(b) => Affine::translate(b.min.x, b.min.y).mul(&Affine::scale(b.width(), b.height())), + // Nothing to size the clip by: it clips everything. + None => return Some(vec![Region::new(format!("clip:{target:p}:empty"), id, Vec::new())]), + } + } else { + Affine::IDENTITY + }; + let base = m.mul(&units).mul(&target.attr("transform").map_or(Affine::IDENTITY, transform)); + let style = Style::default().with(target, &mut Report::default()); + self.resolving.push(target); + let mut parts = Vec::new(); + for c in &target.children { + self.clip_child(c, &base, &style, &mut parts, 0); + } + let mut out = vec![Region::new(format!("clip:{target:p}:{:?}", base.m), id, parts)]; + let inner = get(&declarations(target), "clip-path").and_then(url); + if let Some(inner) = inner + && let Some(r) = self.clip_path(&inner, m, bbox) + { + out.extend(r); + } + self.resolving.pop(); + Some(out) + } + + /// One child of a `clipPath`: a shape, text, or a `use` of one. Only its geometry counts. + fn clip_child(&mut self, c: &'a X, base: &Affine, style: &Style, parts: &mut Vec, uses: usize) { + let name = local(&c.name); + let d = declarations(c); + if name == anicraft_xml::TEXT_NODE || get(&d, "display") == Some("none") || hidden(&d) { + return; + } + if get(&d, "clip-path").is_some_and(|v| v != "none") { + self.report.skip("clip paths on the contents of a clip path (ignored)"); + } + let style = style.with(c, &mut Report::default()); + let t = base.mul(&c.attr("transform").map_or(Affine::IDENTITY, transform)); + match name { + "use" if uses < crate::MAX_USE_DEPTH => { + let href = c.attr("href").or_else(|| c.attr("xlink:href")).unwrap_or("").trim_start_matches('#'); + let Some(target) = self.ids.get(href).copied() else { return }; + let (vw, vh) = self.viewport; + let x = c.attr("x").and_then(|v| length(v, vw)).unwrap_or(0.0); + let y = c.attr("y").and_then(|v| length(v, vh)).unwrap_or(0.0); + self.clip_child(target, &t.mul(&Affine::translate(x, y)), &style, parts, uses + 1); + } + "text" => parts.extend(self.text(c, &t, &style, 1.0)), + "path" | "rect" | "circle" | "ellipse" | "polyline" | "polygon" => { + if let Some((p, true)) = self.geometry(c, name) + && !p.is_empty() + && t.is_finite() + { + parts.push(mask_part(name_of(c), p, t, style.clip_rule)); + } + } + _ => {} + } + } + + /// The regions of `mask` `id` used in user space `m`: its content's fills, cut to its + /// region. `None` when there is no such mask; no regions when the mask is soft (reported). + fn mask(&mut self, id: &str, m: &Affine, bbox: Option, depth: usize) -> Option>> { + let target = self.ids.get(id).copied().filter(|t| local(&t.name) == "mask")?; + if self.looping(target) { + return Some(Vec::new()); + } + let everything = || Some(vec![Region::new(format!("mask:{target:p}:empty"), id, Vec::new())]); + // The mask's region: by default the bounding box grown by 10% on every side. + let rect = if target.attr("maskUnits") == Some("userSpaceOnUse") { + let (vw, vh) = self.viewport; + let len = |k: &str, reference: f32, d: f32| target.attr(k).and_then(|v| length(v, reference)).unwrap_or(d * reference); + let (x, y) = (len("x", vw, -0.1), len("y", vh, -0.1)); + Rect::new(x, y, x + len("width", vw, 1.2), y + len("height", vh, 1.2)) + } else { + let Some(b) = bbox else { return everything() }; + let (x, y) = (fraction(target.attr("x"), -0.1), fraction(target.attr("y"), -0.1)); + let (w, h) = (fraction(target.attr("width"), 1.2), fraction(target.attr("height"), 1.2)); + let x0 = b.min.x + x * b.width(); + let y0 = b.min.y + y * b.height(); + Rect::new(x0, y0, x0 + w * b.width(), y0 + h * b.height()) + }; + if rect.is_empty() { + return everything(); + } + let content_m = if target.attr("maskContentUnits") == Some("objectBoundingBox") { + let Some(b) = bbox else { return everything() }; + m.mul(&Affine::translate(b.min.x, b.min.y)).mul(&Affine::scale(b.width(), b.height())) + } else { + *m + }; + let alpha_mask = get(&declarations(target), "mask-type") == Some("alpha"); + let style = Style::default().with(target, &mut Report::default()); + self.resolving.push(target); + let mark = self.items.len(); + self.children(target, &content_m, &style, 1.0, depth + 1, 0); + self.resolving.pop(); + let content: Vec = self.items.drain(mark..).collect(); + // Only an opaque mask is the coverage of its shapes: full alpha, no strokes, and for a + // luminance mask, white. + let opaque = |c: Rgba| c.a >= 0.999 && (alpha_mask || (c.r >= 0.996 && c.g >= 0.996 && c.b >= 0.996)); + let mut parts = Vec::new(); + let mut soft = false; + for it in content { + let e = it.el; + let ok = it.clips.is_empty() + && e.alpha >= 0.999 + && match &e.kind { + ElementKind::Shape(s) => s.stroke.is_none() && matches!(s.fill, Some(Paint::Solid(c)) if opaque(c)), + ElementKind::Text(t) => opaque(t.color), + ElementKind::Symbol { .. } => false, + }; + if !ok { + soft = true; + break; + } + parts.push(match &e.kind { + ElementKind::Shape(s) => mask_part(e.name.clone(), (*s.path).clone(), e.transform, s.fill_rule), + _ => e, + }); + } + if soft { + self.report.skip("soft, faded or coloured masks (drawn unmasked)"); + return Some(Vec::new()); + } + let area = mask_part(String::new(), Path::rect(rect.min.x, rect.min.y, rect.width(), rect.height()), *m, FillRule::NonZero); + Some(vec![Region::new(format!("mask:{target:p}:{:?}", content_m.m), id, parts), Region::new(format!("maskarea:{target:p}:{:?}:{rect:?}", m.m), id, vec![area])]) + } + + /// What an item's clips come to (combinations are cached by key; `None` = hidden). + fn effective(&mut self, it: &Item, cache: &mut HashMap>>) -> Effective { + let b = element_bounds(&it.el); + let mut keep: Vec> = Vec::new(); + for r in &it.clips { + if r.parts.is_empty() || r.bounds.intersect(&b).is_empty() { + return Effective::Hidden; + } + if r.contains(&b) || keep.iter().any(|k| k.key == r.key) { + continue; + } + keep.push(r.clone()); + } + // A convex region holding another region whole cuts nothing more. + let mut i = 0; + while keep.len() > 1 && i < keep.len() { + let holds = keep.get(i).is_some_and(|r| keep.iter().enumerate().any(|(j, o)| j != i && r.contains(&o.bounds))); + if holds { + keep.remove(i); + } else { + i += 1; + } + } + if keep.len() <= 1 { + return keep.pop().map_or(Effective::Unclipped, Effective::Masked); + } + let key = keep.iter().map(|r| r.key.as_str()).collect::>().join("&"); + let combined = match cache.get(&key) { + Some(c) => c.clone(), + None => { + let (curved, convex): (Vec>, Vec>) = keep.into_iter().partition(|r| r.convex.is_none()); + if curved.len() > 1 { + self.report.skip("curved clips inside curved clips (drawn with the inner one)"); + } + let mut rest = convex.into_iter(); + let base = match curved.first() { + Some(c) => Some(c.clone()), + None => rest.next(), + }; + let r = base.map(|base| rest.fold(base, |acc, c| acc.intersect(&c))).filter(|r| !r.parts.is_empty()); + cache.insert(key, r.clone()); + r + } + }; + match combined { + Some(r) if !r.bounds.intersect(&b).is_empty() => Effective::Masked(r), + _ => Effective::Hidden, + } + } + + /// The drawing as layers, bottom first: runs of items with the same mask. + pub(crate) fn layers(&mut self) -> Vec { + let items = std::mem::take(&mut self.items); + let mut cache = HashMap::new(); + let mut runs: Vec<(Option>, Vec)> = Vec::new(); + let mut masks = 0usize; + for it in items { + let mut region = match self.effective(&it, &mut cache) { + Effective::Hidden => continue, + Effective::Unclipped => None, + Effective::Masked(r) => Some(r), + }; + let same = |run: &(Option>, Vec), r: &Option>| match (&run.0, r) { + (None, None) => true, + (Some(a), Some(b)) => a.key == b.key, + _ => false, + }; + if !runs.last().is_some_and(|run| same(run, ®ion)) && region.is_some() { + if masks >= MAX_MASKS { + self.report.skip("clip paths and masks past 250 per drawing (drawn unclipped)"); + region = None; + } else { + masks += 1; + } + } + match runs.last_mut() { + Some(run) if same(run, ®ion) => run.1.push(it.el), + _ => runs.push((region, vec![it.el])), + } + } + runs.into_iter().map(|(r, elements)| ImportedLayer { mask: r.map(|r| ImportedMask { name: r.name.clone(), elements: r.parts.clone() }), elements }).collect() + } +} diff --git a/crates/svg/src/clip_tests.rs b/crates/svg/src/clip_tests.rs new file mode 100644 index 00000000..9a95aca4 --- /dev/null +++ b/crates/svg/src/clip_tests.rs @@ -0,0 +1,184 @@ +//! Clip paths and masks → mask layers (ADR 0021), on self-authored drawings. + +use super::*; + +fn imp(svg: &str) -> SvgImport { + match import_with_fonts(svg.as_bytes(), &Fonts::from_faces(Vec::new())) { + Ok(i) => i, + Err(e) => panic!("{e}: {svg}"), + } +} + +fn names(l: &ImportedLayer) -> Vec<&str> { + l.elements.iter().map(|e| e.name.as_str()).collect() +} + +fn path_of(e: &ImportedElement) -> Path { + match &e.kind { + ElementKind::Shape(s) => s.path.transformed(&e.transform), + other => panic!("not a shape: {other:?}"), + } +} + +/// Whether drawing-space point `p` is inside the mask layer's fills. +fn in_mask(m: &ImportedMask, p: Vec2) -> bool { + m.elements.iter().any(|e| match &e.kind { + ElementKind::Shape(s) => s.path.contains(p, &e.transform, s.fill_rule), + _ => false, + }) +} + +#[test] +fn a_clipped_group_becomes_a_masked_layer_under_its_mask() { + let i = imp(r##" + + + + + "##); + assert_eq!(i.layers.len(), 3, "{:?}", i.layers); + assert!(i.layers[0].mask.is_none() && i.layers[2].mask.is_none()); + assert_eq!((names(&i.layers[0]), names(&i.layers[1]), names(&i.layers[2])), (vec!["bg"], vec!["a", "b"], vec!["top"])); + let mask = i.layers[1].mask.as_ref().expect("masked"); + assert_eq!(mask.name, "round"); + assert_eq!(mask.elements.len(), 1); + assert!(in_mask(mask, Vec2::new(50.0, 50.0)) && !in_mask(mask, Vec2::new(5.0, 5.0))); + let b = path_of(&mask.elements[0]).bounds(); + assert!((b.min.x - 10.0).abs() < 1e-3 && (b.max.x - 90.0).abs() < 1e-3, "{b:?}"); + // The artwork keeps its paint and stroke; the mask's own artwork is a plain fill. + assert!(matches!(&i.layers[1].elements[0].kind, ElementKind::Shape(s) if s.stroke.is_some())); + assert!(i.report.skipped.is_empty(), "{:?}", i.report); + assert_eq!(i.elements().count(), 4, "mask artwork isn't drawn"); +} + +#[test] +fn clips_that_cut_nothing_go_and_clips_that_hide_everything_drop_the_artwork() { + // A frame clip around the whole drawing (as design tools export) changes nothing. + let i = imp(r##" + + + + + + + + "##); + assert_eq!(i.layers.len(), 1, "{:?}", i.layers); + assert!(i.layers[0].mask.is_none()); + assert_eq!(names(&i.layers[0]), ["a", "kept"]); + assert_eq!(i.report.skipped.get("references to missing clip paths (drawn unclipped)"), Some(&1)); +} + +#[test] +fn clips_inside_clips_intersect_exactly() { + // A circle clip inside a band clip: the mask is the circle cut to the band, still curved. + let i = imp(r##" + + + + "##); + assert_eq!(i.layers.len(), 2, "{:?}", i.layers); + let (outer, inner) = (i.layers[0].mask.as_ref().unwrap(), i.layers[1].mask.as_ref().unwrap()); + assert_eq!((outer.name.as_str(), inner.name.as_str()), ("band", "disc")); + let p = path_of(&inner.elements[0]); + assert!(p.cmds.iter().any(|c| matches!(c, anicraft_geom::PathCmd::CubicTo(..))), "the arcs stay curves"); + let b = p.bounds(); + assert!(b.min.y >= 40.0 - 1e-3 && b.max.y <= 80.0 + 1e-3 && b.min.x >= 20.0 - 1e-3 && b.max.x <= 100.0 + 1e-3, "{b:?}"); + assert!(in_mask(inner, Vec2::new(60.0, 60.0)) && !in_mask(inner, Vec2::new(60.0, 30.0)) && !in_mask(inner, Vec2::new(150.0, 60.0))); + // Two curved clips can't be intersected exactly: one is kept, and the report says so. + let two = imp(r##" + + + + "##); + assert_eq!(two.layers.len(), 1); + assert_eq!(two.report.skipped.get("curved clips inside curved clips (drawn with the inner one)"), Some(&1)); +} + +#[test] +fn bounding_box_units_and_transforms_place_the_clip() { + let i = imp(r##" + + + + + "##); + assert_eq!(i.layers.len(), 2); + let oval = path_of(&i.layers[0].mask.as_ref().unwrap().elements[0]).bounds(); + assert!((oval.min.x - 10.0).abs() < 1e-3 && (oval.max.x - 110.0).abs() < 1e-3 && (oval.min.y - 10.0).abs() < 1e-3 && (oval.max.y - 60.0).abs() < 1e-3, "{oval:?}"); + // A userSpaceOnUse clip lives in the space of the element it clips (inside its group). + let user = i.layers[1].mask.as_ref().unwrap(); + assert!(in_mask(user, Vec2::new(150.0, 155.0)) && !in_mask(user, Vec2::new(155.0, 150.0)), "rotated 45° about the group's origin"); +} + +#[test] +fn shapes_sharing_one_clip_share_one_mask_layer() { + // What SVG export writes: every masked path names the same clip. + let i = imp(r##" + + + + + + "##); + let shape: Vec<(bool, usize)> = i.layers.iter().map(|l| (l.mask.is_some(), l.elements.len())).collect(); + assert_eq!(shape, [(true, 2), (false, 1), (true, 1)], "a clip in another space is another mask"); +} + +#[test] +fn opaque_masks_become_mask_layers_and_soft_ones_are_reported() { + let i = imp(r##" + + + + + + + + + + + "##); + let shape: Vec<(Option<&str>, Vec<&str>)> = i.layers.iter().map(|l| (l.mask.as_ref().map(|m| m.name.as_str()), names(l))).collect(); + assert_eq!(shape, [(Some("white"), vec!["a"]), (Some("alpha"), vec!["b"]), (None, vec!["c", "d"]), (Some("tight"), vec!["e"])]); + let white = i.layers[0].mask.as_ref().unwrap(); + assert_eq!(white.elements.len(), 2, "the default mask region (bounding box + 10%) holds the content and cuts nothing"); + assert!(in_mask(white, Vec2::new(5.0, 5.0)) && in_mask(white, Vec2::new(50.0, 50.0)) && !in_mask(white, Vec2::new(90.0, 10.0))); + assert_eq!(i.report.skipped.get("soft, faded or coloured masks (drawn unmasked)"), Some(&2)); + // A mask region cuts the mask: the full-size rect becomes the middle quarter. + let tight = path_of(&i.layers[3].mask.as_ref().unwrap().elements[0]).bounds(); + assert_eq!(tight, Rect::new(25.0, 25.0, 75.0, 75.0)); +} + +#[test] +fn loops_and_floods_of_clips_stay_bounded() { + let start = std::time::Instant::now(); + let mut svg = String::from(r##" + + + + "##); + for k in 0..300 { + svg.push_str(&format!(r##""##, 5 + k % 90)); + } + svg.push_str(""); + let i = imp(&svg); + assert!(start.elapsed().as_secs() < 10, "{:?}", start.elapsed()); + assert!(i.report.skipped.contains_key("clip paths or masks that refer to themselves (ignored)"), "{:?}", i.report); + assert!(i.layers.iter().filter(|l| l.mask.is_some()).count() <= clip::MAX_MASKS); + assert!(i.report.skipped.contains_key("clip paths and masks past 250 per drawing (drawn unclipped)")); +} + +#[test] +fn the_fixture_drawing_comes_across_as_five_layers() { + let i = imp(include_str!("../fixtures/clips-masks-text.svg")); + let shape: Vec> = i.layers.iter().map(|l| l.mask.as_ref().map(|m| m.name.as_str())).collect(); + // The frame clip holds everything and goes; the sun and sea sit in the porthole, the red + // ball in the porthole cut to the band, the stripes under the mask. + assert_eq!(shape[..4], [None, Some("porthole"), Some("porthole"), Some("reveal")], "{shape:?}"); + assert_eq!(i.layers[1].elements.len(), 3); + assert_eq!(i.layers[3].elements.len(), 3); + let ball = path_of(&i.layers[2].mask.as_ref().unwrap().elements[0]).bounds(); + assert!(ball.min.y >= 95.0 - 1e-3 && ball.max.y <= 155.0 + 1e-3, "{ball:?}"); + assert_eq!(i.report.skipped.get("text (no fonts on this computer)"), Some(&2), "{:?}", i.report); +} diff --git a/crates/svg/src/lib.rs b/crates/svg/src/lib.rs index 0101cced..f13dc4aa 100644 --- a/crates/svg/src/lib.rs +++ b/crates/svg/src/lib.rs @@ -1,34 +1,55 @@ -//! AniCraft SVG import (layer L2): an SVG drawing into editable vector shapes. +//! AniCraft SVG import (layer L2): an SVG drawing into editable vector shapes and text. //! -//! Written from the public W3C SVG 1.1 / SVG 2 specifications. Supported: `svg`, `g`, `a`, -//! `switch`, `use`, `path`, `rect` (rounded), `circle`, `ellipse`, `line`, `polyline` and -//! `polygon`, read in document order. Styling comes from presentation attributes and `style=""` -//! declarations, with inheritance. Colours can be hex, `rgb()`/`rgba()`, CSS names, `none`, -//! `transparent` or `currentColor`. Also supported: `opacity`, `fill-opacity` and +//! Written from the public W3C SVG 1.1 / SVG 2 and CSS Masking specifications. Supported: `svg`, +//! `g`, `a`, `switch`, `use`, `path`, `rect` (rounded), `circle`, `ellipse`, `line`, `polyline` +//! and `polygon`, read in document order. Styling comes from presentation attributes and +//! `style=""` declarations, with inheritance. Colours can be hex, `rgb()`/`rgba()`, CSS names, +//! `none`, `transparent` or `currentColor`. Also supported: `opacity`, `fill-opacity` and //! `stroke-opacity`, `fill-rule`, `stroke-width` with units, the transform list (`matrix`, //! `translate`, `scale`, `rotate`, `skewX`, `skewY`), `viewBox` with `preserveAspectRatio`, and //! linear and radial gradients (both unit systems, `gradientTransform`, stops inherited through //! `href`). //! -//! What AniCraft cannot represent yet is reported, never guessed silently: text, images, -//! filters, clip paths and masks (drawn unclipped), patterns, dashes, style sheets, -//! reflected/repeated gradients and skewed gradient transforms (approximated). +//! **Clip paths and masks** (`clip`, ADR 0015) become AniCraft mask layers: the drawing comes +//! out as layers, bottom first, and artwork under a clip is a masked layer under a mask layer +//! holding the clip's shapes. A clip that cuts nothing is dropped, artwork it hides entirely is +//! left out, and clips inside clips are intersected exactly when all but one are convex +//! polygons. A `mask` comes across when its content is opaque (and white, for a luminance mask), +//! so that it is the coverage of its shapes. **Text** (`text`) becomes text blocks laid out by +//! `anicraft-text`, one per text chunk, with the missing-font reporting of Animate import +//! (ADR 0014). +//! +//! What AniCraft cannot represent yet is reported, never guessed silently: images, filters, +//! soft masks, patterns, dashes, style sheets, text on a path, reflected/repeated gradients and +//! skewed gradient transforms (approximated). #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use anicraft_doc::{GradientStop, Paint, Rgba, Shape, Stroke}; +use anicraft_doc::{ElementKind, GradientStop, Paint, Rgba, Shape, Stroke}; 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; -use std::collections::{BTreeMap, HashMap}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; +use std::rc::Rc; use std::sync::Arc; +mod clip; +mod text; + +#[cfg(test)] +mod clip_tests; #[cfg(test)] mod tests; +#[cfg(test)] +mod text_tests; /// Most shapes read from one file. pub const MAX_SHAPES: usize = 200_000; const MAX_DEPTH: usize = 64; const MAX_USE_DEPTH: usize = 16; +/// Most elements visited while reading one file. Masks draw their content again, so this, not +/// the file's size, bounds the work. +const MAX_VISITS: usize = 2_000_000; #[derive(Debug, thiserror::Error)] pub enum SvgError { @@ -38,35 +59,66 @@ pub enum SvgError { NotSvg(String), } -/// What could not come across, by kind ("2 text elements"). +/// What could not come across, by kind ("2 images"), and the fonts the text asks for that +/// aren't on this computer. #[derive(Clone, Debug, Default, PartialEq)] pub struct Report { pub skipped: BTreeMap, + /// Font families the drawing's text asks for that aren't on this computer. + pub missing_fonts: BTreeSet, + /// The family that text was laid out in instead. + pub fallback_font: Option, } impl Report { fn skip(&mut self, what: &str) { *self.skipped.entry(what.to_string()).or_default() += 1; } - /// One line for a status bar. + /// One line for a status bar: "Imported. Not yet supported: 2 images. Fonts not on this + /// computer, drawn in Inter: Futura." pub fn summary(&self) -> String { - if self.skipped.is_empty() { + if self.skipped.is_empty() && self.missing_fonts.is_empty() { return "Imported everything in the drawing.".into(); } - let parts: Vec = self.skipped.iter().map(|(k, n)| format!("{n} {k}")).collect(); - format!("Imported. Not yet supported: {}.", parts.join(", ")) + let mut out = String::from("Imported."); + if !self.skipped.is_empty() { + let parts: Vec = self.skipped.iter().map(|(k, n)| format!("{n} {k}")).collect(); + out.push_str(&format!(" Not yet supported: {}.", parts.join(", "))); + } + if !self.missing_fonts.is_empty() { + let names: Vec<&str> = self.missing_fonts.iter().map(String::as_str).collect(); + let instead = self.fallback_font.as_deref().map(|f| format!(", drawn in {f}")).unwrap_or_default(); + out.push_str(&format!(" Fonts not on this computer{instead}: {}.", names.join(", "))); + } + out } } -/// One shape, ready to become an element: its path in local coordinates, the local → drawing -/// transform, and the opacity of the shape and its groups. +/// One shape or text block, ready to become an element: its geometry in local coordinates, +/// the local → drawing transform, and the opacity of the element and its groups. #[derive(Clone, Debug)] -pub struct ImportedShape { +pub struct ImportedElement { /// The element's `id`, if it had one. pub name: String, pub transform: Affine, pub alpha: f32, - pub shape: Shape, + /// A shape or a text block. + pub kind: ElementKind, +} + +/// The artwork of a mask layer: its fills make the mask (ADR 0010). +#[derive(Clone, Debug)] +pub struct ImportedMask { + /// The clip path's or mask's `id`, if it had one. + pub name: String, + pub elements: Vec, +} + +/// Artwork drawn together on one layer, bottom first; masked by `mask` when there is one. +#[derive(Clone, Debug)] +pub struct ImportedLayer { + pub mask: Option, + pub elements: Vec, } /// An imported drawing. Coordinates are SVG user units (CSS pixels) of the drawing, with the @@ -75,13 +127,42 @@ pub struct ImportedShape { pub struct SvgImport { pub width: f32, pub height: f32, - pub shapes: Vec, + /// Bottom layer first. A drawing without clips or masks is one unmasked layer. + pub layers: Vec, pub report: Report, } -/// Reads an SVG document. +impl SvgImport { + /// A drawing of these elements on one layer. + pub fn single(width: f32, height: f32, elements: Vec) -> SvgImport { + SvgImport { width, height, layers: vec![ImportedLayer { mask: None, elements }], report: Report::default() } + } + /// Every element that draws (not mask artwork), bottom first. + pub fn elements(&self) -> impl Iterator { + self.layers.iter().flat_map(|l| l.elements.iter()) + } + /// Whether nothing in the drawing could be imported. + pub fn is_empty(&self) -> bool { + self.layers.iter().all(|l| l.elements.is_empty()) + } +} + +/// Elements whose character data keeps its place among their children (SVG text content). +const TEXT_CONTENT: &[&str] = &["text", "tspan", "a", "textPath"]; + +/// Reads an SVG document, laying any text out with this computer's fonts. pub fn import(bytes: &[u8]) -> Result { - let root = anicraft_xml::parse(bytes)?; + import_from(bytes, None) +} + +/// Reads an SVG document, laying text out with `fonts` (tests, and hosts with their own font +/// library). +pub fn import_with_fonts(bytes: &[u8], fonts: &Fonts) -> Result { + import_from(bytes, Some(fonts)) +} + +fn import_from(bytes: &[u8], fonts: Option<&Fonts>) -> Result { + let root = anicraft_xml::parse_mixed(bytes, TEXT_CONTENT)?; if local(&root.name) != "svg" { return Err(SvgError::NotSvg(root.name.clone())); } @@ -92,14 +173,34 @@ pub fn import(bytes: &[u8]) -> Result { let fallback = vb.map_or((300.0, 150.0), |r| (r.width(), r.height())); let size = |key: &str, d: f32| root.attr(key).and_then(|v| length(v, d)).filter(|v| *v > 0.0).unwrap_or(d); let (w, h) = (size("width", fallback.0), size("height", fallback.1)); - let mut b = Builder { ids, report: Report::default(), shapes: Vec::new(), viewport: vb.map_or((w, h), |r| (r.width(), r.height())) }; + let mut b = Builder { + ids, + report: Report::default(), + items: Vec::new(), + viewport: vb.map_or((w, h), |r| (r.width(), r.height())), + fonts, + faces: HashMap::new(), + visits: 0, + resolving: Vec::new(), + }; let base = match vb { Some(r) => view_box_transform(r, w, h, root.attr("preserveAspectRatio").unwrap_or("")), None => Affine::IDENTITY, }; let style = Style::default().with(&root, &mut b.report); b.children(&root, &base, &style, 1.0, 0, 0); - Ok(SvgImport { width: w, height: h, shapes: b.shapes, report: b.report }) + let layers = b.layers(); + Ok(SvgImport { width: w, height: h, layers, report: b.report }) +} + +/// The element's `id`, as an element name. +fn name_of(el: &X) -> String { + el.attr("id").unwrap_or("").chars().take(128).collect() +} + +/// Whether `visibility` hides the element. +fn hidden(d: &[(String, String)]) -> bool { + get(d, "visibility").is_some_and(|v| v == "hidden" || v == "collapse") } /// An element name without its namespace prefix (`svg:path` → `path`). @@ -347,16 +448,35 @@ fn paint_spec(v: &str) -> Option { color(v).map(PaintSpec::Color) } +/// Where a text chunk sits relative to its position (`text-anchor`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Anchor { + #[default] + Start, + Middle, + End, +} + /// Inherited presentation properties. #[derive(Clone, Debug)] struct Style { fill: PaintSpec, fill_opacity: f32, fill_rule: FillRule, + clip_rule: FillRule, stroke: PaintSpec, stroke_opacity: f32, stroke_width: f32, current: Rgba, + /// The CSS `font-family` list, as written. + font_family: String, + font_size: f32, + bold: bool, + italic: bool, + anchor: Anchor, + letter_spacing: f32, + /// `xml:space="preserve"`: keep every space. + preserve: bool, } impl Default for Style { @@ -365,20 +485,29 @@ impl Default for Style { fill: PaintSpec::Color(Rgba::BLACK), fill_opacity: 1.0, fill_rule: FillRule::NonZero, + clip_rule: FillRule::NonZero, stroke: PaintSpec::None, stroke_opacity: 1.0, stroke_width: 1.0, current: Rgba::BLACK, + font_family: String::new(), + font_size: 16.0, + bold: false, + italic: false, + anchor: Anchor::Start, + letter_spacing: 0.0, + preserve: false, } } } /// An element's declarations: presentation attributes, overridden by `style=""`. fn declarations(el: &X) -> Vec<(String, String)> { - const KEYS: [&str; 16] = [ + const KEYS: &[&str] = &[ "fill", "fill-opacity", "fill-rule", + "clip-rule", "stroke", "stroke-opacity", "stroke-width", @@ -390,8 +519,17 @@ fn declarations(el: &X) -> Vec<(String, String)> { "filter", "clip-path", "mask", + "mask-type", "stop-color", "stop-opacity", + "font-family", + "font-size", + "font-weight", + "font-style", + "text-anchor", + "letter-spacing", + "text-decoration", + "writing-mode", ]; let mut out: Vec<(String, String)> = KEYS.iter().filter_map(|k| el.attr(k).map(|v| (k.to_string(), v.trim().to_string()))).collect(); if let Some(style) = el.attr("style") { @@ -419,6 +557,26 @@ fn opacity(v: &str) -> Option { x.is_finite().then(|| x.clamp(0.0, 1.0)) } +/// A `font-size`: a keyword, a length, or relative to the parent's size (`em`, `ex`, `%`). +fn font_size(v: &str, parent: f32) -> Option { + let v = v.trim(); + let keyword = match v { + "xx-small" => Some(9.0), + "x-small" => Some(10.0), + "small" => Some(13.0), + "medium" => Some(16.0), + "large" => Some(18.0), + "x-large" => Some(24.0), + "xx-large" => Some(32.0), + "larger" => Some(parent * 1.2), + "smaller" => Some(parent / 1.2), + _ => None, + }; + let rel = |suffix: &str, k: f32| v.strip_suffix(suffix).and_then(|n| n.trim().parse::().ok()).map(|n| n * k); + let size = keyword.or_else(|| rel("em", parent)).or_else(|| rel("ex", parent * 0.5)).or_else(|| rel("%", parent / 100.0)).or_else(|| length(v, parent))?; + size.is_finite().then(|| size.clamp(0.0, 2000.0)) +} + impl Style { /// This style inherited by `el`, with `el`'s own declarations applied. fn with(&self, el: &X, report: &mut Report) -> Style { @@ -442,9 +600,53 @@ impl Style { if let Some(w) = get(&d, "stroke-width").and_then(|v| length(v, 100.0)).filter(|w| *w >= 0.0) { s.stroke_width = w; } - match get(&d, "fill-rule") { - Some("evenodd") => s.fill_rule = FillRule::EvenOdd, - Some("nonzero") => s.fill_rule = FillRule::NonZero, + let rule = |v: Option<&str>, old: FillRule| match v { + Some("evenodd") => FillRule::EvenOdd, + Some("nonzero") => FillRule::NonZero, + _ => old, + }; + s.fill_rule = rule(get(&d, "fill-rule"), s.fill_rule); + s.clip_rule = rule(get(&d, "clip-rule"), s.clip_rule); + if let Some(f) = get(&d, "font-family").filter(|f| !f.is_empty() && *f != "inherit") { + s.font_family = f.chars().take(512).collect(); + } + if let Some(z) = get(&d, "font-size").and_then(|v| font_size(v, self.font_size)) { + s.font_size = z; + } + match get(&d, "font-weight") { + Some("bold" | "bolder") => s.bold = true, + Some("normal" | "lighter") => s.bold = false, + Some(n) => { + if let Ok(w) = n.trim().parse::() { + s.bold = w >= 600.0; + } + } + None => {} + } + match get(&d, "font-style") { + Some("italic" | "oblique") => s.italic = true, + Some("normal") => s.italic = false, + _ => {} + } + match get(&d, "text-anchor") { + Some("start") => s.anchor = Anchor::Start, + Some("middle") => s.anchor = Anchor::Middle, + Some("end") => s.anchor = Anchor::End, + _ => {} + } + match get(&d, "letter-spacing") { + Some("normal") => s.letter_spacing = 0.0, + Some(v) => { + let em = v.strip_suffix("em").and_then(|n| n.trim().parse::().ok()).map(|n| n * s.font_size); + if let Some(x) = em.or_else(|| length(v, s.font_size)).filter(|x| x.is_finite()) { + s.letter_spacing = x.clamp(-1000.0, 1000.0); + } + } + None => {} + } + match el.attr("xml:space") { + Some("preserve") => s.preserve = true, + Some("default") => s.preserve = false, _ => {} } if get(&d, "stroke-dasharray").is_some_and(|v| v != "none") { @@ -453,21 +655,34 @@ impl Style { if get(&d, "filter").is_some_and(|v| v != "none") { report.skip("filters"); } - if get(&d, "clip-path").is_some_and(|v| v != "none") || get(&d, "mask").is_some_and(|v| v != "none") { - report.skip("clip paths and masks (drawn unclipped)"); - } s } } // ----- building --------------------------------------------------------------------------------- +/// Something drawn, and the clips (clip paths and masks) of everything around it, innermost +/// first. The clips are resolved into layers at the end ([`Builder::layers`]). +struct Item { + el: ImportedElement, + clips: Vec>, +} + struct Builder<'a> { ids: HashMap<&'a str, &'a X>, report: Report, - shapes: Vec, + items: Vec, /// The size percentages refer to (the viewBox, or the drawing size). viewport: (f32, f32), + /// The fonts text is laid out with; this computer's, found on the first text. + fonts: Option<&'a Fonts>, + /// Font name → what it is on this computer, looked up once per name. + faces: HashMap, + /// Elements visited so far (see [`MAX_VISITS`]). + visits: usize, + /// The clip paths and masks being read, innermost last (a reference back to one of them is + /// a loop). + resolving: Vec<&'a X>, } impl<'a> Builder<'a> { @@ -478,7 +693,14 @@ impl<'a> Builder<'a> { } fn node(&mut self, el: &'a X, parent: &Affine, inherited: &Style, alpha: f32, depth: usize, uses: usize) { - if depth > MAX_DEPTH || self.shapes.len() >= MAX_SHAPES { + if depth > MAX_DEPTH || self.items.len() >= MAX_SHAPES { + return; + } + self.visits += 1; + if self.visits > MAX_VISITS { + if self.visits == MAX_VISITS + 1 { + self.report.skip("parts of a drawing too complex to read (left out)"); + } return; } let d = declarations(el); @@ -489,14 +711,11 @@ impl<'a> Builder<'a> { // Containers that never draw by themselves. match name { "defs" | "linearGradient" | "radialGradient" | "stop" | "symbol" | "metadata" | "title" | "desc" | "clipPath" | "mask" | "marker" | "pattern" | "filter" | "script" => return, + anicraft_xml::TEXT_NODE => return, "style" => { self.report.skip("style sheets (inline styles are read)"); return; } - "text" => { - self.report.skip("text elements"); - return; - } "image" => { self.report.skip("images"); return; @@ -510,6 +729,16 @@ impl<'a> Builder<'a> { let style = inherited.with(el, &mut self.report); let alpha = alpha * get(&d, "opacity").and_then(opacity).unwrap_or(1.0); let m = parent.mul(&el.attr("transform").map_or(Affine::IDENTITY, transform)); + let start = self.items.len(); + self.draw(el, name, &d, &m, &style, alpha, depth, uses); + if self.items.len() > start { + self.clip(&d, &m, start, depth); + } + } + + /// What `el` draws, into `items`. + #[allow(clippy::too_many_arguments)] + fn draw(&mut self, el: &'a X, name: &str, d: &[(String, String)], m: &Affine, style: &Style, alpha: f32, depth: usize, uses: usize) { match name { "svg" if depth > 0 => { // A nested viewport: x/y offset, then its own viewBox. @@ -523,9 +752,9 @@ impl<'a> Builder<'a> { None => Affine::IDENTITY, }; let m = m.mul(&Affine::translate(x, y)).mul(&inner); - self.children(el, &m, &style, alpha, depth, uses); + self.children(el, &m, style, alpha, depth, uses); } - "svg" | "g" | "a" | "switch" => self.children(el, &m, &style, alpha, depth, uses), + "svg" | "g" | "a" | "switch" => self.children(el, m, style, alpha, depth, uses), "use" => { let href = el.attr("href").or_else(|| el.attr("xlink:href")).unwrap_or("").trim_start_matches('#'); let Some(target) = self.ids.get(href).copied() else { @@ -544,29 +773,42 @@ impl<'a> Builder<'a> { let inner = style.with(target, &mut self.report); self.children(target, &m, &inner, alpha, depth, uses + 1); } else { - self.node(target, &m, &style, alpha, depth + 1, uses + 1); + self.node(target, &m, style, alpha, depth + 1, uses + 1); + } + } + "text" => { + if hidden(d) { + return; + } + for el in self.text(el, m, style, alpha) { + self.items.push(Item { el, clips: Vec::new() }); } } _ => { let Some((path, closed_shape)) = self.geometry(el, name) else { return }; - if !m.is_finite() || path.is_empty() { - return; - } - if get(&d, "visibility").is_some_and(|v| v == "hidden" || v == "collapse") { + if !m.is_finite() || path.is_empty() || hidden(d) { return; } let bounds = path.bounds(); - let fill = if closed_shape { self.paint(&style.fill, style.fill_opacity, &style, &bounds) } else { None }; - let stroke = self.stroke(&style, &bounds); + let fill = if closed_shape { self.paint(&style.fill, style.fill_opacity, style, &bounds) } else { None }; + let stroke = self.stroke(style, &bounds); if fill.is_none() && stroke.is_none() { return; } - self.shapes.push(ImportedShape { - name: el.attr("id").unwrap_or("").chars().take(128).collect(), - transform: m, - alpha, - shape: Shape { path: Arc::new(path), fill, stroke, fill_rule: style.fill_rule }, - }); + let shape = Shape { path: Arc::new(path), fill, stroke, fill_rule: style.fill_rule }; + self.items.push(Item { el: ImportedElement { name: name_of(el), transform: *m, alpha, kind: ElementKind::Shape(shape) }, clips: Vec::new() }); + } + } + } + + /// The fonts to lay text out with: the ones given, else this computer's (scanned once). + fn fonts(&mut self) -> &'a Fonts { + match self.fonts { + Some(f) => f, + None => { + let f = Fonts::get(); + self.fonts = Some(f); + f } } } diff --git a/crates/svg/src/tests.rs b/crates/svg/src/tests.rs index b200be9b..40bb4e23 100644 --- a/crates/svg/src/tests.rs +++ b/crates/svg/src/tests.rs @@ -1,10 +1,36 @@ use super::*; -fn imp(svg: &str) -> SvgImport { - match import(svg.as_bytes()) { +/// An imported shape, flattened out of its layer. +#[derive(Clone, Debug)] +struct ImportedShape { + name: String, + transform: Affine, + alpha: f32, + shape: Shape, +} + +/// An import whose layers are flattened into its shapes. +#[derive(Clone, Debug)] +struct Flat { + width: f32, + height: f32, + shapes: Vec, + report: Report, +} + +fn imp(svg: &str) -> Flat { + let i = match import_with_fonts(svg.as_bytes(), &Fonts::from_faces(Vec::new())) { Ok(i) => i, Err(e) => panic!("{e}: {svg}"), - } + }; + let shapes = i + .elements() + .filter_map(|e| match &e.kind { + ElementKind::Shape(s) => Some(ImportedShape { name: e.name.clone(), transform: e.transform, alpha: e.alpha, shape: s.clone() }), + _ => None, + }) + .collect(); + Flat { width: i.width, height: i.height, shapes, report: i.report } } fn solid(s: &ImportedShape) -> Rgba { @@ -82,7 +108,7 @@ fn gradients_in_both_unit_systems_with_inherited_stops() { "##); - let i = SvgImport { shapes: i.shapes[1..].to_vec(), ..i }; + let i = Flat { shapes: i.shapes[1..].to_vec(), ..i }; match &i.shapes[0].shape.fill { Some(Paint::Linear { start, end, stops }) => { assert_eq!((*start, *end), (Vec2::new(20.0, 10.0), Vec2::new(60.0, 10.0)), "bounding-box units map onto the shape"); @@ -121,7 +147,7 @@ fn use_references_and_reported_leftovers() { assert_eq!(first.transform.apply(Vec2::new(0.0, 0.0)), Vec2::new(10.0, 20.0)); assert_eq!(solid(first), Rgba::hex(0x123456)); assert_eq!(i.shapes.len(), 4, "the dot, the symbol's two rects and the plain rect"); - for k in ["text elements", "images", "references to missing elements", "dashed strokes (drawn solid)", "filters", "clip paths and masks (drawn unclipped)", "style sheets (inline styles are read)"] { + for k in ["text (no fonts on this computer)", "images", "references to missing elements", "dashed strokes (drawn solid)", "filters", "references to missing clip paths (drawn unclipped)", "style sheets (inline styles are read)"] { assert_eq!(i.report.skipped.get(k), Some(&1), "{k}: {:?}", i.report); } assert!(i.report.summary().starts_with("Imported. Not yet supported: ")); diff --git a/crates/svg/src/text.rs b/crates/svg/src/text.rs new file mode 100644 index 00000000..c3534cff --- /dev/null +++ b/crates/svg/src/text.rs @@ -0,0 +1,320 @@ +//! SVG text (`text`, `tspan`) → text blocks laid out by `anicraft-text` (ADR 0021). +//! +//! SVG places text in chunks: a chunk starts at the `text` element and at every `tspan` with +//! an absolute `x`, and runs on until the next one. Each chunk becomes one single-line text +//! block, placed by its baseline (`x`, `y`, plus a leading `dx`/`dy`) and its `text-anchor`. +//! An AniCraft block has one style, so a chunk whose pieces differ in style takes the style of +//! most of its visible characters, and the report counts it (as in ADR 0014). Whitespace is +//! collapsed as browsers do, unless `xml:space="preserve"`. + +use crate::{Anchor, Builder, ImportedElement, PaintSpec, Style, declarations, get, hidden, length, local, name_of}; +use anicraft_doc::{ElementKind, Paint, TextAlign, TextBlock}; +use anicraft_geom::{Affine, Rect}; +use anicraft_text::{Align, FaceMatch, Fonts, MAX_CHARS, TextError}; +use anicraft_xml::Element as X; +use std::sync::Arc; + +/// Most chunks read from one `text` element. +const MAX_CHUNKS: usize = 10_000; +/// Deepest nesting of `tspan`s read. +const MAX_TSPAN_DEPTH: usize = 32; + +/// A run of text that starts at one position. +struct Chunk { + x: f32, + y: f32, + anchor: Anchor, + pieces: Vec<(String, Style)>, + chars: usize, +} + +impl Chunk { + fn has_text(&self) -> bool { + self.pieces.iter().any(|(t, _)| !t.trim().is_empty()) + } +} + +/// What a `text` element used that AniCraft draws differently, reported once per element. +#[derive(Default)] +struct Flags { + per_char: bool, + rotated: bool, + on_path: bool, + decorated: bool, + vertical: bool, + cut: bool, +} + +/// Whether two pieces would be drawn the same. +fn same_look(a: &Style, b: &Style) -> bool { + a.font_family == b.font_family && a.font_size == b.font_size && a.bold == b.bold && a.italic == b.italic && a.fill == b.fill && a.fill_opacity == b.fill_opacity && a.letter_spacing == b.letter_spacing +} + +/// The CSS generic family a name stands for, as the device font `anicraft-text` knows. +fn generic(name: &str) -> Option<&'static str> { + match name.to_ascii_lowercase().as_str() { + "sans-serif" | "system-ui" | "ui-sans-serif" | "ui-rounded" | "-apple-system" | "blinkmacsystemfont" | "cursive" | "fantasy" => Some("_sans"), + "serif" | "ui-serif" => Some("_serif"), + "monospace" | "ui-monospace" => Some("_typewriter"), + _ => None, + } +} + +/// The names in a `font-family` list, unquoted. +fn families(css: &str) -> Vec { + css.split(',').map(|n| n.trim().trim_matches(['"', '\'']).trim().to_string()).filter(|n| !n.is_empty()).take(16).collect() +} + +/// Collapses whitespace across the chunks as browsers do: line breaks and tabs are spaces, +/// runs of spaces are one, and spaces at the start go. `xml:space="preserve"` keeps them. +fn collapse(chunks: &mut [Chunk]) { + let mut prev_space = true; + for c in chunks { + for (t, st) in &mut c.pieces { + let mut out = String::with_capacity(t.len()); + for ch in t.chars() { + let ch = if matches!(ch, '\n' | '\r' | '\t') { ' ' } else { ch }; + if st.preserve { + out.push(ch); + } else if ch == ' ' { + if !prev_space { + out.push(' '); + } + } else { + out.push(ch); + } + prev_space = ch == ' '; + } + *t = out; + } + } +} + +impl<'a> Builder<'a> { + /// The text blocks of a `text` element (whose own style is `style`), placed by `m`. + pub(crate) fn text(&mut self, el: &'a X, m: &Affine, style: &Style, alpha: f32) -> Vec { + let mut chunks: Vec = Vec::new(); + let mut flags = Flags::default(); + self.text_content(el, style, &mut chunks, &mut flags, 0); + collapse(&mut chunks); + let report = [ + (flags.per_char, "per-character text positions (ignored)"), + (flags.rotated, "rotated characters (drawn upright)"), + (flags.on_path, "text on a path"), + (flags.decorated, "underlined or struck-through text (lines left out)"), + (flags.vertical, "vertical text (drawn horizontal)"), + (flags.cut, "text cut to 100,000 characters per block"), + ]; + for (on, what) in report { + if on { + self.report.skip(what); + } + } + let mut out = Vec::new(); + for c in chunks { + if !c.has_text() { + continue; + } + // The style most of the visible characters have (the first on a tie). + let mut totals: Vec<(usize, usize)> = Vec::new(); + for (i, (t, st)) in c.pieces.iter().enumerate() { + let n = t.chars().filter(|ch| !ch.is_whitespace()).count(); + match totals.iter_mut().find(|(j, _)| c.pieces.get(*j).is_some_and(|(_, s)| same_look(s, st))) { + Some(e) => e.1 += n, + None => totals.push((i, n)), + } + } + let mut best: Option<(usize, usize)> = None; + for &(i, n) in &totals { + if best.is_none_or(|(_, b)| n > b) { + best = Some((i, n)); + } + } + if totals.iter().filter(|(_, n)| *n > 0).count() > 1 { + self.report.skip("text with mixed styles (drawn in its main style)"); + } + let Some((_, st)) = best.and_then(|(i, _)| c.pieces.get(i)) else { continue }; + let st = st.clone(); + let text: String = c.pieces.iter().map(|(t, _)| t.as_str()).collect(); + match self.text_block(text, &st, alpha) { + Ok(Some((block, ascent))) => { + let w = block.box_width; + let shift = match c.anchor { + Anchor::Start => 0.0, + Anchor::Middle => -w * 0.5, + Anchor::End => -w, + }; + let transform = m.mul(&Affine::translate(c.x + shift, c.y - ascent)); + if !transform.is_finite() { + continue; + } + let name = if out.is_empty() { name_of(el) } else { String::new() }; + let block_alpha = alpha; + let block = TextBlock { align: match c.anchor { Anchor::Start => TextAlign::Left, Anchor::Middle => TextAlign::Center, Anchor::End => TextAlign::Right }, ..block }; + out.push(ImportedElement { name, transform, alpha: block_alpha, kind: ElementKind::Text(Arc::new(block)) }); + } + Ok(None) => {} + Err(()) => break, + } + } + out + } + + /// Reads `el`'s positions and content into chunks. + fn text_content(&mut self, el: &'a X, style: &Style, chunks: &mut Vec, flags: &mut Flags, depth: usize) { + let (vw, vh) = self.viewport; + let list = |key: &str, reference: f32| -> Vec { el.attr(key).map(|v| v.split([' ', ',', '\t', '\n', '\r']).filter(|p| !p.is_empty()).filter_map(|p| length(p, reference)).collect()).unwrap_or_default() }; + let (xs, ys, dxs, dys) = (list("x", vw), list("y", vh), list("dx", vw), list("dy", vh)); + if xs.len() > 1 || ys.len() > 1 || dxs.len() > 1 || dys.len() > 1 { + flags.per_char = true; + } + flags.rotated |= el.attr("rotate").is_some_and(|r| r.split([' ', ',']).any(|v| v.trim().parse::().is_ok_and(|a| a != 0.0))); + let d = declarations(el); + flags.decorated |= get(&d, "text-decoration").is_some_and(|v| v != "none"); + flags.vertical |= get(&d, "writing-mode").is_some_and(|v| v.starts_with("tb") || v.starts_with("vertical")); + let root = depth == 0; + if root || !xs.is_empty() { + if chunks.len() >= MAX_CHUNKS { + flags.cut = true; + return; + } + let y = ys.first().copied().or_else(|| chunks.last().map(|c| c.y)).unwrap_or(0.0); + chunks.push(Chunk { x: xs.first().copied().unwrap_or(0.0), y, anchor: style.anchor, pieces: Vec::new(), chars: 0 }); + } else if let Some(&y) = ys.first() { + // A new line without a new x continues after the text before it, which only the + // layout knows: kept on the line when there is text already. + match chunks.last_mut() { + Some(c) if !c.has_text() => c.y = y, + _ => flags.per_char = true, + } + } + let (dx, dy) = (dxs.first().copied().unwrap_or(0.0), dys.first().copied().unwrap_or(0.0)); + if dx != 0.0 || dy != 0.0 { + match chunks.last_mut() { + Some(c) if !c.has_text() => { + c.x += dx; + c.y += dy; + } + _ => flags.per_char = true, + } + } + for child in &el.children { + match local(&child.name) { + anicraft_xml::TEXT_NODE => { + let Some(c) = chunks.last_mut() else { continue }; + let room = MAX_CHARS.saturating_sub(c.chars); + let n = child.text.chars().count(); + if n > room { + flags.cut = true; + } + c.chars += n.min(room); + c.pieces.push((child.text.chars().take(room).collect(), style.clone())); + } + "tspan" | "a" => { + let cd = declarations(child); + if get(&cd, "display") == Some("none") || hidden(&cd) || depth >= MAX_TSPAN_DEPTH { + continue; + } + let st = style.with(child, &mut self.report); + self.text_content(child, &st, chunks, flags, depth + 1); + } + "textPath" => flags.on_path = true, + _ => {} + } + } + } + + /// Lays one chunk out: the block (aligned left, at the origin) and its first baseline. + /// `Ok(None)` draws nothing; `Err` means no text can be laid out at all. + fn text_block(&mut self, text: String, st: &Style, alpha: f32) -> Result, ()> { + if st.font_size <= 0.0 || alpha <= 0.0 { + return Ok(None); + } + let unit = Rect::new(0.0, 0.0, 1.0, 1.0); + let color = match self.paint(&st.fill, st.fill_opacity, st, &unit) { + None => { + if st.stroke != PaintSpec::None { + self.report.skip("outlined text without a fill (left out)"); + } + return Ok(None); + } + Some(Paint::Solid(c)) => c, + Some(other) => { + self.report.skip("gradient-filled text (drawn in one colour)"); + other.primary_color() + } + }; + if st.stroke != PaintSpec::None && st.stroke_width > 0.0 { + self.report.skip("strokes on text (left out)"); + } + let fonts = self.fonts(); + let face = self.face(fonts, &st.font_family); + let style = anicraft_text::Style { + family: face.family.clone().unwrap_or_default(), + size: st.font_size, + bold: st.bold || face.bold, + italic: st.italic || face.italic, + align: Align::Left, + letter_spacing: st.letter_spacing, + line_spacing: 0.0, + width: None, + }; + let layout = match fonts.layout(&text, &style) { + Ok(l) => l, + Err(TextError::NoFonts) => { + self.report.skip("text (no fonts on this computer)"); + return Err(()); + } + Err(TextError::TooLong) => { + self.report.skip("text cut to 100,000 characters per block"); + return Ok(None); + } + }; + // A family that isn't installed falls back to the default, as the text engine does + // (ADR 0012), and the report names it. + if face.family.is_none() && !face.wanted.is_empty() { + self.report.missing_fonts.insert(face.wanted.clone()); + self.report.fallback_font.get_or_insert_with(|| layout.family.clone()); + } + let ascent = layout.ascent; + let block = TextBlock { + text, + font: layout.family, + size: style.size, + bold: style.bold, + italic: style.italic, + color, + align: TextAlign::Left, + letter_spacing: style.letter_spacing, + line_spacing: 0.0, + width: None, + outline: Arc::new(layout.outline), + box_width: layout.width, + box_height: layout.height, + }; + Ok(Some((block, ascent))) + } + + /// The installed face for a `font-family` list: its first installed family, or (when none + /// is) the first named family, uninstalled, for the report. No family is serif, as in + /// browsers. + fn face(&mut self, fonts: &Fonts, css: &str) -> FaceMatch { + let mut names = families(css); + if names.is_empty() { + names.push("serif".into()); + } + let mut first: Option = None; + for n in &names { + let key = generic(n).unwrap_or(n); + let m = self.faces.entry(key.to_string()).or_insert_with(|| fonts.find_face(key)).clone(); + if m.family.is_some() { + return m; + } + if first.is_none() && generic(n).is_none() { + first = Some(m); + } + } + // Only generic families, none installed: the default family, nothing to report. + first.unwrap_or(FaceMatch { family: None, wanted: String::new(), bold: false, italic: false }) + } +} diff --git a/crates/svg/src/text_tests.rs b/crates/svg/src/text_tests.rs new file mode 100644 index 00000000..5c9b0471 --- /dev/null +++ b/crates/svg/src/text_tests.rs @@ -0,0 +1,117 @@ +//! SVG text → text blocks (ADR 0021), laid out with this computer's fonts. + +use super::*; +use anicraft_doc::{TextAlign, TextBlock}; + +/// This computer's fonts, or `None` (and the test passes) on one without fonts. +fn fonts() -> Option<&'static Fonts> { + let f = Fonts::get(); + f.resolve("").map(|_| f) +} + +fn texts(svg: &str, fonts: &Fonts) -> (Vec<(ImportedElement, TextBlock)>, Report) { + let i = match import_with_fonts(svg.as_bytes(), fonts) { + Ok(i) => i, + Err(e) => panic!("{e}"), + }; + let t = i + .elements() + .filter_map(|e| match &e.kind { + ElementKind::Text(t) => Some((e.clone(), (**t).clone())), + _ => None, + }) + .collect(); + (t, i.report) +} + +/// Drawing-space bounds of a block's glyphs. +fn ink(e: &ImportedElement, t: &TextBlock) -> Rect { + t.outline.bounds().transformed(&e.transform) +} + +#[test] +fn text_sits_on_its_baseline_in_its_style() { + let Some(fonts) = fonts() else { return }; + let (t, report) = texts(r##"Hello"##, fonts); + assert_eq!(t.len(), 1); + let (e, b) = &t[0]; + assert_eq!((e.name.as_str(), b.text.as_str(), b.size, b.bold, b.italic, b.letter_spacing), ("title", "Hello", 24.0, true, false, 2.0)); + assert_eq!(b.color, Rgba::hex(0xff0000).with_alpha(0.5)); + assert_eq!(b.font, fonts.find_face("_sans").family.unwrap(), "the first installed family of the list"); + let r = ink(e, b); + assert!((r.max.y - 50.0).abs() < 1.5, "letters stand on the baseline: {r:?}"); + assert!(r.min.x >= 9.0 && r.min.x < 14.0, "{r:?}"); + assert!(report.missing_fonts.is_empty(), "a later family in the list is installed: {report:?}"); + assert!(report.skipped.is_empty(), "{report:?}"); +} + +#[test] +fn anchors_chunks_and_whitespace() { + let Some(fonts) = fonts() else { return }; + let (t, report) = texts( + r##" + Centred + title + Right + Line oneLine two + Mostly plain bold words + "##, + fonts, + ); + let words: Vec<&str> = t.iter().map(|(_, b)| b.text.as_str()).collect(); + assert_eq!(words, ["Centred title ", "Right", "Line one", "Line two", "Mostly plain bold words"]); + let (e, b) = &t[0]; + let c = ink(e, b).center().x; + assert!((c - 200.0).abs() < 2.0, "middle anchor centres the line: {c}"); + assert_eq!(b.align, TextAlign::Center); + let r = ink(&t[1].0, &t[1].1); + assert!((r.max.x - 390.0).abs() < 2.0 && t[1].1.align == TextAlign::Right, "end anchor: {r:?}"); + // Each positioned tspan is its own block, placed through the text's transform. + let (l1, l2) = (ink(&t[2].0, &t[2].1), ink(&t[3].0, &t[3].1)); + assert!((l1.max.y - 100.0).abs() < 5.0 && (l2.max.y - 124.0).abs() < 5.0, "{l1:?} {l2:?}"); + assert!(t[3].1.italic && !t[2].1.italic); + // A leading dx moves the chunk; the bold word is drawn in the main style and counted. + assert!(ink(&t[4].0, &t[4].1).min.x >= 14.0); + assert!(!t[4].1.bold); + assert_eq!(report.skipped.get("text with mixed styles (drawn in its main style)"), Some(&1), "{report:?}"); +} + +#[test] +fn missing_fonts_and_unsupported_text_are_reported() { + let Some(fonts) = fonts() else { return }; + let (t, report) = texts( + r##" + One + Two + Three + Four + Outline + + Tiny + "##, + fonts, + ); + assert_eq!(t.len(), 3, "{:?}", t.iter().map(|(_, b)| &b.text).collect::>()); + assert_eq!(report.missing_fonts.iter().map(String::as_str).collect::>(), ["Zz Missing Face"]); + assert!(fonts.families().contains(report.fallback_font.as_ref().unwrap())); + assert!(report.summary().contains("Fonts not on this computer, drawn in"), "{}", report.summary()); + for k in ["underlined or struck-through text (lines left out)", "per-character text positions (ignored)", "strokes on text (left out)", "text on a path", "outlined text without a fill (left out)"] { + assert_eq!(report.skipped.get(k), Some(&1), "{k}: {report:?}"); + } +} + +#[test] +fn text_can_be_a_clip_and_needs_fonts() { + let none = Fonts::from_faces(Vec::new()); + let (t, report) = texts(r#"Hi"#, &none); + assert!(t.is_empty()); + assert_eq!(report.skipped.get("text (no fonts on this computer)"), Some(&1)); + let Some(fonts) = fonts() else { return }; + let i = import_with_fonts( + br##"REVEAL"##, + fonts, + ) + .unwrap(); + let mask = i.layers.iter().find_map(|l| l.mask.as_ref()).expect("a mask layer"); + assert!(matches!(&mask.elements[0].kind, ElementKind::Text(b) if b.text == "REVEAL"), "the mask stays editable text"); +}