From 716a24ce40c3a797b1d9cb9fa654cc41654368bb Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sun, 29 Nov 2026 22:38:29 -0500 Subject: [PATCH] svg(paths): preserve source group ancestry during import (#4374) * svg(paths): preserve source group ancestry during import * svg(paths): support namespaced group metadata attributes --- crates/svg/src/paths.rs | 178 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 177 insertions(+), 1 deletion(-) diff --git a/crates/svg/src/paths.rs b/crates/svg/src/paths.rs index 013c6a252b..3bd57521d7 100644 --- a/crates/svg/src/paths.rs +++ b/crates/svg/src/paths.rs @@ -27,6 +27,11 @@ pub trait Kind: Clone + Default { /// styles and stylesheets, as well as the presentation properties the reader tracks itself. const PROPERTIES: &'static [&'static str] = &[]; + /// Optional raw attributes to retain on source groups (for example an editor's + /// document-local group ID). Unlike computed properties, these do not inherit. + /// At most 16 attributes per group, with values bounded by `MAX_GROUP_LABEL`. + const GROUP_ATTRIBUTES: &'static [GroupAttribute] = &[]; + /// The tag an element sets, from its computed style and `class` attribute; `None` inherits /// its parent's. fn of(style: &StyleMap, class: &str) -> Option; @@ -81,18 +86,69 @@ pub struct Shape { /// `inkscape:groupmode="layer"`, named by its `inkscape:label`, else its `id`, else empty. /// `None` outside any layer. At most [`MAX_LAYER_NAME`] characters. pub layer: Option, + /// Innermost retained source group, an index into [`Imported::groups`]. + pub group: Option, } /// Most characters of a layer name kept in [`Shape::layer`]. pub const MAX_LAYER_NAME: usize = 256; const INKSCAPE_NS: &str = "http://www.inkscape.org/namespaces/inkscape"; +/// Maximum characters retained for a group's source ID, label or requested attribute. +pub const MAX_GROUP_LABEL: usize = 256; +const MAX_GROUP_ATTRIBUTES: usize = 16; +const MAX_GROUP_METADATA_BYTES: usize = 8 * 1024 * 1024; + +/// An attribute selector for group metadata. Namespace URIs, not document-local +/// prefixes, identify namespaced XML attributes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct GroupAttribute { + pub namespace: Option<&'static str>, + pub name: &'static str, +} + +impl GroupAttribute { + pub const fn unqualified(name: &'static str) -> Self { + Self { namespace: None, name } + } + + pub const fn namespaced(namespace: &'static str, name: &'static str) -> Self { + Self { namespace: Some(namespace), name } + } +} + +/// A requested attribute and its bounded raw value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct GroupMetadata { + pub attribute: GroupAttribute, + pub value: String, +} + +/// A source SVG `` containing imported drawable geometry. Groups are in traversal order +/// (parents before children). Each expansion of a reused group has a distinct index even if +/// its source ID is the same; a source ID is a label, not a unique imported identity. +#[derive(Debug, Clone, PartialEq)] +pub struct Group { + pub parent: Option, + /// Raw source ID, if present. + pub source_id: Option, + /// Inkscape label, when present, otherwise the source ID. + pub label: Option, + /// Effective caller-defined kind after the normal style cascade. + pub kind: K, + /// Only attributes explicitly requested by [`Kind::GROUP_ATTRIBUTES`]. + pub attributes: Vec, +} + /// What [`import`] read. Shapes may lie outside the `width_mm` × `height_mm` viewport. #[derive(Debug, Clone, PartialEq)] pub struct Imported { pub width_mm: f64, pub height_mm: f64, pub shapes: Vec>, + /// Ancestors of the returned shapes; empty groups are omitted. A caller that drops + /// geometries after clipping may prune their groups as part of its model mapping. + pub groups: Vec>, pub clips: Vec, /// What was skipped or approximated. A caller adding its own goes through [`push_warning`] /// with `dropped_warnings`, to keep the list bounded. @@ -386,6 +442,7 @@ struct ImportState { clips: Vec, /// The innermost Inkscape layer's name ([`Shape::layer`]). layer: Option>, + group: Option, } impl Default for ImportState { @@ -398,6 +455,7 @@ impl Default for ImportState { inherited_style: std::collections::HashMap::new(), clips: Vec::new(), layer: None, + group: None, } } } @@ -424,7 +482,7 @@ pub(crate) const MAX_CSS_SELECTOR_CHECKS: usize = 5_000_000; /// combinators, `:not()`, `:first-child`, `:last-child`, `:root`, selector lists, and a bounded /// presentation-property cascade. Curves stay curves: nothing is flattened. /// -/// Each shape carries its stroke paint as written and the `clip-path` regions that apply to it; +/// Each shape carries its source group ancestry, stroke paint as written and the `clip-path` regions that apply to it; /// [`Imported::clipped_path`] returns its geometry with those clips applied. /// /// What cannot be represented is skipped with a line in [`Imported::warnings`]: `` (no @@ -473,6 +531,8 @@ pub fn import(svg: &str, name: &str) -> Result, Error> { reference_stack: Vec::new(), instance_count: 0, shapes: Vec::new(), + groups: Vec::new(), + group_metadata_bytes: 0, clips: Vec::new(), clip_pieces: 0, segments: 0, @@ -482,16 +542,50 @@ pub fn import(svg: &str, name: &str) -> Result, Error> { }; let base = ImportState { transform: viewport, ..ImportState::default() }; import_node(root, base, 0, &mut context)?; + let groups = retain_drawable_groups(context.groups, &mut context.shapes); Ok(Imported { width_mm, height_mm, shapes: context.shapes, + groups, clips: context.clips, warnings: context.warnings, dropped_warnings: context.dropped_warnings, }) } +/// Keep exactly the groups that own drawable shapes and their ancestors, remapping the +/// indices without another XML walk. Parent groups precede their descendants. +fn retain_drawable_groups(groups: Vec>, shapes: &mut [Shape]) -> Vec> { + let mut used = vec![false; groups.len()]; + for shape in shapes.iter() { + if let Some(index) = shape.group { + used[index] = true; + } + } + for (index, group) in groups.iter().enumerate().rev() { + if used[index] + && let Some(parent) = group.parent + { + used[parent] = true; + } + } + let mut remap = vec![None; groups.len()]; + let mut retained = Vec::new(); + for (index, mut group) in groups.into_iter().enumerate() { + if !used[index] { + continue; + } + group.parent = group.parent.and_then(|parent| remap[parent]); + remap[index] = Some(retained.len()); + retained.push(group); + } + for shape in shapes { + shape.group = shape.group.and_then(|index| remap[index]); + } + retained +} + struct ImportContext<'a, 'input, K> { visited: usize, path_name: &'a str, @@ -500,6 +594,8 @@ struct ImportContext<'a, 'input, K> { reference_stack: Vec, instance_count: usize, shapes: Vec>, + groups: Vec>, + group_metadata_bytes: usize, clips: Vec, clip_pieces: usize, segments: usize, @@ -609,6 +705,32 @@ fn import_node<'a, 'input, K: Kind>( state.display_none = true; } } + if tag == "g" && !state.display_none { + let bounded = |value: &str| value.chars().take(MAX_GROUP_LABEL).collect::(); + let source_id = node.attribute("id").map(bounded); + let label = node.attribute((INKSCAPE_NS, "label")).map(bounded).or_else(|| source_id.clone()); + let attributes: Vec = K::GROUP_ATTRIBUTES + .iter() + .take(MAX_GROUP_ATTRIBUTES) + .filter_map(|&attribute| { + let value = match attribute.namespace { + Some(namespace) => node.attribute((namespace, attribute.name)), + None => node.attribute(attribute.name), + }?; + Some(GroupMetadata { attribute, value: bounded(value) }) + }) + .collect(); + let bytes = source_id.as_ref().map_or(0, String::len) + + label.as_ref().map_or(0, String::len) + + attributes.iter().map(|item| item.value.len()).sum::(); + context.group_metadata_bytes = context.group_metadata_bytes.saturating_add(bytes); + if context.group_metadata_bytes > MAX_GROUP_METADATA_BYTES { + return Err(svg_error(context.path_name, "SVG group metadata exceeds the import limit")); + } + let index = context.groups.len(); + context.groups.push(Group { parent: state.group, source_id, label, kind: state.kind.clone(), attributes }); + state.group = Some(index); + } if !state.display_none && !state.visibility_hidden { for (property, effect) in [("mask", "the art is imported unmasked"), ("filter", "the art is imported unfiltered")] { if style.get(property).is_some_and(|v| v != "none") { @@ -699,6 +821,7 @@ fn import_node<'a, 'input, K: Kind>( fill_rule: if style.get("fill-rule").is_some_and(|value| value == "evenodd") { FillRule::EvenOdd } else { FillRule::NonZero }, clips: state.clips.clone(), layer: state.layer.as_deref().map(str::to_string), + group: state.group, })); } for child in node.children().filter(|n| n.is_element()) { @@ -1937,6 +2060,8 @@ mod tests { } impl Kind for Tag { + const GROUP_ATTRIBUTES: &'static [GroupAttribute] = + &[GroupAttribute::unqualified("data-group"), GroupAttribute::namespaced("urn:editor-metadata", "group-id")]; const PROPERTIES: &'static [&'static str] = &["data-kind"]; fn of(style: &StyleMap, class: &str) -> Option { @@ -2160,6 +2285,57 @@ mod tests { assert!(near(b.x0, 12.0) && near(b.y0, 24.0) && near(b.width(), 6.0), "{b:?}"); } + #[test] + fn group_ancestry_uses_the_geometry_walk_and_keeps_source_metadata() { + let got = read( + r#" + + + + + + + + + "#, + ); + assert_eq!(got.shapes.len(), 3); + assert_eq!(got.groups.len(), 2); + assert_eq!(got.groups[0].source_id.as_deref(), Some("decor")); + assert_eq!(got.groups[0].label.as_deref(), Some("Decorative motif")); + assert_eq!( + got.groups[0].attributes, + vec![ + GroupMetadata { attribute: GroupAttribute::unqualified("data-group"), value: "15".into() }, + GroupMetadata { attribute: GroupAttribute::namespaced("urn:editor-metadata", "group-id"), value: "42".into() }, + ] + ); + assert!(got.groups[0].parent.is_none()); + assert_eq!(got.groups[1].source_id.as_deref(), Some("details")); + assert_eq!(got.groups[1].parent, Some(0)); + assert!(got.groups[1].attributes.is_empty()); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(1), Some(0), None]); + } + + #[test] + fn repeated_use_groups_have_distinct_membership_at_each_site() { + let got = read( + r##" + + + + + + "##, + ); + assert_eq!(got.shapes.len(), 2); + assert_eq!(got.groups.len(), 5); + assert_eq!(got.groups.iter().map(|g| g.parent).collect::>(), [None, Some(0), Some(1), Some(0), Some(3)]); + assert_eq!(got.shapes.iter().map(|s| s.group).collect::>(), [Some(2), Some(4)]); + assert_eq!(got.groups[1].source_id, got.groups[3].source_id); + assert!(bounds(&got, 1).x0 > bounds(&got, 0).x0); + } + #[test] fn local_use_instances_take_x_y_transform_and_symbol_viewboxes() { let got = read(