SVG import: a textPath finds the element its href names through an id map built once (#8160)

Each <textPath> with an href walked the whole document to find the element it names, so a file with many texts on paths took time proportional to the number of texts times the number of elements. The importer now builds a map of element ids at the first such lookup, keeping the first element in document order for each id, and looks each href up there. Files whose texts name no element do not build the map. The imported document is the same: a test compares the whole document and warnings with the per-id walk, including duplicate, missing and unusable ids.
This commit is contained in:
.CooCoo
2026-11-18 15:51:04 -05:00
committed by GitHub
parent e34bf8c82f
commit f2ffbe81d0
2 changed files with 171 additions and 2 deletions
+39 -2
View File
@@ -29,7 +29,7 @@
use craft_svg::tree::usvg;
use std::borrow::Cow;
use std::cell::RefCell;
use std::cell::{OnceCell, RefCell};
use std::collections::HashMap;
use std::fmt::Write as _;
use std::ops::{Range, RangeInclusive};
@@ -774,6 +774,10 @@ struct Ctx {
/// no usable one. The styles of a `<use>` instance share it, so each path is found and parsed
/// once however many `<use>` elements show its text.
paths: Rc<RefCell<HashMap<roxmltree::NodeId, Option<Rc<FollowedPath>>>>>,
/// Each element id in the document and the first element in document order that carries it
/// ([`Self::element`]). It is built when the first `<textPath>` names an element, and the
/// styles of a `<use>` instance share it.
ids: Rc<OnceCell<HashMap<Box<str>, roxmltree::NodeId>>>,
}
/// The path a `<textPath>` follows ([`Ctx::text_path`]).
@@ -788,6 +792,11 @@ struct FollowedPath {
thread_local! {
/// How many times [`Ctx::read_text_path`] has read a `<textPath>`'s path on this thread.
static TEXT_PATH_READS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// How many times [`Ctx::element`] has walked a document's elements on this thread.
static ID_WALKS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
/// When set, [`Ctx::element`] walks the document for each id instead of using the map, so
/// tests can compare the two.
static LINEAR_IDS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
impl Ctx {
@@ -802,6 +811,7 @@ impl Ctx {
elems: RefCell::default(),
strong: RefCell::default(),
paths: Rc::default(),
ids: Rc::default(),
};
let root = xml.root_element();
let dim = |a: &str| root.attribute(a).and_then(|v| cx.length(v, DEFAULT_FONT_SIZE, 0.0)).filter(|v| *v > 0.0);
@@ -824,6 +834,7 @@ impl Ctx {
elems: RefCell::default(),
strong: RefCell::default(),
paths: self.paths.clone(),
ids: self.ids.clone(),
}
}
@@ -1219,7 +1230,7 @@ impl Ctx {
Some(d) => BezPath::from_svg(d).ok()?,
None => {
let id = href(tp)?.trim().strip_prefix('#')?;
let el = xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id))?;
let el = self.element(xml, id)?;
let d = match el.tag_name().name() {
"path" => el.attribute("d")?.to_string(),
_ => self.shape_path(el)?,
@@ -1238,6 +1249,32 @@ impl Ctx {
usable.then_some(FollowedPath { path: bp, author_length })
}
/// The first element in document order whose `id` is `id`, as the DOM's `getElementById`
/// finds it (https://dom.spec.whatwg.org/#dom-nonelementparentnode-getelementbyid). The first
/// call walks `xml` once to build [`Self::ids`]; later calls look the id up there. `xml` is
/// the document [`Self::new`] read.
fn element<'a, 'i>(&self, xml: &'a roxmltree::Document<'i>, id: &str) -> Option<XNode<'a, 'i>> {
#[cfg(test)]
if LINEAR_IDS.get() {
ID_WALKS.set(ID_WALKS.get() + 1);
return xml.descendants().find(|n| n.is_element() && n.attribute("id") == Some(id));
}
let ids = self.ids.get_or_init(|| {
#[cfg(test)]
ID_WALKS.set(ID_WALKS.get() + 1);
let mut ids = HashMap::new();
for n in xml.descendants().filter(|n| n.is_element()) {
if let Some(id) = n.attribute("id") {
ids.entry(Box::from(id)).or_insert(n.id());
}
}
ids
});
let el = xml.get_node(*ids.get(id)?)?;
debug_assert_eq!(el.attribute("id"), Some(id), "the id map was built from another document");
Some(el)
}
/// The equivalent path of a basic shape (SVG 2 › Basic Shapes), as path data: what a
/// `<textPath>` that points at it follows. Circles and ellipses start at 3 o'clock and rounded
/// rects at the end of the top-left corner, all running clockwise; lines and polylines follow
+132
View File
@@ -1,4 +1,5 @@
use super::*;
use vectorcraft_doc::Document;
/// The texts [`prepare`] builds from `body` and how many times it read a `<textPath>`'s path.
fn prepared(body: &str) -> (usize, u64, Vec<String>) {
@@ -27,3 +28,134 @@ fn uses_of_a_text_on_a_path_read_the_path_once() {
));
assert_eq!((texts, reads), (51, 1));
}
/// How many times [`prepare`] walked the document's elements to find the element a
/// `<textPath>` names.
fn id_walks(body: &str) -> u64 {
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
let xml = roxmltree::Document::parse(&svg).unwrap();
let before = ID_WALKS.get();
prepare(&svg, &xml, None, 96.0, &mut vec![]);
ID_WALKS.get() - before
}
/// The texts on paths in one file find the elements they name through one walk of the document.
#[test]
fn text_paths_find_their_elements_in_one_walk() {
let paths: String = (0..20).map(|i| format!(r#"<path id="p{i}" d="M0 {i}L150 {i}"/>"#)).collect();
let texts: String = (0..20).map(|i| format!(r##"<text id="t{i}"><textPath href="#p{i}">Path</textPath></text>"##)).collect();
assert_eq!(id_walks(&format!("<defs>{paths}</defs>{texts}")), 1);
// Texts shown only through `<use>` elements share the walk, and a missing id needs no other.
let uses: String = (0..20).map(|i| format!(r##"<use href="#t{i}" font-size="20"/>"##)).collect();
let missing = r##"<text><textPath xlink:href="#none" xmlns:xlink="http://www.w3.org/1999/xlink">Path</textPath></text>"##;
assert_eq!(id_walks(&format!("<defs>{paths}{texts}</defs>{uses}{missing}")), 1);
// A file whose texts name no element is not walked.
assert_eq!(id_walks(r#"<text>Plain</text><text><textPath path="M0 20L150 20">Inline</textPath></text>"#), 0);
assert_eq!(id_walks(r#"<path id="p" d="M0 20L150 20"/><text><textPath href="p">No hash</textPath></text>"#), 0);
}
/// The document and warnings [`crate::import`] gives for `body`, with each `<textPath>`'s
/// element found through the map of ids or, with `linear`, by walking the document for each one.
fn imported(body: &str, linear: bool) -> (Document, Vec<String>) {
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="400">{body}</svg>"#);
LINEAR_IDS.set(linear);
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
LINEAR_IDS.set(false);
out.unwrap_or_else(|e| panic!("{e}"))
}
/// The text objects of `d`, in paint order.
fn text_objects(d: &Document) -> Vec<TextObject> {
let mut v = vec![];
d.walk(|n| {
if let vectorcraft_doc::NodeKind::Text(t) = &n.kind {
v.push((**t).clone());
}
});
v
}
/// The map of ids finds the element the document walk finds: the first element in document order
/// with the id, whatever it is.
#[test]
fn text_paths_find_the_element_a_document_walk_finds() {
let cases = [
// Several paths, one of them named twice, and shapes.
r##"<defs><path id="a" d="M0 20L150 20"/><path id="b" d="M0 50C50 0 100 100 150 50" pathLength="10"/><path id="a" d="M0 80L150 80"/>
<circle id="c" cx="200" cy="200" r="80"/><rect id="r" x="10" y="10" width="200" height="100" rx="5"/></defs>
<text font-size="12"><textPath href="#a">First</textPath></text>
<text font-size="12"><textPath xlink:href=" #b " startOffset="5">Second</textPath></text>
<text font-size="12"><textPath href="#c" side="right">Circle</textPath></text>
<text font-size="12"><textPath href="#r" startOffset="50%">Rect</textPath></text>"##,
// A missing id, an empty one, and one without a `#`.
r##"<path id="p" d="M0 20L150 20"/><text><textPath href="#none">Missing</textPath></text>
<text><textPath href="#">Empty</textPath></text><text><textPath href="p">Bare</textPath></text>"##,
// The first element with the id has no path; the later path is not used.
r##"<g id="p"><path d="M0 20L150 20"/></g><path id="p" d="M0 80L150 80"/><text><textPath href="#p">Group</textPath></text>"##,
// Ids on texts and groups, one of them named twice.
r##"<g id="g"><text id="t"><textPath href="#t">Self</textPath></text></g><text id="g">Later</text><text><textPath href="#g">Group</textPath></text>"##,
// Uses of texts on paths, and an inline path beside an href.
r##"<defs><path id="p" d="M0 20L150 20"/><text id="t"><textPath href="#p">Used</textPath></text></defs>
<use href="#t" font-size="30"/><use href="#t" y="40"/><text><textPath href="#p" path="M0 90L150 90">Inline</textPath></text>"##,
];
for body in cases {
let map = imported(body, false);
assert_eq!(map, imported(body, true), "{body}");
assert!(!text_objects(&map.0).is_empty(), "{body}");
}
}
/// With two elements of one id, a `<textPath>` follows the first.
#[test]
fn a_text_path_follows_the_first_element_with_its_id() {
let text = r##"<text font-size="12"><textPath href="#p">Path</textPath></text>"##;
let first = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
let only = text_objects(&imported(&format!(r#"<path id="p" d="M0 20L150 20"/><path id="q" d="M0 80L150 80"/>{text}"#), false).0);
let second = text_objects(&imported(&format!(r#"<path id="q" d="M0 20L150 20"/><path id="p" d="M0 80L150 80"/>{text}"#), false).0);
assert!(matches!(first[0].kind, TextKind::OnPath { .. }), "{:?}", first[0].kind);
assert_eq!(first, only);
assert_ne!(first, second);
// A first element with no path leaves the text without one.
let (doc, warnings) = imported(&format!(r#"<g id="p"/><path id="p" d="M0 80L150 80"/>{text}"#), false);
assert!(!matches!(text_objects(&doc)[0].kind, TextKind::OnPath { .. }), "{warnings:?}");
}
/// Times importing a file with 20,000 paths and 2,000 texts on paths, finding each `<textPath>`'s
/// element through the map of ids and by walking the document for each one, after checking that
/// the two give the same document. Run it with
/// `cargo test --release -p vectorcraft-svg --lib text_path_lookup_timing -- --ignored --nocapture`.
#[test]
#[ignore = "timing; run by hand in a release build"]
fn text_path_lookup_timing() {
let mut body = String::new();
for i in 0..20_000 {
let _ = write!(body, r#"<path id="p{i}" d="M0 {}L300 {}"/>"#, i % 400, i % 400);
if i % 10 == 9 {
let k = (i * 7919) % 20_000;
let _ = write!(body, r##"<text font-size="8"><textPath href="#p{k}">L{i}</textPath></text>"##);
}
}
let svg = format!(r#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400">{body}</svg>"#);
let run = |linear: bool| {
LINEAR_IDS.set(linear);
let start = std::time::Instant::now();
let out = crate::import::import(&svg, &crate::ImportOptions::default(), crate::MAX_NODES);
let took = start.elapsed();
LINEAR_IDS.set(false);
(out.unwrap_or_else(|e| panic!("{e}")), took)
};
let (map, _) = run(false);
let (walk, _) = run(true);
assert_eq!(map, walk);
assert_eq!(text_objects(&map.0).len(), 2_000);
let (mut maps, mut walks) = (vec![], vec![]);
for _ in 0..7 {
walks.push(run(true).1);
maps.push(run(false).1);
}
println!("walk per textPath: {walks:?}");
println!("map of ids: {maps:?}");
walks.sort();
maps.sort();
println!("median: walk {:?}, map {:?}", walks[3], maps[3]);
}