From 3919a2858374bada1e6542f9cae3db50f701f6fb Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:55:27 +0100 Subject: [PATCH] svg: a scene in local coordinates, with fill rules and element ids (#778, #789) (#1859) * svg: a scene in local coordinates, with fill rules and element ids (#778, #789) Document::from_tree_local keeps every node in its own user space, with its transform relative to its parent, so an app can keep geometry editable apart from where it is placed (EffectCraft's shape layers). Paths now carry their fill rule, id and transform, and groups their id. from_tree is unchanged: segments, strokes and group transforms stay absolute, path transforms are the identity. * craft-svg: place local text and glyph groups in their own frames (#789) * svg: pattern paints carry their tile and content (#778, #789) (#1863) Paint::Pattern now holds the resolved tile: id, rect, transform and the content as scene nodes in tile space. Each pattern is converted once and shared by every use; content past the depth limit, or a pattern that refers back to itself, has none. In absolute scenes the tile transform maps to the document. * craft-svg: report scene-omitted group effects and unsupported elements (#789) (#1870) --- crates/svg/src/tree.rs | 37 ++ crates/svg/src/tree/document.rs | 457 ++++++++++++++++++------- crates/svg/src/tree/document_tests.rs | 349 +++++++++++++++++++ crates/svg/src/tree/primitive_tests.rs | 3 + 4 files changed, 715 insertions(+), 131 deletions(-) create mode 100644 crates/svg/src/tree/document_tests.rs diff --git a/crates/svg/src/tree.rs b/crates/svg/src/tree.rs index 99b6f73a4..ab04a3002 100644 --- a/crates/svg/src/tree.rs +++ b/crates/svg/src/tree.rs @@ -174,12 +174,49 @@ impl Preflight<'_> { self.depth } + /// The SVG elements in the document that the parsed tree leaves out, by name and count, + /// sorted by name: animation, scripts, embedded HTML and media, and text when this build + /// converts no text (neither `tree-text` nor `tree-render`). For an import's "not imported" notes. + pub fn unsupported_elements(&self) -> Vec<(&'static str, usize)> { + const SVG_NS: &str = "http://www.w3.org/2000/svg"; + let mut counts: std::collections::BTreeMap<&'static str, usize> = std::collections::BTreeMap::new(); + for node in self.xml.descendants().filter(roxmltree::Node::is_element) { + if !matches!(node.tag_name().namespace(), None | Some(SVG_NS)) { + continue; + } + if let Some(name) = UNSUPPORTED.iter().copied().find(|name| *name == node.tag_name().name()) { + *counts.entry(name).or_default() += 1; + } + } + counts.into_iter().collect() + } + /// Converts this already-checked XML into the configured usvg tree. pub fn parse(self, options: &usvg::Options<'_>) -> Result { usvg::Tree::from_xmltree(&self.xml, options).map_err(|e| Error::Parse(e.to_string())) } } +/// Elements the parsed tree never holds: usvg reads static content only, and text needs fonts. +const UNSUPPORTED: &[&str] = &[ + "animate", + "animateColor", + "animateMotion", + "animateTransform", + "audio", + "canvas", + "discard", + "foreignObject", + "iframe", + "script", + "set", + // usvg converts text when built with its `text` feature: `tree-text`, or `tree-render` + // through resvg. + #[cfg(not(any(feature = "tree-text", feature = "tree-render")))] + "text", + "video", +]; + /// Checks already-decoded SVG text once, retaining the parsed XML for both depth policy and tree conversion. pub fn preflight<'s>(svg: &'s str, limits: &Limits) -> Result, Error> { let preflight_limits = crate::preflight::Limits { diff --git a/crates/svg/src/tree/document.rs b/crates/svg/src/tree/document.rs index 838f62e98..19f594173 100644 --- a/crates/svg/src/tree/document.rs +++ b/crates/svg/src/tree/document.rs @@ -1,8 +1,12 @@ //! A format-neutral vector scene made from a bounded SVG tree. //! //! The scene preserves paths, groups, paints, transforms, opacity, strokes and image sources -//! without depending on an application's document model. Coordinates and stroke widths use the -//! SVG tree's CSS-pixel coordinate system. +//! without depending on an application's document model. +//! +//! [`Document::from_tree`] gives every coordinate and stroke width in the document's CSS pixels +//! ([`Coordinates::Absolute`]). [`Document::from_tree_local`] keeps each node in its own user +//! space with its transform relative to its parent ([`Coordinates::Local`]), for an app that +//! keeps a node's geometry editable apart from where it is placed. #[cfg(feature = "tree-render")] use super::draw::Refusal; @@ -18,9 +22,42 @@ pub struct Document { pub images: usize, /// True if nodes deeper than the requested depth were omitted. pub too_deep: bool, + /// The space segments, transforms, bounds and stroke widths are given in. + pub coordinates: Coordinates, + /// Group effects the scene flags ([`GroupFeatures`]) but doesn't carry, counted. + pub omitted: Omitted, source: Option>, } +/// How many groups have an effect the scene doesn't carry: an app that draws only the scene +/// draws them without it, and can say so. Elements usvg itself leaves out (animation, scripts…) +/// are listed by [`super::Preflight::unsupported_elements`]. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct Omitted { + /// Groups with `filter`. + pub filters: usize, + /// Groups with `clip-path`. + pub clip_paths: usize, + /// Groups with `mask`. + pub masks: usize, + /// Groups with a `mix-blend-mode` other than normal. + pub blends: usize, +} + +/// Where a scene's geometry is given. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Coordinates { + /// Document CSS pixels: path segments, stroke widths and dashes are already transformed, a + /// path's `transform` is the identity, and a group's or image's `transform` is its full + /// transform to the document. + #[default] + Absolute, + /// Each node in its own user space: path segments, stroke widths, dashes, gradients and + /// bounds are as the SVG gives them, and every `transform` maps the node into its parent + /// (the document for top-level nodes). + Local, +} + impl PartialEq for Document { fn eq(&self, other: &Self) -> bool { self.width == other.width @@ -28,6 +65,8 @@ impl PartialEq for Document { && self.nodes == other.nodes && self.images == other.images && self.too_deep == other.too_deep + && self.coordinates == other.coordinates + && self.omitted == other.omitted } } @@ -44,7 +83,16 @@ impl NodePath { /// A group or path in document order. #[derive(Clone, Debug, PartialEq)] pub enum Node { - Group { children: Vec, opacity: f32, transform: [f64; 6], bounds: [f64; 4], features: GroupFeatures, source_path: NodePath }, + Group { + children: Vec, + opacity: f32, + transform: [f64; 6], + bounds: [f64; 4], + features: GroupFeatures, + source_path: NodePath, + /// The element's `id`, empty when it has none. + id: String, + }, Path(Box), Image(Image), } @@ -80,13 +128,27 @@ pub enum ImageKind { Svg, } -/// A transformed path with its resolved fill and stroke. +/// A path with its resolved fill and stroke. #[derive(Clone, Debug, PartialEq)] pub struct Path { pub segments: Vec, pub fill: Option, + /// How the fill decides what is inside (`fill-rule`); `NonZero` when there is no fill. + pub fill_rule: FillRule, pub stroke: Option, pub source_path: NodePath, + /// The element's `id`, empty when it has none. + pub id: String, + /// Maps the segments into the parent ([`Coordinates`]); the identity in absolute scenes. + pub transform: [f64; 6], +} + +/// The `fill-rule` property. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum FillRule { + #[default] + NonZero, + EvenOdd, } impl Path { @@ -97,7 +159,7 @@ impl Path { } } -/// A path segment in CSS pixels after its absolute transform. +/// A path segment, in the space the scene's [`Coordinates`] name. #[derive(Clone, Copy, Debug, PartialEq)] pub enum Segment { MoveTo([f64; 2]), @@ -107,12 +169,42 @@ pub enum Segment { Close, } -/// A resolved color or an unsupported SVG paint server. +/// A resolved color, gradient or pattern. #[derive(Clone, Debug, PartialEq)] pub enum Paint { - Color { rgb: [u8; 3], opacity: f32 }, - Gradient { kind: GradientKind, stops: Vec, transform: [f64; 6], spread: Spread, opacity: f32 }, - Pattern, + Color { + rgb: [u8; 3], + opacity: f32, + }, + Gradient { + kind: GradientKind, + stops: Vec, + transform: [f64; 6], + spread: Spread, + opacity: f32, + }, + /// A ``; `None` when its content is past the depth limit or refers back to the + /// pattern itself. + Pattern { + pattern: Option, + opacity: f32, + }, +} + +/// A resolved `` tile. usvg has already applied `patternUnits`, +/// `patternContentUnits` and `viewBox`, so the tile and its content share one space. +#[derive(Clone, Debug, PartialEq)] +pub struct Pattern { + /// The element's `id`. + pub id: String, + /// The tile `[x, y, width, height]` in tile space. + pub rect: [f64; 4], + /// Maps tile space into the painted path's space: `patternTransform` in a local scene; in + /// an absolute scene, `patternTransform` followed by the path's transform to the document. + pub transform: [f64; 6], + /// What one tile draws, in tile space ([`Coordinates::Local`] whatever the scene's + /// coordinates). Shared by every use of the same pattern. + pub content: std::sync::Arc>, } #[derive(Clone, Debug, PartialEq)] @@ -162,20 +254,32 @@ pub enum LineJoin { } impl Document { - /// Convert a bounded usvg tree to a scene, omitting nodes beyond `max_depth`. + /// Convert a bounded usvg tree to a scene in document pixels ([`Coordinates::Absolute`]), + /// omitting nodes beyond `max_depth`. pub fn from_tree(tree: &usvg::Tree, max_depth: usize) -> Self { - let size = tree.size(); - let mut document = Self { width: f64::from(size.width()), height: f64::from(size.height()), ..Self::default() }; - document.nodes = convert_group(tree.root(), 0, max_depth, &mut document, &[]); + Self::convert(tree, max_depth, Coordinates::Absolute) + } + + /// Convert a bounded usvg tree to a scene that keeps every node in its own user space with a + /// transform relative to its parent ([`Coordinates::Local`]), omitting nodes beyond + /// `max_depth`. + pub fn from_tree_local(tree: &usvg::Tree, max_depth: usize) -> Self { + Self::convert(tree, max_depth, Coordinates::Local) + } + + /// Build a scene in document pixels that retains its source tree for fallback rendering. + pub fn from_owned_tree(tree: usvg::Tree, max_depth: usize) -> Self { + let mut document = Self::convert(&tree, max_depth, Coordinates::Absolute); + document.source = Some(Box::new(tree)); document } - /// Build a scene that retains its source tree for fallback rendering. - pub fn from_owned_tree(tree: usvg::Tree, max_depth: usize) -> Self { + fn convert(tree: &usvg::Tree, max_depth: usize, coordinates: Coordinates) -> Self { let size = tree.size(); - let mut document = Self { width: f64::from(size.width()), height: f64::from(size.height()), ..Self::default() }; - document.nodes = convert_group(tree.root(), 0, max_depth, &mut document, &[]); - document.source = Some(Box::new(tree)); + let mut document = Self { width: f64::from(size.width()), height: f64::from(size.height()), coordinates, ..Self::default() }; + let mut cx = Convert { doc: &mut document, max_depth, local: coordinates == Coordinates::Local, patterns: std::collections::HashMap::new() }; + let nodes = cx.group(tree.root(), tree.root().abs_transform(), 0, &[]); + document.nodes = nodes; document } @@ -231,7 +335,7 @@ fn spread(s: usvg::SpreadMethod) -> Spread { } } -fn color(paint: &usvg::Paint, opacity: f32) -> Paint { +fn color(paint: &usvg::Paint, opacity: f32, pattern: impl FnOnce(&std::sync::Arc) -> Option) -> Paint { match paint { usvg::Paint::Color(c) => Paint::Color { rgb: [c.red, c.green, c.blue], opacity }, usvg::Paint::LinearGradient(g) => Paint::Gradient { @@ -269,7 +373,7 @@ fn color(paint: &usvg::Paint, opacity: f32) -> Paint { spread: spread(g.spread_method()), opacity, }, - usvg::Paint::Pattern(_) => Paint::Pattern, + usvg::Paint::Pattern(source) => Paint::Pattern { pattern: pattern(source), opacity }, } } @@ -279,122 +383,213 @@ fn point(transform: usvg::Transform, p: usvg::tiny_skia_path::Point) -> [f64; 2] [f64::from(p.x), f64::from(p.y)] } -fn convert_group(group: &usvg::Group, depth: usize, max_depth: usize, doc: &mut Document, parent_path: &[usize]) -> Vec { - let mut result = Vec::new(); - for (index, node) in group.children().iter().enumerate() { - let mut source_path = parent_path.to_vec(); - source_path.push(index); - match node { - usvg::Node::Path(path) => { - if !path.is_visible() || path.data().is_empty() { - continue; +const IDENTITY: [f64; 6] = [1.0, 0.0, 0.0, 1.0, 0.0, 0.0]; + +/// A node's transform relative to `parent` (both absolute): `parent⁻¹ · node`. The identity +/// when `parent` cannot be inverted (a degenerate group draws nothing anyway). +fn relative(parent: usvg::Transform, node: usvg::Transform) -> usvg::Transform { + parent.invert().map_or(usvg::Transform::identity(), |inverse| inverse.pre_concat(node)) +} + +struct Convert<'d> { + doc: &'d mut Document, + max_depth: usize, + local: bool, + /// Pattern content already converted, by the address of usvg's shared pattern; `None` while + /// a pattern is being converted, so a pattern that refers back to itself gets no content. + patterns: std::collections::HashMap>>>, +} + +impl Convert<'_> { + /// The transform a node with absolute transform `node` gets under a group whose absolute + /// transform is `parent`. + fn placement(&self, parent: usvg::Transform, node: usvg::Transform) -> [f64; 6] { + if self.local { transform(relative(parent, node)) } else { transform(node) } + } + + /// `parent` is the absolute transform `group`'s leaves are placed against: its own, except + /// for flattened text, whose outline paths carry the text's while the group has none. + fn group(&mut self, group: &usvg::Group, parent: usvg::Transform, depth: usize, parent_path: &[usize]) -> Vec { + let mut result = Vec::new(); + for (index, node) in group.children().iter().enumerate() { + let mut source_path = parent_path.to_vec(); + source_path.push(index); + match node { + usvg::Node::Path(path) => { + if let Some(path) = self.path(path, parent, source_path, depth) { + result.push(Node::Path(Box::new(path))); + } } - let transform = path.abs_transform(); - let segments = path - .data() - .segments() - .map(|segment| { - use usvg::tiny_skia_path::PathSegment as S; - match segment { - S::MoveTo(a) => Segment::MoveTo(point(transform, a)), - S::LineTo(a) => Segment::LineTo(point(transform, a)), - S::QuadTo(a, b) => Segment::QuadTo(point(transform, a), point(transform, b)), - S::CubicTo(a, b, c) => Segment::CubicTo(point(transform, a), point(transform, b), point(transform, c)), - S::Close => Segment::Close, + usvg::Node::Group(child) => { + if depth >= self.max_depth { + self.doc.too_deep = true; + continue; + } + let children = self.group(child, child.abs_transform(), depth + 1, &source_path); + if !children.is_empty() { + let omitted = &mut self.doc.omitted; + omitted.filters += usize::from(!child.filters().is_empty()); + omitted.clip_paths += usize::from(child.clip_path().is_some()); + omitted.masks += usize::from(child.mask().is_some()); + omitted.blends += usize::from(child.blend_mode() != usvg::BlendMode::Normal); + let bounds = if self.local { child.layer_bounding_box().to_rect() } else { child.abs_layer_bounding_box().to_rect() }; + result.push(Node::Group { + children, + opacity: child.opacity().get(), + // Locally, the group's own transform: usvg leaves the absolute one at + // the identity for colour and bitmap glyph groups in text. + transform: if self.local { transform(child.transform()) } else { transform(child.abs_transform()) }, + bounds: rect(bounds), + features: GroupFeatures { + filters: !child.filters().is_empty(), + clip_path: child.clip_path().is_some(), + mask: child.mask().is_some(), + non_normal_blend: child.blend_mode() != usvg::BlendMode::Normal, + isolation: child.should_isolate(), + }, + source_path: NodePath(source_path), + id: child.id().to_string(), + }); + } + } + usvg::Node::Text(text) => { + if depth >= self.max_depth { + self.doc.too_deep = true; + continue; + } + let flat = text.flattened(); + // The flattened group has no transform of its own, but its outline paths + // have the text's: place its leaves, and the wrapper, in the text's frame. + let frame = if self.local { text.abs_transform() } else { flat.abs_transform() }; + let children = self.group(flat, frame, depth + 1, &source_path); + if !children.is_empty() { + let bounds = if self.local { text.bounding_box() } else { text.abs_bounding_box() }; + result.push(Node::Group { + children, + opacity: 1.0, + transform: self.placement(parent, frame), + bounds: rect(bounds), + features: GroupFeatures::default(), + source_path: NodePath(source_path), + id: text.id().to_string(), + }); + } + } + usvg::Node::Image(image) => { + self.doc.images += 1; + let kind = match image.kind() { + usvg::ImageKind::JPEG(_) => ImageKind::Jpeg, + usvg::ImageKind::PNG(_) => ImageKind::Png, + usvg::ImageKind::GIF(_) => ImageKind::Gif, + usvg::ImageKind::WEBP(_) => ImageKind::WebP, + usvg::ImageKind::SVG(_) => ImageKind::Svg, + }; + let (encoded, svg) = match image.kind() { + usvg::ImageKind::JPEG(data) | usvg::ImageKind::PNG(data) | usvg::ImageKind::GIF(data) | usvg::ImageKind::WEBP(data) => { + (Some(data.clone()), None) } - }) - .collect(); - let fill = path.fill().map(|f| color(f.paint(), f.opacity().get())); - let stroke = path.stroke().map(|s| { - let scale = f64::from((transform.sx * transform.sy - transform.kx * transform.ky).abs().sqrt()); - Stroke { - paint: color(s.paint(), s.opacity().get()), - width: f64::from(s.width().get()) * scale, - cap: match s.linecap() { - usvg::LineCap::Butt => LineCap::Butt, - usvg::LineCap::Round => LineCap::Round, - usvg::LineCap::Square => LineCap::Square, - }, - join: match s.linejoin() { - usvg::LineJoin::Round => LineJoin::Round, - usvg::LineJoin::Bevel => LineJoin::Bevel, - usvg::LineJoin::Miter | usvg::LineJoin::MiterClip => LineJoin::Miter, - }, - miter_limit: f64::from(s.miterlimit().get()), - dash_array: s.dasharray().map(|d| d.iter().map(|v| f64::from(*v) * scale).collect()), - dash_offset: f64::from(s.dashoffset()) * scale, - } - }); - result.push(Node::Path(Box::new(Path { segments, fill, stroke, source_path: NodePath(source_path) }))); - } - usvg::Node::Group(child) => { - if depth >= max_depth { - doc.too_deep = true; - continue; - } - let children = convert_group(child, depth + 1, max_depth, doc, &source_path); - if !children.is_empty() { - result.push(Node::Group { - children, - opacity: child.opacity().get(), - transform: transform(child.abs_transform()), - bounds: rect(child.abs_layer_bounding_box().to_rect()), - features: GroupFeatures { - filters: !child.filters().is_empty(), - clip_path: child.clip_path().is_some(), - mask: child.mask().is_some(), - non_normal_blend: child.blend_mode() != usvg::BlendMode::Normal, - isolation: child.should_isolate(), - }, + usvg::ImageKind::SVG(tree) => { + let max_depth = self.max_depth.saturating_sub(depth + 1); + let nested = if self.local { + Document::from_tree_local(tree, max_depth) + } else { + Document::from_owned_tree(tree.clone(), max_depth) + }; + (None, Some(Box::new(nested))) + } + }; + let bounds = if self.local { image.bounding_box() } else { image.abs_bounding_box() }; + result.push(Node::Image(Image { + kind, + visible: image.is_visible(), + transform: self.placement(parent, image.abs_transform()), + bounds: rect(bounds), + encoded, + svg, source_path: NodePath(source_path), - }); + })); } } - usvg::Node::Text(text) => { - if depth >= max_depth { - doc.too_deep = true; - continue; - } - let children = convert_group(text.flattened(), depth + 1, max_depth, doc, &source_path); - if !children.is_empty() { - result.push(Node::Group { - children, - opacity: 1.0, - transform: transform(text.abs_transform()), - bounds: rect(text.abs_bounding_box()), - features: GroupFeatures::default(), - source_path: NodePath(source_path), - }); - } - } - usvg::Node::Image(image) => { - doc.images += 1; - let kind = match image.kind() { - usvg::ImageKind::JPEG(_) => ImageKind::Jpeg, - usvg::ImageKind::PNG(_) => ImageKind::Png, - usvg::ImageKind::GIF(_) => ImageKind::Gif, - usvg::ImageKind::WEBP(_) => ImageKind::WebP, - usvg::ImageKind::SVG(_) => ImageKind::Svg, - }; - let (encoded, svg) = match image.kind() { - usvg::ImageKind::JPEG(data) | usvg::ImageKind::PNG(data) | usvg::ImageKind::GIF(data) | usvg::ImageKind::WEBP(data) => { - (Some(data.clone()), None) - } - usvg::ImageKind::SVG(tree) => { - (None, Some(Box::new(Document::from_owned_tree(tree.clone(), max_depth.saturating_sub(depth + 1))))) - } - }; - result.push(Node::Image(Image { - kind, - visible: image.is_visible(), - transform: transform(image.abs_transform()), - bounds: rect(image.abs_bounding_box()), - encoded, - svg, - source_path: NodePath(source_path), - })); - } } + result + } + + /// A visible, non-empty path. Its own absolute transform is its group's in usvg, so in a + /// local scene its segments stay as they are and its transform is normally the identity. + /// The tile of `pattern` painted on a path at `depth` whose own transform to the document is + /// `abs`. + fn pattern(&mut self, pattern: &std::sync::Arc, abs: usvg::Transform, depth: usize) -> Option { + let key = std::sync::Arc::as_ptr(pattern) as usize; + let content = match self.patterns.get(&key) { + Some(done) => done.clone(), + None if depth >= self.max_depth => { + self.doc.too_deep = true; + None + } + None => { + self.patterns.insert(key, None); + let local = std::mem::replace(&mut self.local, true); + let nodes = self.group(pattern.root(), pattern.root().abs_transform(), depth + 1, &[]); + self.local = local; + let content = Some(std::sync::Arc::new(nodes)); + self.patterns.insert(key, content.clone()); + content + } + }?; + let placement = if self.local { pattern.transform() } else { abs.pre_concat(pattern.transform()) }; + Some(Pattern { id: pattern.id().to_string(), rect: rect(pattern.rect().to_rect()), transform: transform(placement), content }) + } + + fn path(&mut self, path: &usvg::Path, parent: usvg::Transform, source_path: Vec, depth: usize) -> Option { + if !path.is_visible() || path.data().is_empty() { + return None; + } + let abs = path.abs_transform(); + let (to_points, scale, placement) = if self.local { + (usvg::Transform::identity(), 1.0, transform(relative(parent, abs))) + } else { + (abs, f64::from((abs.sx * abs.sy - abs.kx * abs.ky).abs().sqrt()), IDENTITY) + }; + let segments = path + .data() + .segments() + .map(|segment| { + use usvg::tiny_skia_path::PathSegment as S; + match segment { + S::MoveTo(a) => Segment::MoveTo(point(to_points, a)), + S::LineTo(a) => Segment::LineTo(point(to_points, a)), + S::QuadTo(a, b) => Segment::QuadTo(point(to_points, a), point(to_points, b)), + S::CubicTo(a, b, c) => Segment::CubicTo(point(to_points, a), point(to_points, b), point(to_points, c)), + S::Close => Segment::Close, + } + }) + .collect(); + let fill = path.fill().map(|f| color(f.paint(), f.opacity().get(), |p| self.pattern(p, abs, depth))); + let fill_rule = match path.fill().map(usvg::Fill::rule) { + Some(usvg::FillRule::EvenOdd) => FillRule::EvenOdd, + _ => FillRule::NonZero, + }; + let stroke = path.stroke().map(|s| Stroke { + paint: color(s.paint(), s.opacity().get(), |p| self.pattern(p, abs, depth)), + width: f64::from(s.width().get()) * scale, + cap: match s.linecap() { + usvg::LineCap::Butt => LineCap::Butt, + usvg::LineCap::Round => LineCap::Round, + usvg::LineCap::Square => LineCap::Square, + }, + join: match s.linejoin() { + usvg::LineJoin::Round => LineJoin::Round, + usvg::LineJoin::Bevel => LineJoin::Bevel, + usvg::LineJoin::Miter | usvg::LineJoin::MiterClip => LineJoin::Miter, + }, + miter_limit: f64::from(s.miterlimit().get()), + dash_array: s.dasharray().map(|d| d.iter().map(|v| f64::from(*v) * scale).collect()), + dash_offset: f64::from(s.dashoffset()) * scale, + }); + Some(Path { segments, fill, fill_rule, stroke, source_path: NodePath(source_path), id: path.id().to_string(), transform: placement }) } - result } + +#[cfg(test)] +#[path = "document_tests.rs"] +mod tests; diff --git a/crates/svg/src/tree/document_tests.rs b/crates/svg/src/tree/document_tests.rs new file mode 100644 index 000000000..a130a6f6f --- /dev/null +++ b/crates/svg/src/tree/document_tests.rs @@ -0,0 +1,349 @@ +#![allow(clippy::unwrap_used, clippy::panic, clippy::indexing_slicing, clippy::float_cmp)] + +use super::*; +use crate::tree::{Limits, parse}; + +fn tree(body: &str) -> usvg::Tree { + let svg = format!(r#"{body}"#); + parse(svg.as_bytes(), &Limits::default(), &usvg::Options::default()).unwrap() +} + +fn apply(m: [f64; 6], p: [f64; 2]) -> [f64; 2] { + [m[0] * p[0] + m[2] * p[1] + m[4], m[1] * p[0] + m[3] * p[1] + m[5]] +} + +fn then(outer: [f64; 6], inner: [f64; 6]) -> [f64; 6] { + let [a, b, c, d, e, f] = outer; + let [p, q, r, s, t, u] = inner; + [a * p + c * q, b * p + d * q, a * r + c * s, b * r + d * s, a * t + c * u + e, b * t + d * u + f] +} + +fn close(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3 +} + +/// Every path's points, mapped to document pixels through the scene's transforms. +fn document_points(nodes: &[Node], outer: [f64; 6], local: bool, out: &mut Vec<[f64; 2]>) { + for node in nodes { + match node { + Node::Group { children, transform, .. } => { + let next = if local { then(outer, *transform) } else { outer }; + document_points(children, next, local, out); + } + Node::Path(path) => { + let m = then(outer, path.transform); + for segment in &path.segments { + match segment { + Segment::MoveTo(p) | Segment::LineTo(p) => out.push(apply(m, *p)), + Segment::QuadTo(a, b) => out.extend([apply(m, *a), apply(m, *b)]), + Segment::CubicTo(a, b, c) => out.extend([apply(m, *a), apply(m, *b), apply(m, *c)]), + Segment::Close => {} + } + } + } + Node::Image(_) => {} + } + } +} + +fn paths(nodes: &[Node]) -> Vec<&Path> { + let mut out = Vec::new(); + for node in nodes { + match node { + Node::Group { children, .. } => out.extend(paths(children)), + Node::Path(path) => out.push(path), + Node::Image(_) => {} + } + } + out +} + +fn group_ids(nodes: &[Node]) -> Vec<(String, [f64; 6])> { + let mut out = Vec::new(); + for node in nodes { + if let Node::Group { children, id, transform, .. } = node { + out.push((id.clone(), *transform)); + out.extend(group_ids(children)); + } + } + out +} + +const NESTED: &str = r##" + + + + +"##; + +#[test] +fn a_local_scene_keeps_user_space_geometry_and_relative_transforms() { + let tree = tree(NESTED); + let local = Document::from_tree_local(&tree, 64); + assert_eq!(local.coordinates, Coordinates::Local); + let groups = group_ids(&local.nodes); + let outer = groups.iter().find(|(id, _)| id == "outer").unwrap(); + assert!(close([outer.1[0], outer.1[3]], [2.0, 2.0]) && close([outer.1[4], outer.1[5]], [10.0, 20.0]), "{outer:?}"); + let inner = groups.iter().find(|(id, _)| id == "inner").unwrap(); + assert!(close([inner.1[0], inner.1[1]], [0.0, 1.0]) && close([inner.1[4], inner.1[5]], [0.0, 0.0]), "relative, not absolute: {inner:?}"); + + let all = paths(&local.nodes); + let rect = all.iter().find(|p| p.id == "box").unwrap(); + let Segment::MoveTo(start) = rect.segments[0] else { panic!("{:?}", rect.segments) }; + assert!(close(start, [1.0, 2.0]), "user space: {start:?}"); + let stroke = rect.stroke.as_ref().unwrap(); + assert_eq!(stroke.width, 2.0, "not scaled by the groups"); + assert_eq!(stroke.dash_array.as_deref(), Some([1.0, 3.0].as_slice())); +} + +#[test] +fn an_absolute_scene_is_unchanged_by_the_local_option() { + let tree = tree(NESTED); + let absolute = Document::from_tree(&tree, 64); + assert_eq!(absolute.coordinates, Coordinates::Absolute); + let rect = paths(&absolute.nodes).into_iter().find(|p| p.id == "box").unwrap(); + assert_eq!(rect.transform, IDENTITY); + // (1, 2) rotated 90° is (-2, 1), then scaled by 2 and moved by (10, 20). + let Segment::MoveTo(start) = rect.segments[0] else { panic!("{:?}", rect.segments) }; + assert!(close(start, [6.0, 22.0]), "{start:?}"); + assert_eq!(rect.stroke.as_ref().unwrap().width, 4.0); +} + +#[test] +fn local_and_absolute_scenes_put_every_point_in_the_same_place() { + let tree = tree(NESTED); + let (mut local, mut absolute) = (Vec::new(), Vec::new()); + document_points(&Document::from_tree_local(&tree, 64).nodes, IDENTITY, true, &mut local); + document_points(&Document::from_tree(&tree, 64).nodes, IDENTITY, false, &mut absolute); + assert_eq!(local.len(), absolute.len()); + assert!(!local.is_empty()); + for (l, a) in local.iter().zip(&absolute) { + assert!(close(*l, *a), "{l:?} vs {a:?}"); + } +} + +#[test] +fn fill_rule_and_ids_are_kept() { + let tree = + tree(r##""##); + for document in [Document::from_tree(&tree, 64), Document::from_tree_local(&tree, 64)] { + let all = paths(&document.nodes); + assert_eq!(all.len(), 2); + assert_eq!((all[0].id.as_str(), all[0].fill_rule), ("hole", FillRule::EvenOdd)); + assert_eq!((all[1].id.as_str(), all[1].fill_rule), ("", FillRule::NonZero), "no fill: the default"); + assert!(all[1].fill.is_none()); + } +} + +#[test] +fn a_local_scene_respects_the_depth_limit() { + let deep = format!("{}{}", "".repeat(6), "".repeat(6)); + let tree = tree(&deep); + let shallow = Document::from_tree_local(&tree, 2); + assert!(shallow.too_deep); + assert!(paths(&shallow.nodes).is_empty()); + assert!(!Document::from_tree_local(&tree, 64).too_deep); +} + +#[test] +fn an_embedded_svg_in_a_local_scene_is_local_too() { + use std::io::Write as _; + let inner = r##""##; + let mut b64 = Vec::new(); + { + // A tiny base64 encoder keeps the test free of extra dependencies. + const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for chunk in inner.as_bytes().chunks(3) { + let n = chunk.iter().enumerate().fold(0u32, |n, (i, b)| n | (u32::from(*b) << (16 - 8 * i))); + for i in 0..4 { + if i <= chunk.len() { + b64.push(A[((n >> (18 - 6 * i)) & 63) as usize]); + } else { + b64.push(b'='); + } + } + } + } + let mut body = Vec::new(); + write!(body, r#""#, String::from_utf8(b64).unwrap()).unwrap(); + let svg = format!(r#"{}"#, String::from_utf8(body).unwrap()); + let options = usvg::Options { image_href_resolver: crate::tree::image_resolver(Limits::default()), ..usvg::Options::default() }; + let tree = parse(svg.as_bytes(), &Limits::default(), &options).unwrap(); + let local = Document::from_tree_local(&tree, 64); + let image = local + .nodes + .iter() + .find_map(|n| match n { + Node::Image(image) => Some(image), + Node::Group { children, .. } => children.iter().find_map(|c| if let Node::Image(image) = c { Some(image) } else { None }), + Node::Path(_) => None, + }) + .unwrap(); + let nested = image.svg.as_ref().unwrap(); + assert_eq!(nested.coordinates, Coordinates::Local); + let rect = paths(&nested.nodes)[0]; + let Segment::LineTo(p) = rect.segments[1] else { panic!("{:?}", rect.segments) }; + assert!(close(p, [1.0, 0.0]), "inside its own scaled group: {p:?}"); +} + +fn fill_pattern(path: &Path) -> Option<&Pattern> { + match path.fill.as_ref()? { + Paint::Pattern { pattern, .. } => pattern.as_ref(), + _ => None, + } +} + +const PATTERN: &str = r##" + + +"##; + +#[test] +fn a_pattern_paint_carries_its_tile_and_content() { + let tree = tree(PATTERN); + let local = Document::from_tree_local(&tree, 64); + let all = paths(&local.nodes); + let a = all.iter().find(|p| p.id == "a").unwrap(); + let pattern = fill_pattern(a).unwrap(); + assert_eq!(pattern.id, "dots"); + assert_eq!(pattern.rect, [0.0, 0.0, 4.0, 4.0]); + assert!(close([pattern.transform[4], pattern.transform[5]], [1.0, 2.0]) && close([pattern.transform[0], pattern.transform[3]], [1.0, 1.0])); + let tile = paths(&pattern.content); + assert_eq!(tile.len(), 1); + assert_eq!(tile[0].fill, Some(Paint::Color { rgb: [255, 0, 0], opacity: 1.0 })); + + // Every use shares one converted tile, and keeps its own opacity. + let b = all.iter().find(|p| p.id == "b").unwrap(); + assert!(std::sync::Arc::ptr_eq(&pattern.content, &fill_pattern(b).unwrap().content)); + assert!(matches!(b.fill, Some(Paint::Pattern { opacity, .. }) if (opacity - 0.5).abs() < 1e-6)); +} + +#[test] +fn an_absolute_scene_maps_the_tile_to_the_document() { + let tree = tree(PATTERN); + let absolute = Document::from_tree(&tree, 64); + let a = paths(&absolute.nodes).into_iter().find(|p| p.id == "a").unwrap(); + let pattern = fill_pattern(a).unwrap(); + // translate(1 2), then the group's scale(2). + assert!(close([pattern.transform[0], pattern.transform[3]], [2.0, 2.0]), "{:?}", pattern.transform); + assert!(close([pattern.transform[4], pattern.transform[5]], [2.0, 4.0]), "{:?}", pattern.transform); + // The tile's content stays in tile space. + let Segment::LineTo(p) = paths(&pattern.content)[0].segments[1] else { panic!() }; + assert!(close(p, [2.0, 0.0]), "{p:?}"); +} + +#[test] +fn bounding_box_pattern_units_are_resolved() { + let tree = tree( + r##""##, + ); + let document = Document::from_tree_local(&tree, 64); + let pattern = fill_pattern(paths(&document.nodes)[0]).unwrap(); + assert_eq!(pattern.rect, [0.0, 0.0, 5.0, 10.0]); +} + +#[test] +fn nested_patterns_convert_within_the_depth_limit() { + let svg = r##" + + + "##; + let tree = tree(svg); + let deep = Document::from_tree_local(&tree, 64); + let outer = fill_pattern(paths(&deep.nodes)[0]).unwrap(); + let inner = fill_pattern(paths(&outer.content)[0]).unwrap(); + assert_eq!(inner.id, "inner"); + assert!(!deep.too_deep); + + let shallow = Document::from_tree_local(&tree, 1); + assert!(shallow.too_deep); + let outer = fill_pattern(paths(&shallow.nodes)[0]).unwrap(); + assert!(fill_pattern(paths(&outer.content)[0]).is_none(), "past the limit: no content"); +} + +#[test] +fn a_pattern_that_refers_to_itself_ends() { + let tree = tree( + r##""##, + ); + let document = Document::from_tree_local(&tree, 64); + // usvg may drop the reference; if it keeps it, the inner use has no content. + for path in paths(&document.nodes) { + if let Some(pattern) = fill_pattern(path) { + for inner in paths(&pattern.content) { + assert!(fill_pattern(inner).is_none()); + } + } + } +} + +#[test] +fn group_effects_the_scene_leaves_out_are_counted() { + let tree = tree( + r##" + + + + + + "##, + ); + for document in [Document::from_tree(&tree, 64), Document::from_tree_local(&tree, 64)] { + assert_eq!(document.omitted, Omitted { filters: 1, clip_paths: 2, masks: 1, blends: 1 }); + } + assert_eq!(Document::from_tree(&self::tree(r#""#), 64).omitted, Omitted::default()); +} + +#[test] +fn elements_usvg_leaves_out_are_listed() { + let svg = r##" + + + + + "##; + let checked = crate::tree::preflight(svg, &Limits::default()).unwrap(); + assert_eq!( + checked.unsupported_elements(), + vec![("animate", 2), ("animateTransform", 1), ("foreignObject", 1), ("script", 1), ("set", 1)], + "the XHTML div is not an SVG element" + ); + // The same checked XML still parses. + assert!(checked.parse(&usvg::Options::default()).is_ok()); + let plain = crate::tree::preflight(r#""#, &Limits::default()).unwrap(); + assert!(plain.unsupported_elements().is_empty()); +} + +#[cfg(feature = "tree-text")] +#[test] +fn local_text_is_placed_and_bounded_in_its_parents_frame() { + let mut options = usvg::Options::default(); + let fonts = options.fontdb_mut(); + fonts.load_font_data(include_bytes!("../../../ui/tests/fonts/NotoSans-test.ttf").to_vec()); + let family = fonts.faces().next().unwrap().families[0].0.clone(); + let svg = format!( + r#"Hi"# + ); + let tree = parse(svg.as_bytes(), &Limits::default(), &options).unwrap(); + let local = Document::from_tree_local(&tree, 64); + let absolute = Document::from_tree(&tree, 64); + + let groups = group_ids(&local.nodes); + let text = groups.iter().find(|(id, _)| id == "t").unwrap(); + assert!(close([text.1[0], text.1[3]], [1.0, 1.0]) && close([text.1[4], text.1[5]], [0.0, 0.0]), "text sits in its group's frame: {text:?}"); + + let bounds = |nodes: &[Node]| -> [f64; 4] { + let Node::Group { children, .. } = &nodes[0] else { panic!() }; + let Node::Group { bounds, .. } = &children[0] else { panic!() }; + *bounds + }; + let (l, a) = (bounds(&local.nodes), bounds(&absolute.nodes)); + assert!(close([l[0] + 50.0, l[1]], [a[0], a[1]]) && close([l[2], l[3]], [a[2], a[3]]), "local {l:?} vs absolute {a:?}"); + assert!(l[0] > 0.0 && l[0] < 10.0, "near x=5 in the group's frame: {l:?}"); + + let (mut lp, mut ap) = (Vec::new(), Vec::new()); + document_points(&local.nodes, IDENTITY, true, &mut lp); + document_points(&absolute.nodes, IDENTITY, false, &mut ap); + assert!(!lp.is_empty() && lp.len() == ap.len()); + assert!(lp.iter().zip(&ap).all(|(l, a)| close(*l, *a))); +} diff --git a/crates/svg/src/tree/primitive_tests.rs b/crates/svg/src/tree/primitive_tests.rs index 81f4c0979..ac417eb6c 100644 --- a/crates/svg/src/tree/primitive_tests.rs +++ b/crates/svg/src/tree/primitive_tests.rs @@ -109,8 +109,11 @@ fn hand_written_segments_are_recognised_too() { Segment::Close, ], fill: None, + fill_rule: crate::tree::document::FillRule::NonZero, stroke: None, source_path: crate::tree::document::NodePath::default(), + id: String::new(), + transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0], }; assert_eq!(path.primitive(), Some(Primitive::Ellipse { cx: 5.0, cy: 5.0, rx: 5.0, ry: 5.0 })); }