From f2ffbe81d02d5eb6d1bf4aa6a748f432748d4f99 Mon Sep 17 00:00:00 2001 From: ".CooCoo" Date: Wed, 18 Nov 2026 12:51:04 -0800 Subject: [PATCH] SVG import: a textPath finds the element its href names through an id map built once (#8160) Each 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. --- crates/svg/src/import/text.rs | 41 ++++++++- crates/svg/src/import/text/tests.rs | 132 ++++++++++++++++++++++++++++ 2 files changed, 171 insertions(+), 2 deletions(-) diff --git a/crates/svg/src/import/text.rs b/crates/svg/src/import/text.rs index f814ea65a9..55a14740b1 100644 --- a/crates/svg/src/import/text.rs +++ b/crates/svg/src/import/text.rs @@ -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 `` instance share it, so each path is found and parsed /// once however many `` elements show its text. paths: Rc>>>>, + /// Each element id in the document and the first element in document order that carries it + /// ([`Self::element`]). It is built when the first `` names an element, and the + /// styles of a `` instance share it. + ids: Rc, roxmltree::NodeId>>>, } /// The path a `` follows ([`Ctx::text_path`]). @@ -788,6 +792,11 @@ struct FollowedPath { thread_local! { /// How many times [`Ctx::read_text_path`] has read a ``'s path on this thread. static TEXT_PATH_READS: std::cell::Cell = 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 = 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 = 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> { + #[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 /// `` 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 diff --git a/crates/svg/src/import/text/tests.rs b/crates/svg/src/import/text/tests.rs index a6bcf07265..18ec0ec102 100644 --- a/crates/svg/src/import/text/tests.rs +++ b/crates/svg/src/import/text/tests.rs @@ -1,4 +1,5 @@ use super::*; +use vectorcraft_doc::Document; /// The texts [`prepare`] builds from `body` and how many times it read a ``'s path. fn prepared(body: &str) -> (usize, u64, Vec) { @@ -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 +/// `` names. +fn id_walks(body: &str) -> u64 { + let svg = format!(r#"{body}"#); + 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#""#)).collect(); + let texts: String = (0..20).map(|i| format!(r##"Path"##)).collect(); + assert_eq!(id_walks(&format!("{paths}{texts}")), 1); + // Texts shown only through `` elements share the walk, and a missing id needs no other. + let uses: String = (0..20).map(|i| format!(r##""##)).collect(); + let missing = r##"Path"##; + assert_eq!(id_walks(&format!("{paths}{texts}{uses}{missing}")), 1); + // A file whose texts name no element is not walked. + assert_eq!(id_walks(r#"PlainInline"#), 0); + assert_eq!(id_walks(r#"No hash"#), 0); +} + +/// The document and warnings [`crate::import`] gives for `body`, with each ``'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) { + let svg = format!(r#"{body}"#); + 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 { + 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##" + + First + Second + Circle + Rect"##, + // A missing id, an empty one, and one without a `#`. + r##"Missing + EmptyBare"##, + // The first element with the id has no path; the later path is not used. + r##"Group"##, + // Ids on texts and groups, one of them named twice. + r##"SelfLaterGroup"##, + // Uses of texts on paths, and an inline path beside an href. + r##"Used + Inline"##, + ]; + 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 `` follows the first. +#[test] +fn a_text_path_follows_the_first_element_with_its_id() { + let text = r##"Path"##; + let first = text_objects(&imported(&format!(r#"{text}"#), false).0); + let only = text_objects(&imported(&format!(r#"{text}"#), false).0); + let second = text_objects(&imported(&format!(r#"{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#"{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 ``'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#""#, i % 400, i % 400); + if i % 10 == 9 { + let k = (i * 7919) % 20_000; + let _ = write!(body, r##"L{i}"##); + } + } + let svg = format!(r#"{body}"#); + 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]); +}