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 @@
+
+
+
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##"");
+ 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