Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

compose cache: compact neighbour signatures, resolve each anchored host once (#2186)

Dylan M. Taylorf1bdec7fee7a
diff --git a/crates/compose/src/cache.rs b/crates/compose/src/cache.rs
index 66122ccf4..5e4cb0911 100644
--- a/crates/compose/src/cache.rs
+++ b/crates/compose/src/cache.rs
@@ -7,7 +7,7 @@
//! story's composition places it. Entries hold clones of those `Arc`s, so the pointers
//! can't be reused by other allocations while the entry lives.
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex, PoisonError};
use designcraft_doc::{Document, Item, Story, StoryId, Styles};
@@ -39,6 +39,12 @@ impl From<Option<usize>> for ShownOn {
/// (`true`) or not.
type Key = (StoryId, ShownOn, bool);
+/// The hosts and wrap neighbours already resolved while answering one [`Cache::get_on`], by
+/// story, whether other stories wrap it, and depth. A story reached from many others (frames of
+/// many stories anchored in it, at several levels) is resolved once instead of once per path to
+/// it.
+type Resolved = HashMap<(StoryId, bool, usize), Arc<ComposedStory>>;
+
struct Entry {
sig: Vec<usize>,
_keep: (Arc<Story>, Arc<Styles>, Vec<Arc<Item>>, Vec<Arc<Story>>),
@@ -58,6 +64,14 @@ pub struct Cache {
previous: Mutex<HashMap<StoryId, (Vec<usize>, Arc<ComposedStory>)>>,
}
+/// A signature's hash, standing in for it in another story's signature.
+fn hash_of(sig: &[usize]) -> usize {
+ use std::hash::{Hash, Hasher};
+ let mut h = std::collections::hash_map::DefaultHasher::new();
+ sig.hash(&mut h);
+ h.finish() as usize
+}
+
/// Identity of everything a running header can depend on (stories, spreads, styles, variables).
fn doc_signature(doc: &Document) -> u64 {
use std::hash::{Hash, Hasher};
@@ -100,29 +114,44 @@ impl Cache {
/// [`Cache::get`] for any [`ShownOn`].
pub fn get_on(&self, doc: &Document, sid: StoryId, on: ShownOn) -> Arc<ComposedStory> {
- self.get_with(doc, sid, on, true, 0)
+ self.get_with(doc, sid, on, true, 0, &mut Resolved::new())
+ }
+
+ /// [`Cache::get_with`] for a host or a wrap neighbour (shown in its own frames), once per
+ /// traversal.
+ fn resolve(&self, doc: &Document, sid: StoryId, cross: bool, depth: usize, resolved: &mut Resolved) -> Arc<ComposedStory> {
+ if let Some(c) = resolved.get(&(sid, cross, depth)) {
+ return c.clone();
+ }
+ let c = self.get_with(doc, sid, ShownOn::Own, cross, depth, resolved);
+ resolved.insert((sid, cross, depth), c.clone());
+ c
}
/// [`Cache::get_on`], wrapped by other stories' anchored objects only when `cross` is set, for
/// a story `depth` hosts down from the story asked for.
- fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize) -> Arc<ComposedStory> {
+ fn get_with(&self, doc: &Document, sid: StoryId, on: ShownOn, cross: bool, depth: usize, resolved: &mut Resolved) -> Arc<ComposedStory> {
let Some(story) = doc.stories.get(&sid) else { return Arc::new(ComposedStory { story: sid, ..Default::default() }) };
let (mut sig, mut keep_items) = signature(doc, story);
let neighbours = if cross { crate::wrap::neighbours(doc, sid) } else { Vec::new() };
let mut keep_stories = Vec::new();
+ // A neighbour's signature goes in as its hash, and its items only once each: stories on
+ // one spread share its wrapping items, so copying every neighbour's whole signature and
+ // items made each entry as large as all of theirs together.
+ let mut kept: HashSet<*const Item> = keep_items.iter().map(Arc::as_ptr).collect();
for n in &neighbours {
if let Some(ns) = doc.stories.get(n) {
let (s, k) = signature(doc, ns);
sig.push(usize::MAX - 1);
- sig.extend(s);
- keep_items.extend(k);
+ sig.push(hash_of(&s));
+ keep_items.extend(k.into_iter().filter(|it| kept.insert(Arc::as_ptr(it))));
keep_stories.push(ns.clone());
}
}
// Anchored frames compose where their host story places them, so the host is composed
// first and the placements are part of the signature.
let placed = if depth < crate::placed::MAX_DEPTH {
- crate::placed::placements(doc, sid, &mut |host| self.get_with(doc, host, ShownOn::Own, true, depth + 1))
+ crate::placed::placements(doc, sid, &mut |host| self.resolve(doc, host, true, depth + 1, resolved))
} else {
Vec::new()
};
@@ -229,7 +258,7 @@ impl Cache {
// Parent-page items are composed per page: markers show its name, variables need its index.
let page = page.filter(|_| with_vars);
let running = running.then(|| self.running_index(doc));
- let others: Vec<Arc<ComposedStory>> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth)).collect();
+ let others: Vec<Arc<ComposedStory>> = neighbours.iter().map(|n| self.neighbour(doc, *n, depth, resolved)).collect();
let out = Arc::new(crate::wrap::compose_among(
doc,
sid,
@@ -315,13 +344,13 @@ impl Cache {
/// Story `sid` composed for the wrap of its anchored objects in other stories: without other
/// stories' anchored objects (no cycles), and outside the cache when it needs the document-wide
/// indexes (they compose every story).
- fn neighbour(&self, doc: &Document, sid: StoryId, depth: usize) -> Arc<ComposedStory> {
+ fn neighbour(&self, doc: &Document, sid: StoryId, depth: usize, resolved: &mut Resolved) -> Arc<ComposedStory> {
let indexed =
doc.stories.get(&sid).is_some_and(|st| crate::xref::has_xrefs(st) || (crate::vars::has_vars(st) && crate::vars::has_running(doc, st)));
if indexed {
Arc::new(crate::wrap::compose_among(doc, sid, &ComposeOptions::default(), &[]))
} else {
- self.get_with(doc, sid, ShownOn::Own, false, depth)
+ self.resolve(doc, sid, false, depth, resolved)
}
}
diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs
index e8e08dba6..b6cf33cd5 100644
--- a/crates/compose/src/lib.rs
+++ b/crates/compose/src/lib.rs
@@ -833,16 +833,31 @@ pub(crate) fn frame_specs_placed(doc: &Document, sid: StoryId, placed: &[(ItemId
/// objects ([`wrap`]).
/// Anchored frames are composed where their host story places them (unless `opts` places them).
pub fn compose_story(doc: &Document, sid: StoryId, opts: &ComposeOptions) -> ComposedStory {
- compose_story_at(doc, sid, opts, 0)
+ compose_story_at(doc, sid, opts, 0, &mut HashMap::new())
}
-/// [`compose_story`] for a story `depth` hosts down from the story asked for.
-fn compose_story_at(doc: &Document, sid: StoryId, opts: &ComposeOptions, depth: usize) -> ComposedStory {
+/// [`compose_story`] for a story `depth` hosts down from the story asked for. `hosts` holds the
+/// hosts already composed (by story and depth) while composing the story asked for, so a host
+/// that many anchored frames lead to is composed once.
+fn compose_story_at(
+ doc: &Document,
+ sid: StoryId,
+ opts: &ComposeOptions,
+ depth: usize,
+ hosts: &mut HashMap<(StoryId, usize), Arc<ComposedStory>>,
+) -> ComposedStory {
let others: Vec<ComposedStory> =
wrap::neighbours(doc, sid).into_iter().map(|o| wrap::compose_among(doc, o, &ComposeOptions::default(), &[])).collect();
let others: Vec<&ComposedStory> = others.iter().collect();
if opts.placed.is_empty() && depth < placed::MAX_DEPTH {
- let placed = placed::placements(doc, sid, &mut |host| Arc::new(compose_story_at(doc, host, &ComposeOptions::default(), depth + 1)));
+ let placed = placed::placements(doc, sid, &mut |host| {
+ if let Some(c) = hosts.get(&(host, depth + 1)) {
+ return c.clone();
+ }
+ let c = Arc::new(compose_story_at(doc, host, &ComposeOptions::default(), depth + 1, hosts));
+ hosts.insert((host, depth + 1), c.clone());
+ c
+ });
if !placed.is_empty() {
return wrap::compose_among(doc, sid, &ComposeOptions { placed, ..opts.clone() }, &others);
}
diff --git a/crates/compose/src/placed.rs b/crates/compose/src/placed.rs
index 200ff6e3c..33e4ff73c 100644
--- a/crates/compose/src/placed.rs
+++ b/crates/compose/src/placed.rs
@@ -4,6 +4,7 @@
//! own story is composed against that placement (page, page side, page rect, baseline grid), so
//! the host story is composed first.
+use std::collections::HashMap;
use std::sync::Arc;
use designcraft_doc::{Document, Item, ItemId, SpreadRef, StoryId};
@@ -23,10 +24,12 @@ pub struct Placement {
pub xf: Affine,
}
-/// The placements of `sid`'s anchored frames, from their host stories composed by `host`.
+/// The placements of `sid`'s anchored frames, from their host stories composed by `host`. Each
+/// host is asked for once, however many of the frames it holds.
pub(crate) fn placements(doc: &Document, sid: StoryId, host: &mut dyn FnMut(StoryId) -> Arc<ComposedStory>) -> Vec<(ItemId, Placement)> {
let Some(st) = doc.story(sid) else { return Vec::new() };
let mut anchored = None;
+ let mut hosts: HashMap<StoryId, Arc<ComposedStory>> = HashMap::new();
let mut out = Vec::new();
for &fid in &st.frames {
if doc.find(fid).is_some() {
@@ -35,7 +38,8 @@ pub(crate) fn placements(doc: &Document, sid: StoryId, host: &mut dyn FnMut(Stor
let items = anchored.get_or_insert_with(|| doc.anchored_items());
// A frame anchored in its own story would need its own composition to place it.
let Some(owner) = items.iter().find_map(|(owner, it)| (it.id == fid).then_some(*owner)).filter(|o| *o != sid) else { continue };
- if let Some(p) = locate(doc, &host(owner), fid) {
+ let composed = hosts.entry(owner).or_insert_with(|| host(owner));
+ if let Some(p) = locate(doc, composed, fid) {
out.push((fid, p));
}
}
diff --git a/crates/compose/src/tests.rs b/crates/compose/src/tests.rs
index 4d056dcc2..92f24682b 100644
--- a/crates/compose/src/tests.rs
+++ b/crates/compose/src/tests.rs
@@ -8457,6 +8457,41 @@ fn an_rtl_first_line_indent_is_at_the_right_edge() {
assert!((left_edge(lines[1]) - (rect.x0 + 10.0 * MM)).abs() < 1.0, "left to right, wrapped line indented: {}", left_edge(lines[1]));
}
+/// A story threaded through several frames anchored in one host story asks for the host's
+/// composition once, not once per frame.
+#[test]
+fn anchored_frames_in_one_host_compose_it_once() {
+ let mut d = Document::new(&NewDocument { pages: 1, ..Default::default() });
+ let lid = d.default_layer();
+ let body = "One.\nTwo.\nThree.\nFour.";
+ let (_, sid) = d.add_text_frame(SpreadRef::Doc(0), Rect::new(36.0, 36.0, 400.0, 400.0), lid, body, ParaFormat::default()).unwrap();
+ let nsid = StoryId(d.alloc());
+ let ids: Vec<ItemId> = (0..3).map(|_| ItemId(d.alloc())).collect();
+ let mut story = Story::with_text(nsid, "Note", ParaFormat::default());
+ story.frames.extend(&ids);
+ d.stories.insert(nsid, Arc::new(story));
+ for (k, &nid) in ids.iter().enumerate() {
+ let mut note = designcraft_doc::Item::new(
+ nid,
+ lid,
+ designcraft_doc::Shape::Rectangle,
+ designcraft_geom::shapes::rectangle(Rect::new(0.0, 0.0, 60.0, 40.0)),
+ );
+ note.content = Content::Text(designcraft_doc::TextFrame { story: nsid, options: Default::default() });
+ let at = body.find(["Two", "Three", "Four"][k]).unwrap();
+ d.story_mut(sid).unwrap().insert_object(at, designcraft_doc::AnchoredObject::new(note, Default::default()));
+ }
+ let mut asked = 0;
+ let placed = placed::placements(&d, nsid, &mut |h| {
+ asked += 1;
+ Arc::new(compose_story(&d, h, &ComposeOptions::default()))
+ });
+ assert_eq!(asked, 1, "the host is composed once");
+ assert_eq!(placed.len(), 3, "{placed:?}");
+ // The cache and the uncached path agree on where the frames go.
+ assert_eq!(Cache::new().get(&d, nsid, None).frames.len(), compose_story(&d, nsid, &ComposeOptions::default()).frames.len());
+}
+
/// A marginal note (an anchored text frame, Only Align First Line to Grid, 9/10) hangs 15 pt
/// above its anchor's baseline on a right-hand page. It composes against the document grid where
/// it is placed: its first line moves down onto the grid line, the second follows 10 pt below,