From 66391f53ed923adbe36099199b97ae420be930d1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 00:24:59 +0000 Subject: [PATCH 01/32] ui-contract: a run reaches its pass state and its pass facts through one binding The running pass's facts live on the thread's entry for its context, beside the pass state, so frame::running, current_viewport, pass_nr and frame_nr read the component tree's binding instead of a second thread-local searched by context. Inside the tree, pass_state::with runs on the bound state directly; the visit through a dyn callback serves only reads outside it. Per-viewport records of types the pass state names no field for (Facts, dock targets, toasts and the other Stored types) live in the pass state by type, not in egui context data behind its data lock and a service mutex. The memory eviction sweep reads the running pass once, not once per owner. Trial: a settled pass of forty command-bound leaves makes as many context-data lookups and unbound pass-state reads as one of ten. --- crates/ui-contract/src/runtime/egui/pass.rs | 8 +- crates/ui-contract/src/runtime/frame.rs | 42 ++--- crates/ui-contract/src/runtime/memory.rs | 3 +- crates/ui-contract/src/runtime/pass_state.rs | 157 +++++++++++++++---- crates/ui-contract/src/testing/mod.rs | 2 + crates/ui-contract/tests/it/runtime/frame.rs | 16 +- 6 files changed, 154 insertions(+), 74 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/pass.rs b/crates/ui-contract/src/runtime/egui/pass.rs index cfcbaa3c77..f3a7d6f928 100644 --- a/crates/ui-contract/src/runtime/egui/pass.rs +++ b/crates/ui-contract/src/runtime/egui/pass.rs @@ -5,7 +5,13 @@ use egui::{Context, ViewportId}; /// The pass number of `viewport`; it counts every pass, discard passes included. pub(crate) fn pass_nr(ctx: &Context, viewport: ViewportId) -> u64 { - match frame::running(ctx) { + pass_nr_beside(ctx, frame::running(ctx), viewport) +} + +/// The pass number of `viewport` while `running` is the running pass: for a sweep over the records of every viewport, +/// which reads the running pass once. +pub(crate) fn pass_nr_beside(ctx: &Context, running: Option, viewport: ViewportId) -> u64 { + match running { Some(facts) if facts.viewport == viewport => facts.pass_nr, _ => ctx.cumulative_pass_nr_for(viewport), } diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 2b5922e90a..feee472396 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -2,7 +2,6 @@ use crate::runtime::commands::{self, CommandInput, CommandSet as _, Fired}; use crate::runtime::egui::input::{self as raw_input, Arrived, HeldInput, RawInput}; -use crate::runtime::egui::memory as store; use crate::runtime::egui::{clipboard, pass, scale, style}; use crate::runtime::env::{AltCodePages, Env, RootEnv, WheelSpeed, WindowKey}; use crate::runtime::pass_state; @@ -14,7 +13,6 @@ use craft_keymap::Mods; use craft_theme::{AppSizes, Appearance, Contrast, HitSizes, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, builtins, resolve_sized}; use egui::{Context, Id, Ui, ViewportId}; use std::any::TypeId; -use std::cell::RefCell; use std::collections::HashMap; use std::sync::Arc; @@ -275,18 +273,18 @@ impl PerViewport { } } -/// Where the records of a [`PerViewport`] type live: a context service unless the type is pass-local -/// (`runtime::pass_state`), which overrides these. +/// Where the records of a [`PerViewport`] type live: in the context's pass state, a field of it for the types the +/// runtime names there (`runtime::pass_state`, which overrides these), else by type beside the fields. #[doc(hidden)] pub trait Stored: Default + Send + 'static { /// Runs `f` on the records of this type. fn records(ctx: &Context, f: impl FnOnce(&mut PerViewport) -> R) -> R { - store::with::, R>(ctx, f) + pass_state::with_records::(ctx, f) } /// Runs `f` on the stamped records of this type. fn stamped(ctx: &Context, f: impl FnOnce(&mut PerViewport>) -> R) -> R { - store::with::>, R>(ctx, f) + pass_state::with_records::, R>(ctx, f) } } @@ -681,14 +679,6 @@ struct ViewportRecord { impl Stored for ViewportRecord {} -/// What the begin hook read of the running pass; steps read it, none writes it. -#[derive(Clone)] -struct RunningPass { - /// The context the pass runs in. Another context on the same thread, and a pass a panic left open, read none of these. - ctx: Context, - facts: PassFacts, -} - /// What a pass fixes for every step: its viewport, numbers and time. #[derive(Clone, Copy)] #[doc(hidden)] @@ -703,15 +693,11 @@ pub struct PassFacts { pub elapsed: f64, } -thread_local! { - /// The passes between their begin and end hooks on this thread, innermost last: nested viewport passes stack. - static RUNNING: RefCell> = const { RefCell::new(Vec::new()) }; -} - -/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. +/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. The begin hook +/// reads them; steps read them, none writes them. #[doc(hidden)] pub fn running(ctx: &Context) -> Option { - RUNNING.with(|running| running.borrow().iter().rev().find(|pass| pass.ctx == *ctx).map(|pass| pass.facts)) + pass_state::running(ctx) } /// The facts of the innermost running pass of `ctx`, or outside every pass of it, what the context says of its @@ -840,13 +826,8 @@ pub(crate) fn begin_pass(ui: &mut Ui) { let elapsed = record.now.replace(now).map_or(0.0, |previous| (now - previous).max(0.0)); (elapsed, std::mem::take(&mut record.press_cancelled)) }); - RUNNING.with(|running| { - let mut running = running.borrow_mut(); - // A pass of this viewport that never ended (a panic unwound through it) is not still running. - running.retain(|pass| !(pass.ctx == ctx && pass.facts.viewport == viewport)); - running.push(RunningPass { ctx: ctx.clone(), facts: PassFacts { viewport, pass_nr, frame_nr, now, elapsed } }); - }); pass_state::hold(&ctx); + pass_state::begin_running(&ctx, PassFacts { viewport, pass_nr, frame_nr, now, elapsed }); if root_pass.is_some() && pass::first_of_frame(&ctx) { prune_closed(&ctx); } @@ -916,11 +897,6 @@ pub(crate) fn end_pass(ui: &mut Ui) { pass_state::with::(&ctx, |state| state.passes_open = state.passes_open.saturating_sub(1)); #[cfg(feature = "testing")] crate::runtime::egui::access::check_parents_acyclic(&ctx); - RUNNING.with(|running| { - let mut running = running.borrow_mut(); - if let Some(at) = running.iter().rposition(|pass| pass.ctx == ctx) { - running.remove(at); - } - }); + pass_state::end_running(&ctx); pass_state::release(&ctx); } diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index b0da0f3da0..fb53719828 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -326,8 +326,9 @@ fn end_lives(reg: &mut Registry, owners: impl IntoIterator) { pub(crate) fn evict(ctx: &Context) { let now = frame::clock(ctx); let live = pass::live_viewports(ctx); + let running = frame::running(ctx); pass_state::with::(ctx, |reg| { - let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr(ctx, r.viewport), now, live.contains(&r.viewport)); + let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr_beside(ctx, running, r.viewport), now, live.contains(&r.viewport)); let dead: IdSet = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect(); if dead.is_empty() { return; diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 2ac5ad08b6..8e9d1f9415 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -10,9 +10,10 @@ //! context runs. Another thread can't reach the state while a pass holds it: the runtime touches these services only //! from the thread that runs the pass. -use crate::runtime::egui::memory::Service; -use crate::runtime::frame::{self, PerViewport, Stamped, Stored}; +use crate::runtime::egui::memory::{FastMap, Service}; +use crate::runtime::frame::{PassFacts, PerViewport, Stamped, Stored}; use egui::{Context, IdSet}; +use std::any::{Any, TypeId}; use std::cell::{Cell, RefCell}; use std::sync::Arc; @@ -33,6 +34,9 @@ macro_rules! pass_state { $($(#[$service_attr])* $service: RefCell<$service_ty>,)* $($record: RefCell>,)* $($stamped: RefCell>>,)* + /// The per-viewport records of the types with no field here (generic ones, and those of crates above the + /// runtime), by type: each value is a `RefCell>`. + others: RefCell>>, } $($(#[$service_attr])* impl PassLocal for $service_ty { @@ -163,6 +167,15 @@ pass_state! { struct Held { ctx: Context, state: Box, + /// The context's passes between their begin and end hooks on this thread, innermost last: nested viewport passes + /// stack. A pass a panic unwound through stays until a pass of its viewport begins again. + passes: RefCell>, +} + +impl Held { + fn running(&self) -> bool { + !self.passes.borrow().is_empty() + } } struct HeldStates { @@ -178,13 +191,13 @@ impl HeldStates { /// Service reads in the same context reuse its slot. A nested context or a swap on release /// can change the slot, so verify its owner before reusing it. - fn get(&self, ctx: &Context) -> Option<&PassState> { + fn get(&self, ctx: &Context) -> Option<&Held> { if let Some(entry) = self.entries.get(self.current.get()).filter(|entry| entry.ctx == *ctx) { - return Some(&entry.state); + return Some(entry); } let at = self.entries.iter().position(|entry| entry.ctx == *ctx)?; self.current.set(at); - Some(&self.entries[at].state) + Some(&self.entries[at]) } } @@ -214,7 +227,7 @@ pub(crate) fn with_component_tree(ctx: &Context, run: impl FnOnce()) { impl Drop for Restore { fn drop(&mut self) { if let Some(entry) = self.0.take() { - if frame::running(&entry.ctx).is_some() { + if entry.running() { keep(entry); } else { park(entry); @@ -249,34 +262,103 @@ impl Default for Parked { pub(crate) fn with(ctx: &Context, f: impl FnOnce(&mut S) -> R) -> R { #[cfg(feature = "testing")] crate::runtime::layout_memory::guard::touch::(); + with_state(ctx, |state| f(&mut S::cell(state).borrow_mut())) +} + +/// Runs `f` on the context's records of `T`, one per viewport, for a type with no field in [`PassState`]. `f` makes +/// no call that reaches the context, so no other record of this kind is first used inside it. +pub(crate) fn with_records(ctx: &Context, f: impl FnOnce(&mut PerViewport) -> R) -> R { + with_state(ctx, |state| { + let key = TypeId::of::>(); + if !state.others.borrow().contains_key(&key) { + state.others.borrow_mut().insert(key, Box::new(RefCell::new(PerViewport::::default()))); + } + let others = state.others.borrow(); + #[expect(clippy::expect_used, reason = "the entry under a type's id is created above with that type")] + let records = others.get(&key).and_then(|records| records.downcast_ref::>>()).expect("the records of the type"); + f(&mut records.borrow_mut()) + }) +} + +/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. +pub(crate) fn running(ctx: &Context) -> Option { + if RUNNING.is_set() + && let Some(facts) = RUNNING.with(|entry| (entry.ctx == *ctx).then(|| entry.passes.borrow().last().copied())) + { + return facts; + } + note_unbound(); + HELD.with(|held| held.borrow().get(ctx).and_then(|entry| entry.passes.borrow().last().copied())) +} + +/// Puts the pass the begin hook starts on the running stack of `ctx`, whose state this thread holds: a pass of the +/// same viewport still there never ended (a panic unwound through it). +pub(crate) fn begin_running(ctx: &Context, facts: PassFacts) { + let held = with_entry(ctx, |entry| { + let mut passes = entry.passes.borrow_mut(); + passes.retain(|pass| pass.viewport != facts.viewport); + passes.push(facts); + }); + debug_assert!(held.is_some(), "the begin hook holds the context's pass state"); +} + +/// Takes the innermost pass of `ctx` off its running stack: the end hook. +pub(crate) fn end_running(ctx: &Context) { + with_entry(ctx, |entry| entry.passes.borrow_mut().pop()); +} + +/// Runs `f` on the entry of `ctx` this thread holds, bound or not. +fn with_entry(ctx: &Context, f: impl FnOnce(&Held) -> R) -> Option { + if bound(ctx) { + return Some(RUNNING.with(f)); + } + HELD.with(|held| held.borrow().get(ctx).map(f)) +} + +/// Runs `f` on the context's pass state: inside its component tree, straight from the binding. +fn with_state(ctx: &Context, f: impl FnOnce(&PassState) -> R) -> R { let mut call = Some(f); + if RUNNING.is_set() + && let Some(out) = RUNNING.with(|entry| if entry.ctx == *ctx { call.take().map(|f| f(&entry.state)) } else { None }) + { + return out; + } + note_unbound(); let mut out = None; visit(ctx, &mut |state| { if let Some(f) = call.take() { - out = Some(f(&mut S::cell(state).borrow_mut())); + out = Some(f(state)); } }); #[expect(clippy::expect_used, reason = "visit calls its callback once on both the held and parked paths")] out.expect("the pass state was visited") } -/// The thread-local lookup and the parked-state slow path are shared by every service and caller. +#[cfg(feature = "testing")] +thread_local! { + static UNBOUND: Cell = const { Cell::new(0) }; +} + +/// How many reads of a pass state this thread made outside the component tree that binds it. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn unbound_reads() -> u64 { + UNBOUND.with(Cell::get) +} + +#[inline] +fn note_unbound() { + #[cfg(feature = "testing")] + UNBOUND.with(|reads| reads.set(reads.get() + 1)); +} + +/// The state of a context its component tree does not bind: the thread's held entry, else the parked state, held for +/// this read alone. Shared by every service and caller. fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) { - if RUNNING.is_set() - && RUNNING.with(|entry| { - if entry.ctx != *ctx { - return false; - } - f(&entry.state); - true - }) - { - return; - } let found = HELD.with(|held| { let held = held.borrow(); - let Some(state) = held.get(ctx) else { return false }; - f(state); + let Some(entry) = held.get(ctx) else { return false }; + f(&entry.state); true }); if !found { @@ -292,8 +374,8 @@ fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) { HELD.with(|held| { let held = held.borrow(); #[expect(clippy::expect_used, reason = "`hold` has just moved the context's state into this thread")] - let state = held.get(ctx).expect("the state was just taken"); - f(state) + let entry = held.get(ctx).expect("the state was just taken"); + f(&entry.state) }) } } @@ -304,8 +386,7 @@ pub(crate) fn hold(ctx: &Context) { if bound(ctx) { return; } - let stale: Vec = - HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && frame::running(&entry.ctx).is_none()).collect()); + let stale: Vec = HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && !entry.running()).collect()); for held in stale { park(held); } @@ -315,15 +396,19 @@ pub(crate) fn hold(ctx: &Context) { let state = Service::::run(ctx, |parked| parked.0.take()); debug_assert!(state.is_some(), "another thread holds this context's pass state"); let state = state.unwrap_or_default(); - keep(Held { ctx: ctx.clone(), state }); + keep(Held { ctx: ctx.clone(), state, passes: RefCell::new(Vec::new()) }); } /// Moves the context's state back into its context data unless a pass of it still runs on this thread: the end hook. pub(crate) fn release(ctx: &Context) { - if bound(ctx) || frame::running(ctx).is_some() { + if bound(ctx) { return; } - if let Some(held) = HELD.with(|held| held.borrow_mut().take(ctx)) { + let idle = HELD.with(|held| { + let mut held = held.borrow_mut(); + if held.get(ctx).is_some_and(Held::running) { None } else { held.take(ctx) } + }); + if let Some(held) = idle { park(held); } } @@ -334,14 +419,13 @@ fn park(held: Held) { #[cfg(all(feature = "testing", any(test, feature = "suite")))] pub(crate) mod binding_tests { - use super::{PassState, bound, hold, in_component_tree, visit, with_component_tree}; + use super::{PassState, begin_running, bound, end_running, hold, in_component_tree, release, running, with_component_tree, with_state}; + use crate::runtime::frame::PassFacts; use crate::testing::trial; - use egui::Context; + use egui::{Context, ViewportId}; fn address(ctx: &Context) -> *const PassState { - let mut address = std::ptr::null(); - visit(ctx, &mut |state| address = std::ptr::from_ref(state)); - address + with_state(ctx, std::ptr::from_ref) } #[trial] @@ -349,11 +433,14 @@ pub(crate) mod binding_tests { let outer = Context::default(); let inner = Context::default(); hold(&outer); + begin_running(&outer, PassFacts { viewport: ViewportId::ROOT, pass_nr: 7, frame_nr: 7, now: 0.0, elapsed: 0.0 }); let original = address(&outer); let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { with_component_tree(&outer, || { assert!(bound(&outer)); assert!(!bound(&inner)); + assert_eq!(running(&outer).map(|facts| facts.pass_nr), Some(7), "the tree reads its pass from the binding"); + assert!(running(&inner).is_none(), "a nested context has no pass running"); assert_ne!(address(&inner), original); assert_eq!(address(&outer), original); std::panic::resume_unwind(Box::new("component unwound")); @@ -362,5 +449,9 @@ pub(crate) mod binding_tests { assert!(unwound.is_err_and(|reason| reason.downcast_ref::<&str>() == Some(&"component unwound"))); assert!(!in_component_tree()); assert_eq!(address(&outer), original); + assert_eq!(running(&outer).map(|facts| facts.pass_nr), Some(7), "the running pass outlives the unwound tree"); + end_running(&outer); + release(&outer); + assert!(running(&outer).is_none()); } } diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index d6acf5d4f5..e4ca903c4d 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -61,6 +61,8 @@ pub use crate::runtime::measure::{ last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, last_pass_tip_texts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, }; +#[cfg(feature = "testing")] +pub use crate::runtime::pass_state::unbound_reads as unbound_pass_state_reads; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; pub use frames::Frames; diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index 5c0ba16b23..f2e45c04c2 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -59,11 +59,14 @@ fn one_press_per_pass_and_a_discard_pass_gets_no_held_events() { assert_eq!(run(&mut frames, vec![], false), vec![Vec::<&str>::new()]); } -/// Pass-local state: inside a pass the pipeline looks up no service in context data per run, so a settled pass of -/// forty leaves makes as many lookups as one of ten. +/// Pass-local state: inside a pass the pipeline looks up no service in context data per run, and each run reaches the +/// pass state and the pass's facts through its component tree's binding, so a settled pass of forty command-bound +/// leaves (each registers the command it shows, a per-viewport record) makes as many lookups and unbound reads as one +/// of ten. #[trial] fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() { use craft_ui::runtime::egui::memory::service_lookups; + use craft_ui::testing::unbound_pass_state_reads; use craft_ui_test_kit::contract::Panel; let settled_lookups = |leaves: usize| { let mut frames = Frames::new(); @@ -71,19 +74,20 @@ fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() { Panel::new().id_salt("leaves").show(ui, |ui, _| { for at in 0..leaves { let seen = std::cell::RefCell::new(Seen::default()); - Probe::new(&seen).label(format!("Leaf {at}")).show(ui); + Probe::new(&seen).label(format!("Leaf {at}")).command(Shown::Apply).show(ui); } }); }; for _ in 0..3 { frames.frame(vec![], &mut show); } - let before = service_lookups(); + let (lookups, unbound) = (service_lookups(), unbound_pass_state_reads()); frames.frame(vec![], &mut show); - service_lookups() - before + (service_lookups() - lookups, unbound_pass_state_reads() - unbound) }; - let (ten, forty) = (settled_lookups(10), settled_lookups(40)); + let ((ten, ten_unbound), (forty, forty_unbound)) = (settled_lookups(10), settled_lookups(40)); assert_eq!(ten, forty, "context-data lookups grow with the runs: {ten} for ten leaves, {forty} for forty"); + assert_eq!(ten_unbound, forty_unbound, "unbound pass-state reads grow with the runs: {ten_unbound} for ten leaves, {forty_unbound} for forty"); } /// The app command the settled view's probe is bound to; its modal rule is the default one, `Blocked`. From 090a789c3ba634317cdd382480e34f0b511ce70d Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 00:25:26 +0000 Subject: [PATCH 02/32] perf(ui-contract): shown facts share their command, and facts keep their buffers across passes A bound component's shown fact held its command by value, so every settled pass copied each command's id into a new fact when the replay registered it again, and the next pass freed them all. The fact now shares the kept resolution's Arc, and a fact record swaps its two buffers instead of dropping last pass's, so a settled pass copies no command and grows no fact vector. --- .../ui-contract/src/contract/steps/report.rs | 2 +- .../ui-contract/src/runtime/commands/board.rs | 9 ++- .../ui-contract/src/runtime/commands/mod.rs | 25 ++++++-- crates/ui-contract/src/runtime/memory.rs | 6 +- crates/ui-contract/tests/it/runtime/shown.rs | 57 ++++++++++++++++++- 5 files changed, 88 insertions(+), 11 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index d7cfe572c9..5a7b1873fc 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -115,7 +115,7 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> let resolved = core.resolved; // Before any return: a component without an AccessKit node (merged, or AccessKit off) still records its command // for the inspected region, which keytips place their badges by. - inspect::note_command(ctx, id, core.command.as_deref().map(|command| command.command.clone())); + inspect::note_command(ctx, id, core.command.as_deref().map(|command| (*command.command).clone())); let paint = core.paint.borrow(); if role == Role::Merged { let facts = scope::Merged { diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 8d3474f5cd..2cb20ce175 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -413,7 +413,7 @@ impl Shown { /// The entry `reader` keeps for `command`. fn find(&self, reader: &Reader, number: u32, command: &CommandRef) -> Option { let ids = self.by_reader.get(reader)?.get(&number)?; - ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| entry.kept.resolved.command == *command)) + ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| *entry.kept.resolved.command == *command)) } /// Keeps `kept` for `reader`, in place of what it kept for the same command. @@ -841,7 +841,7 @@ impl Board { hint_alone: state.is_some_and(CommandState::is_hint_alone), kind: def.map_or(CommandKind::Command, |def| def.kind.clone()), edit: self.registry.edit_of(&command.id).is_some(), - command: command.clone(), + command: Arc::new(command.clone()), instance, }; (resolved, key) @@ -1809,7 +1809,10 @@ pub(crate) fn fire_resolved(ctx: &Context, command: &ResolvedCommand, source: Fi if !command.enabled || !crate::runtime::measure::effect(ctx, "board::fire_resolved") { return false; } - queue(ctx, Fired { target: command.instance, ..Fired::new(command.command.clone(), source, FirePhase::Press, pass::now(ctx)) }.mods(mods)); + queue( + ctx, + Fired { target: command.instance, ..Fired::new(CommandRef::clone(&command.command), source, FirePhase::Press, pass::now(ctx)) }.mods(mods), + ); true } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index dc6a98264b..9167d09123 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -407,7 +407,8 @@ pub struct ResolvedCommand { /// The command is an edit a focused component takes as its own (it has an `EditCommand` link): a control bound to /// it keeps the focus where it is on a press, so the edit reaches the focused component. pub edit: bool, - pub(crate) command: CommandRef, + /// Shared by every fact that shows this resolution, so a settled view's facts copy no command. + pub(crate) command: Arc, /// Something besides the command's own state refuses it: the gate, the modal rule, the instance's liveness or a /// focused component whose edit does nothing now. A key whose app-scope command its state alone disables is /// declined (`FrameOutput::declined`); a refused one is not. @@ -781,7 +782,7 @@ struct ShownFact { /// What a [`ShownFact`] shows: a bound component's command, or the commands a container holds. #[derive(Clone, Debug, PartialEq)] enum ShownCommands { - Bound(CommandRef), + Bound(Arc), Held(Arc<[CommandRef]>), } @@ -789,7 +790,7 @@ impl ShownFact { /// Whether the fact shows `command`. fn shows(&self, command: &CommandRef) -> bool { match &self.commands { - ShownCommands::Bound(bound) => bound == command, + ShownCommands::Bound(bound) => **bound == *command, ShownCommands::Held(held) => held.contains(command), } } @@ -822,8 +823,8 @@ pub fn holds(ctx: &Context, layer: LayerKey, rect: egui::Rect, commands: &[Comma /// Records that the bound component of `command` was shown at `rect` in `layer`, with `label`, for this pass and /// viewport: the report step calls it for a component wholly inside its clip. // PLAN: the caller is the report step (menus-w3); until it lands nothing in this crate calls it. -pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label, command: &CommandRef) { - register_shown(ctx, layer, rect, label, ShownCommands::Bound(command.clone())); +pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label, command: &Arc) { + register_shown(ctx, layer, rect, label, ShownCommands::Bound(Arc::clone(command))); } /// How many shown-command registrations the running viewport's last pass made: one per bound component and one per @@ -834,6 +835,20 @@ pub fn shown_registrations(ctx: &Context) -> usize { Facts::::of_last_pass(ctx).len() } +/// The commands the bound components of the running viewport's last pass showed, in registration order: the values +/// the facts hold, so two passes that copied no command give the same allocations. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn shown_commands(ctx: &Context) -> Vec> { + Facts::::of_last_pass(ctx) + .into_iter() + .filter_map(|fact| match fact.commands { + ShownCommands::Bound(command) => Some(command), + ShownCommands::Held(_) => None, + }) + .collect() +} + /// Where `command` was shown in the last pass: a bound component's clipped rect or a holder's rect. `None` unless it /// was wholly in view and not under another window. pub fn shown(ctx: &Context, command: &CommandRef) -> Option { diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index b0da0f3da0..c74fc6a036 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -959,7 +959,11 @@ impl Facts { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); let advance = |record: &mut FactRecord, step: PassStep| match step { - PassStep::Next => record.last = std::mem::take(&mut record.this), + // The buffers swap, so a pass reuses the room the pass before it grew. + PassStep::Next => { + std::mem::swap(&mut record.last, &mut record.this); + record.this.clear(); + } PassStep::Skipped => { record.last.clear(); record.this.clear(); diff --git a/crates/ui-contract/tests/it/runtime/shown.rs b/crates/ui-contract/tests/it/runtime/shown.rs index f74d64a108..c0f3939f25 100644 --- a/crates/ui-contract/tests/it/runtime/shown.rs +++ b/crates/ui-contract/tests/it/runtime/shown.rs @@ -1,8 +1,14 @@ //! Where commands were shown (`commands::holds`, `commands::shown`). +use craft_ui::contract::{CommandSet, MemoProps, MemoView, Props as _, Show as _}; use craft_ui::runtime::commands::{self, CommandRef}; use craft_ui::runtime::env::Label; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::{Fixture, Frames, MemoRun, last_frame_memo_runs, trial}; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::sync::Arc; /// A container that holds a hundred commands, as a menu title holds its menu's, registers once per pass: a replay of /// the menu bar then makes one registration per title, not one per command (photocraft#15493). Each command is still @@ -24,3 +30,52 @@ fn a_container_registers_its_commands_once() { } assert!(commands::shown(fixture.ctx(), &CommandRef::new("test.other")).is_none(), "a command nothing holds is not shown"); } + +/// The command every probe of the leaves view is bound to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] +#[command(prefix = "shownTrial")] +#[non_exhaustive] +enum Bound { + #[command(label = "Apply")] + Apply, +} + +/// A memoized view of `count` probes bound to `Bound::Apply`. +#[derive(MemoProps)] +struct Leaves { + count: usize, +} + +fn leaves(props: &mut Leaves, ui: &mut Ui) { + for _ in 0..props.count { + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).command(Bound::Apply).show(ui); + } +} + +/// A settled view's replay registers where its bound components show their commands with the very commands the run +/// registered, so a settled pass copies no command, however many it shows. +#[trial] +fn a_settled_pass_shows_its_commands_without_copying_them() { + for count in [10, 40] { + let mut frames = Frames::new(); + frames.screen(Vec2::new(400.0, 1400.0)); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(200.0, 1300.0)), |ui| { + MemoView::new("leaves", Leaves { count }, leaves).show(ui); + }); + }; + frames.idle(30, &mut show); + frames.frame(vec![], &mut show); + let before = commands::shown_commands(&frames.ctx); + frames.frame(vec![], &mut show); + let after = commands::shown_commands(&frames.ctx); + assert!(last_frame_memo_runs(&frames.ctx).iter().all(|(_, _, run)| *run != MemoRun::Ran), "the view of {count} probes is settled"); + assert_eq!(before.len(), count, "each of the {count} probes is shown"); + assert_eq!(after.len(), count, "the settled pass registers each of the {count} probes again"); + assert!( + before.iter().zip(&after).all(|(before, after)| Arc::ptr_eq(before, after)), + "a settled pass of {count} probes shows the commands the pass before it showed, not copies" + ); + } +} From 8401672c4c24ff7159d63510f146891c104c7ee8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 00:28:34 +0000 Subject: [PATCH 03/32] perf(ui-contract): menu titles share their held commands, and facts are read in place A menu title kept its held commands in a Vec, and commands::holds copied every command into a new Arc on each run of the title. MenuTitle keeps an Arc<[CommandRef]> and holds() shares it. Facts::of_last_pass cloned last pass's facts for every read; Facts::with_last_pass lends them to the reader instead, so the menu bar's is_open and is_focused answer without a copy. --- crates/menu/src/bar.rs | 2 +- .../ui-contract/src/runtime/commands/mod.rs | 35 +++++++++++-------- crates/ui-contract/src/runtime/memory.rs | 7 ++-- crates/ui-contract/src/testing/memory.rs | 2 +- crates/ui-contract/tests/it/runtime/shown.rs | 2 +- crates/ui-patterns/tests/it/panels/palette.rs | 3 +- crates/ui-widgets/src/menu/bar.rs | 13 +++---- 7 files changed, 36 insertions(+), 28 deletions(-) diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 3d1204ce5e..a852119d72 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -202,7 +202,7 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { .zip(&labels.menus) .map(|((menu, title), level)| { // The commands the title holds, for the palette's callout; a built-in has no command of the app. - let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect(); + let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect::>(); let row = MenuTitle::new(title.label.clone(), move |ui| shared.show(ui, &menu.children, level)).holds(held); match title.hidden { Some(letter) => row.mnemonic(letter), diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 9167d09123..f95bf0bde8 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -814,9 +814,9 @@ fn register_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label /// Records that a container at `rect` holds `commands`, for this pass and viewport. Not [`CommandInput::holds`], which /// turns hold bindings on. -pub fn holds(ctx: &Context, layer: LayerKey, rect: egui::Rect, commands: &[CommandRef], label: Label) { +pub fn holds(ctx: &Context, layer: LayerKey, rect: egui::Rect, commands: &Arc<[CommandRef]>, label: Label) { if !commands.is_empty() { - register_shown(ctx, layer, rect, label, ShownCommands::Held(commands.into())); + register_shown(ctx, layer, rect, label, ShownCommands::Held(Arc::clone(commands))); } } @@ -832,7 +832,7 @@ pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label #[cfg(feature = "testing")] #[doc(hidden)] pub fn shown_registrations(ctx: &Context) -> usize { - Facts::::of_last_pass(ctx).len() + Facts::::with_last_pass(ctx, <[ShownFact]>::len) } /// The commands the bound components of the running viewport's last pass showed, in registration order: the values @@ -840,13 +840,15 @@ pub fn shown_registrations(ctx: &Context) -> usize { #[cfg(feature = "testing")] #[doc(hidden)] pub fn shown_commands(ctx: &Context) -> Vec> { - Facts::::of_last_pass(ctx) - .into_iter() - .filter_map(|fact| match fact.commands { - ShownCommands::Bound(command) => Some(command), - ShownCommands::Held(_) => None, - }) - .collect() + Facts::::with_last_pass(ctx, |facts| { + facts + .iter() + .filter_map(|fact| match &fact.commands { + ShownCommands::Bound(command) => Some(Arc::clone(command)), + ShownCommands::Held(_) => None, + }) + .collect() + }) } /// Where `command` was shown in the last pass: a bound component's clipped rect or a holder's rect. `None` unless it @@ -854,11 +856,14 @@ pub fn shown_commands(ctx: &Context) -> Vec> { pub fn shown(ctx: &Context, command: &CommandRef) -> Option { let viewport = pass::current_viewport(ctx); let scrim = overlay::top_modal_in(ctx, viewport).and_then(|top| top.cover); - Facts::::of_last_pass(ctx) - .into_iter() - .filter(|fact| fact.shows(command)) - .find(|fact| !areas::rects_over(ctx, fact.layer, scrim).iter().any(|over| over.intersects(fact.rect))) - .map(|fact| Shown { rect: fact.rect, viewport, label: fact.label, holder: matches!(fact.commands, ShownCommands::Held(_)) }) + // The rects over a fact are read outside the facts' record, which `with_last_pass` holds. + let showing: Vec = Facts::::with_last_pass(ctx, |facts| facts.iter().filter(|fact| fact.shows(command)).cloned().collect()); + showing.into_iter().find(|fact| !areas::rects_over(ctx, fact.layer, scrim).iter().any(|over| over.intersects(fact.rect))).map(|fact| Shown { + rect: fact.rect, + viewport, + label: fact.label, + holder: matches!(fact.commands, ShownCommands::Held(_)), + }) } /// Where a command was shown, from [`shown`]. diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index c74fc6a036..a5fcd8cfaa 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -949,10 +949,11 @@ impl Facts { Self::with_record(ctx, |record| record.this.push(fact)); } - /// The facts the running viewport's previous pass registered, in registration order. + /// `f` on the facts the running viewport's previous pass registered, in registration order. `f` reaches no + /// service: the record is held while it runs. #[doc(hidden)] - pub fn of_last_pass(ctx: &Context) -> Vec { - Self::with_record(ctx, |record| record.last.clone()) + pub fn with_last_pass(ctx: &Context, f: impl FnOnce(&[T]) -> R) -> R { + Self::with_record(ctx, |record| f(&record.last)) } fn with_record(ctx: &Context, f: impl FnOnce(&mut FactRecord) -> R) -> R { diff --git a/crates/ui-contract/src/testing/memory.rs b/crates/ui-contract/src/testing/memory.rs index 5f029eb593..e2f9745b87 100644 --- a/crates/ui-contract/src/testing/memory.rs +++ b/crates/ui-contract/src/testing/memory.rs @@ -95,7 +95,7 @@ pub fn register_fact(ctx: &Context) -> Vec { - Facts::of_last_pass(ctx) + Facts::with_last_pass(ctx, <[T]>::to_vec) } /// Runs `f` on a child `Ui` of `ui`. diff --git a/crates/ui-contract/tests/it/runtime/shown.rs b/crates/ui-contract/tests/it/runtime/shown.rs index c0f3939f25..835a7639b2 100644 --- a/crates/ui-contract/tests/it/runtime/shown.rs +++ b/crates/ui-contract/tests/it/runtime/shown.rs @@ -16,7 +16,7 @@ use std::sync::Arc; #[trial] fn a_container_registers_its_commands_once() { let held: Vec = (0..100).map(|i| CommandRef::new(format!("test.held{i}"))).collect(); - let shown = held.clone(); + let shown: Arc<[CommandRef]> = held.clone().into(); let mut fixture = Fixture::new(move |ui| { let rect = egui::Rect::from_min_size(ui.max_rect().min, egui::vec2(40.0, 20.0)); commands::holds(ui.ctx(), ui.layer_id(), rect, &shown, Label::from("Image")); diff --git a/crates/ui-patterns/tests/it/panels/palette.rs b/crates/ui-patterns/tests/it/panels/palette.rs index ecfd5ea24a..4be3f59a23 100644 --- a/crates/ui-patterns/tests/it/panels/palette.rs +++ b/crates/ui-patterns/tests/it/panels/palette.rs @@ -14,6 +14,7 @@ use craft_ui::testing::{Fixture, Registry, trial}; use egui::{Key, Modifiers, Pos2, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; /// App commands with the default modal rule: blocked while a dialog is open. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] @@ -488,7 +489,7 @@ fn the_active_row_marks_its_shown_control_and_a_hidden_home_goes_to_the_footer() // Flip is held by a rect in the corner, the way a menu title holds its commands; Rotate has a bound button. let mut rig = rig(entries, Some(vec![TrialCommand::Flip.into()]), false, |ui| { let corner = egui::Rect::from_min_size(ui.max_rect().min, Vec2::new(60.0, 20.0)); - commands::holds(ui.ctx(), ui.layer_id(), corner, &[TrialCommand::Flip.into()], Label::from("Rail slot")); + commands::holds(ui.ctx(), ui.layer_id(), corner, &Arc::from([CommandRef::from(TrialCommand::Flip)]), Label::from("Rail slot")); ui.add_space(24.0); Button::command(TrialCommand::Rotate).show(ui); }); diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index 39d3fded6c..1348430404 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -45,6 +45,7 @@ use craft_host::target::MenuPlacement; use craft_keymap::mnemonic; use craft_theme::Flags; use egui::{Context, Pos2, Rect, Response, Ui, Vec2}; +use std::sync::Arc; const TITLE: PartKey = PartKey::new("title"); const MORE: PartKey = PartKey::new("more"); @@ -207,7 +208,7 @@ type TitleText = (String, Option<(char, Option)>); pub struct MenuTitle<'a> { label: Label, body: Box, - holds: Vec, + holds: Arc<[CommandRef]>, /// The letter that opens the menu in place of the bar's own pick. mnemonic: Option, } @@ -215,7 +216,7 @@ pub struct MenuTitle<'a> { impl<'a> MenuTitle<'a> { /// A menu titled `label` (a `&` marks the mnemonic) whose rows `body` shows. pub fn new(label: impl Into