svg(paths): preserve source group ancestry during import (#4374)

* svg(paths): preserve source group ancestry during import

* svg(paths): support namespaced group metadata attributes
This commit is contained in:
Dylan M. Taylor authored and GitHub committed 2026-11-29 22:38:29 -05:00
1 parent 891f4060c4
commit 716a24ce40
1 file changed
+177 -1
+177 -1
View File
@@ -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<Self>;
@@ -81,18 +86,69 @@ pub struct Shape<K> {
/// `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<String>,
/// Innermost retained source group, an index into [`Imported::groups`].
pub group: Option<usize>,
}
/// 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 `<g>` 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<K> {
pub parent: Option<usize>,
/// Raw source ID, if present.
pub source_id: Option<String>,
/// Inkscape label, when present, otherwise the source ID.
pub label: Option<String>,
/// Effective caller-defined kind after the normal style cascade.
pub kind: K,
/// Only attributes explicitly requested by [`Kind::GROUP_ATTRIBUTES`].
pub attributes: Vec<GroupMetadata>,
}
/// What [`import`] read. Shapes may lie outside the `width_mm` × `height_mm` viewport.
#[derive(Debug, Clone, PartialEq)]
pub struct Imported<K> {
pub width_mm: f64,
pub height_mm: f64,
pub shapes: Vec<Shape<K>>,
/// 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<Group<K>>,
pub clips: Vec<Clip>,
/// 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<K> {
clips: Vec<usize>,
/// The innermost Inkscape layer's name ([`Shape::layer`]).
layer: Option<std::rc::Rc<str>>,
group: Option<usize>,
}
impl<K: Kind> Default for ImportState<K> {
@@ -398,6 +455,7 @@ impl<K: Kind> Default for ImportState<K> {
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`]: `<text>` (no
@@ -473,6 +531,8 @@ pub fn import<K: Kind>(svg: &str, name: &str) -> Result<Imported<K>, 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<K: Kind>(svg: &str, name: &str) -> Result<Imported<K>, 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<K>(groups: Vec<Group<K>>, shapes: &mut [Shape<K>]) -> Vec<Group<K>> {
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<String>,
instance_count: usize,
shapes: Vec<Shape<K>>,
groups: Vec<Group<K>>,
group_metadata_bytes: usize,
clips: Vec<Clip>,
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::<String>();
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<GroupMetadata> = 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::<usize>();
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<Tag> {
@@ -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#"<svg xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape">
<style>.hidden { display: none; }</style>
<g id="unused"><g/></g>
<g id="decor" inkscape:label="Decorative motif" data-group="15" xmlns:meta="urn:editor-metadata" meta:group-id="42">
<g class="hidden"><rect width="2" height="2"/></g>
<g id="details"><rect width="3" height="4"/></g>
<path d="M10 3L12 3"/>
</g>
<rect x="20" width="5" height="5"/>
</svg>"#,
);
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::<Vec<_>>(), [Some(1), Some(0), None]);
}
#[test]
fn repeated_use_groups_have_distinct_membership_at_each_site() {
let got = read(
r##"<svg><defs>
<g id="motif"><g id="detail"><rect width="5" height="6"/></g></g>
</defs><g id="page">
<use href="#motif"/>
<use href="#motif" x="20"/>
</g>
</svg>"##,
);
assert_eq!(got.shapes.len(), 2);
assert_eq!(got.groups.len(), 5);
assert_eq!(got.groups.iter().map(|g| g.parent).collect::<Vec<_>>(), [None, Some(0), Some(1), Some(0), Some(3)]);
assert_eq!(got.shapes.iter().map(|s| s.group).collect::<Vec<_>>(), [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(