diff --git a/crates/ui-contract/src/contract/cx/body.rs b/crates/ui-contract/src/contract/cx/body.rs index 14f0080ca..ac8624c33 100644 --- a/crates/ui-contract/src/contract/cx/body.rs +++ b/crates/ui-contract/src/contract/cx/body.rs @@ -203,6 +203,12 @@ impl<'a> BodyCx<'a> { } impl BodyCx<'_> { + /// The value this body derives from `key`: kept while `key` is unchanged, else built by `build` + /// ([`runtime::derived`](crate::runtime::derived::derived), under the body's id). + pub fn derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc { + crate::runtime::derived::derived(self.memory.ctx(), self.id, key, build) + } + /// Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it /// is empty. `true` once per Escape; the enclosing scope (a dialog, a popover) then does not act on it. /// Components shown earlier in the body have run by the time the body asks. diff --git a/crates/ui-contract/src/runtime/derived.rs b/crates/ui-contract/src/runtime/derived.rs new file mode 100644 index 000000000..3334103ef --- /dev/null +++ b/crates/ui-contract/src/runtime/derived.rs @@ -0,0 +1,75 @@ +//! Derived values: data a component computes from its inputs and keeps across passes. [`derived`] keeps one value per +//! component id and value type, and builds it again only when its key changes. The key implements +//! [`MemoProps`](crate::contract::MemoProps), so it can only be made of checked inputs (`Tracked` revisions, framework +//! revisions, plain values), and a kept value is never stale while the key compiles. +//! +//! A value no pass asks for is dropped by the rule memoized views follow for absent entries (`lazy::absent_past_room`). + +use crate::contract::{MemoKey, MemoProps}; +use crate::runtime::egui::pass; +use crate::runtime::frame::PerViewport; +use egui::{Context, Id, IdMap}; +use std::any::{Any, TypeId}; +use std::sync::Arc; + +/// A kept value: the key it was built from and the frame a pass last asked for it. +struct Entry { + key: u128, + value: Arc, + touched: u64, +} + +/// The kept values of one viewport. +#[derive(Default)] +pub(crate) struct Store { + entries: IdMap, + /// The frame the entries were last pruned in. + pruned: u64, +} + +impl Store { + /// Drops the absent entries past the memo rule's room, once per frame. An entry asked for in this frame or the one + /// before is shown. + fn prune(&mut self, frame: u64) { + if self.pruned == frame { + return; + } + self.pruned = frame; + let shown = self.entries.values().filter(|entry| entry.touched + 1 >= frame).count(); + let absent = self.entries.iter().filter(|(_, entry)| entry.touched + 1 < frame).map(|(id, entry)| (entry.touched, *id)); + for id in super::lazy::absent_past_room(shown, absent) { + self.entries.remove(&id); + } + } +} + +/// The value of the component `id` derived from `key`: the kept one while `key` is the one it was built from, else +/// `build`'s, which is kept in its place. One value is kept per id and value type `V`; a component that derives two +/// values of one type gives each its own id. +pub fn derived(ctx: &Context, id: Id, key: &K, build: impl FnOnce() -> V) -> Arc { + let mut memo = MemoKey::of_view(ctx); + memo.feed_hash(&K::identity()); + key.key(&mut memo); + #[cfg(feature = "testing")] + crate::runtime::measure::count_memo_key_bytes(ctx, memo.bytes()); + let key = memo.finish(); + let slot = id.with(TypeId::of::()); + let viewport = pass::current_viewport(ctx); + let frame = pass::frame_nr(ctx, viewport); + let kept = PerViewport::::with(ctx, viewport, |store| { + store.prune(frame); + let entry = store.entries.get_mut(&slot).filter(|entry| entry.key == key)?; + entry.touched = frame; + Arc::clone(&entry.value).downcast::().ok() + }); + if let Some(value) = kept { + return value; + } + #[cfg(feature = "testing")] + crate::runtime::measure::count_derived(ctx, id); + // Built outside the store, so a build may derive values of its own. + let value = Arc::new(build()); + let entry = Entry { key, value: Arc::clone(&value) as Arc, touched: frame }; + PerViewport::::with(ctx, viewport, |store| store.entries.insert(slot, entry)); + value +} diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 4da3ef9fc..dce40db69 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1270,6 +1270,7 @@ pub(crate) mod guard { "runtime::lazy::Store", "lazy extents: the kept extent of content out of view, its own mechanism; a pass a kept transcript serves decides in its real run, which compares each row by its backstop", ), + ("runtime::derived::Store", "derived values: a pure function of their key, so a value a measuring run builds is the one a real run builds"), ("contract::steps::scroll_owner::", "scroll reveals and moves: read; taken through take_queued"), ("contract::body::scroll::Jumps", "scroll jumps: taken through take_queued"), ("runtime::edit::CancelAll", "edit cancels: read; a measuring run ends nothing"), diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 3a46b3231..19b1b46e3 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -335,6 +335,20 @@ impl Store { } } +/// The memo rule for absent entries, shared by every memo store (memoized views, `runtime::derived`): an entry +/// outlives its absence while the absent ones are at most twice as many as the shown ones, the longest absent dropped +/// first. Takes the absent entries as (frame last touched, id) and returns the ones to drop. +pub(crate) fn absent_past_room(shown: usize, absent: impl IntoIterator) -> Vec { + let mut absent: Vec<(u64, Id)> = absent.into_iter().collect(); + let room = 2 * shown; + if absent.len() <= room { + return Vec::new(); + } + absent.sort_unstable_by_key(|(touched, _)| *touched); + absent.truncate(absent.len() - room); + absent.into_iter().map(|(_, id)| id).collect() +} + fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { let viewport = pass::current_viewport(ctx); let (pass_nr, frame) = (pass::pass_nr(ctx, viewport), pass::frame_nr(ctx, viewport)); @@ -345,16 +359,12 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { store.pruned = frame; let reached = &store.reached; store.entries.retain(|_, entry| entry.memo() || entry.live(frame, reached)); - // A memoized view's entry outlives its absence while the absent ones are at most twice as many as the shown - // ones, the longest absent dropped first: a view shown again with the same props replays. + // A memoized view's entry outlives its absence by the memo rule: a view shown again with the same props + // replays. let shown = store.entries.values().filter(|entry| entry.memo() && entry.live(frame, reached)).count(); - let mut absent: Vec<(u64, Id)> = - store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)).collect(); - if absent.len() > 2 * shown { - absent.sort_unstable_by_key(|(touched, _)| *touched); - for (_, id) in &absent[..absent.len() - 2 * shown] { - store.entries.remove(id); - } + let absent = store.entries.iter().filter(|(_, entry)| !entry.live(frame, reached)).map(|(id, entry)| (entry.touched, *id)); + for id in absent_past_room(shown, absent) { + store.entries.remove(&id); } let owners: IdSet = store.entries.values().filter_map(|entry| entry.owner).collect(); store.reached.retain(|owner, _| owners.contains(owner)); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 6a789786a..8fd0fc014 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -52,6 +52,14 @@ struct BodyRuns { runs: Vec<(Id, u32)>, } +/// The derived values built in a pass, by component id, with the pass that counted them. +#[cfg(feature = "testing")] +#[derive(Default)] +pub(crate) struct DerivedBuilds { + pass: u64, + builds: Vec<(Id, u32)>, +} + /// How many contributions the measuring runs of a pass made that stand, with the pass that counted them. #[cfg(feature = "testing")] #[derive(Default)] @@ -540,6 +548,32 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { last_totals(ctx, |log| log.key_bytes, 0) } +/// Counts a build of a derived value of the component `id` in this pass (`runtime::derived`). +#[cfg(feature = "testing")] +pub(crate) fn count_derived(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } + let pass = ctx.cumulative_pass_nr(); + pass_state::with::(ctx, |log| { + if log.pass != pass { + *log = DerivedBuilds { pass, builds: Vec::new() }; + } + match log.builds.iter_mut().find(|(of, _)| *of == id) { + Some((_, count)) => *count += 1, + None => log.builds.push((id, 1)), + } + }); +} + +/// The components that built a derived value in the last pass, and how many builds each; empty when that pass built +/// none. +#[cfg(feature = "testing")] +pub fn last_pass_derived_builds(ctx: &Context) -> Vec<(Id, u32)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + pass_state::with::(ctx, |log| if log.pass == last { log.builds.clone() } else { Vec::new() }) +} + /// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. #[cfg(feature = "testing")] pub(crate) fn count_text_layout(ctx: &Context) { diff --git a/crates/ui-contract/src/runtime/mod.rs b/crates/ui-contract/src/runtime/mod.rs index 74870f6bb..168e97e3e 100644 --- a/crates/ui-contract/src/runtime/mod.rs +++ b/crates/ui-contract/src/runtime/mod.rs @@ -5,6 +5,7 @@ pub mod access; pub(crate) mod audit; pub mod commands; pub mod cursor; +pub mod derived; pub mod drag; pub mod edit; pub mod egui; diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 47a8da311..a2fbf0034 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -119,6 +119,8 @@ pass_state! { memo_log: crate::runtime::measure::MemoLog, #[cfg(feature = "testing")] pass_totals: crate::runtime::measure::PassTotals, + #[cfg(feature = "testing")] + derived_builds: crate::runtime::measure::DerivedBuilds, } records { focus: crate::runtime::focus::State, @@ -126,6 +128,7 @@ pass_state! { cursor: crate::runtime::cursor::State, layout: crate::runtime::layout_memory::Entries, lazy: crate::runtime::lazy::Store, + derived: crate::runtime::derived::Store, arenas: crate::primitives::sensing::Arenas, envs: crate::runtime::env::ViewportEnvs, pointer: crate::runtime::pointer::Memory, diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 27c05cfeb..32977778f 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -46,8 +46,9 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs, - last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, - last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, + last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, + last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, + widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-contract/tests/it/runtime/derived.rs b/crates/ui-contract/tests/it/runtime/derived.rs new file mode 100644 index 000000000..dbb8343de --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/derived.rs @@ -0,0 +1,62 @@ +//! Derived values: built once per key, kept while the key is unchanged, and dropped by the memo rule once absent. + +use craft_ui::runtime::derived::derived; +use craft_ui::testing::{Fixture, last_pass_derived_builds, trial}; +use egui::Id; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; +use std::sync::Arc; + +/// A fixture whose pass derives a value under each id `ids` holds, keyed by `key`; `seen` collects the values. +fn deriving(ids: Rc>>, key: Rc>, seen: Rc>>>) -> Fixture { + Fixture::new(move |ui| { + seen.borrow_mut().clear(); + for id in ids.borrow().iter() { + let value = derived(ui.ctx(), Id::NULL.with(("derived", *id)), &key.get(), || format!("{id} at {}", key.get())); + seen.borrow_mut().push(value); + } + }) +} + +/// The number of builds in the last pass. +fn builds(fixture: &Fixture) -> u32 { + last_pass_derived_builds(fixture.ctx()).iter().map(|(_, builds)| builds).sum() +} + +/// An unchanged key returns the kept value without a build; a changed key builds once, then keeps that. +#[trial] +fn a_derived_value_builds_once_per_key() { + let (ids, key, seen) = (Rc::new(RefCell::new(vec![1])), Rc::new(Cell::new(7)), Rc::default()); + let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen)); + fixture.frame(Vec::new()); + let first = Arc::clone(&seen.borrow()[0]); + for _ in 0..3 { + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "an unchanged key builds nothing"); + assert!(Arc::ptr_eq(&seen.borrow()[0], &first), "and returns the kept value"); + } + key.set(8); + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 1, "a changed key builds once"); + assert_eq!(*seen.borrow()[0], "1 at 8"); + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "then keeps the new value"); +} + +/// A value no pass asks for is kept while the absent ones are at most twice the shown ones, and dropped past that. +#[trial] +fn an_absent_derived_value_is_dropped_by_the_memo_rule() { + let (ids, key, seen) = (Rc::new(RefCell::new(vec![1, 2, 3])), Rc::new(Cell::new(0)), Rc::default()); + let mut fixture = deriving(Rc::clone(&ids), Rc::clone(&key), Rc::clone(&seen)); + fixture.frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1]; + fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1, 2, 3]; + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 0, "two absent values beside one shown are kept"); + *ids.borrow_mut() = Vec::new(); + fixture.frame(Vec::new()).frame(Vec::new()).frame(Vec::new()); + *ids.borrow_mut() = vec![1]; + fixture.frame(Vec::new()); + assert_eq!(builds(&fixture), 1, "with none shown, every absent value was dropped"); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 44af1552c..d24b2afb1 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -4,6 +4,7 @@ mod chord_fallthrough; mod clipboard; mod control_click; mod cursor; +mod derived; mod elapsed; mod env; mod frame;