From d06fd33dfb967e28fc69e8692e41bf804c4658cb Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:39:51 +0000 Subject: [PATCH 1/4] Add count-trial counters for settling, text layout and measure asks, and an idle-frame trial --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 19 ++- crates/ui-contract/src/runtime/measure.rs | 116 ++++++++++++++++++ crates/ui-contract/src/testing/mod.rs | 5 +- crates/ui-widgets/tests/it/body/settle.rs | 72 +++++++---- 7 files changed, 190 insertions(+), 25 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 6293bebde..856259c7a 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 0170bb71d..e75201bd6 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size))); diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 113581b1b..1d64bf0df 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 8cefd9fb5..7850311c1 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -240,7 +240,7 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { /// pass gets the same answer, so a measuring run and the real run lay out the same children. pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -> Rect, sizing: bool, estimate: Vec2) -> Decision { let targets = crate::runtime::focus::targets(ctx); - with(ctx, |store, pass_nr, frame| { + let decision = with(ctx, |store, pass_nr, frame| { let entry = store.touch(Some(view.owner), id, frame); let kind = usize::from(!sizing); // A child the other kind of run showed last takes that run's extent. @@ -255,7 +255,11 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - } }; if skip { Decision::Skip(size) } else { Decision::Run } - }) + }); + if matches!(decision, Decision::Skip(_)) { + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); + } + decision } /// Records what a run that showed the child `id` found: its extent in a run of this kind and, from a real run, what @@ -298,6 +302,17 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { + use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; + // The 8 bytes of a keyed call's content version are the key fed in. + if content.is_some() { + count_memo_key_bytes(ctx, 8); + } + let size = decide_settled(ctx, owner, id, sizing, place, content); + count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); + size +} + +fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index c281c04a5..5bed8a5e6 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -305,3 +305,119 @@ pub(crate) fn count_least(ctx: &Context, id: Id) { pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| log.runs.clone()) } + +/// What a settling child's decision was. +#[cfg(feature = "testing")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Settle { + /// The child ran. + Ran, + /// The child's last run was replayed in place of running. + Replayed, + /// The child is out of view and took its last extent without running. + OutOfView, +} + +/// The settled-test decisions of one pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct SettleLog { + pass: u64, + decisions: Vec<(Id, Settle)>, +} + +/// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and +/// `lazy::decide` (out of view); a rename of that decision point moves both calls. +pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { + #[cfg(feature = "testing")] + { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); + } + #[cfg(not(feature = "testing"))] + let _ = (ctx, id, what); +} + +/// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. +#[cfg(feature = "testing")] +pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) +} + +/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct PassTotals { + pass: u64, + key_bytes: usize, + text_layouts: u32, + asks: Vec<(&'static str, u32)>, +} + +#[cfg(feature = "testing")] +fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = PassTotals { pass, ..PassTotals::default() }; + } + f(log) + }) +} + +#[cfg(feature = "testing")] +fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) +} + +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.key_bytes += bytes); + #[cfg(not(feature = "testing"))] + let _ = (ctx, bytes); +} + +/// The bytes fed into memo keys in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { + last_totals(ctx, |log| log.key_bytes, 0) +} + +/// Counts a text layout handed to egui (`text_layout::layout`, `layout_with`) in this pass. +pub(crate) fn count_text_layout(ctx: &Context) { + #[cfg(feature = "testing")] + totals(ctx, |log| log.text_layouts += 1); + #[cfg(not(feature = "testing"))] + let _ = ctx; +} + +/// The text layouts handed to egui in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_text_layouts(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.text_layouts, 0) +} + +/// Counts a measure call of a leaf component of the type `name` in this pass. +pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { + #[cfg(feature = "testing")] + totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { + Some((_, count)) => *count += 1, + None => log.asks.push((name, 1)), + }); + #[cfg(not(feature = "testing"))] + let _ = (ctx, name); +} + +/// The leaf types that were asked to measure in the last pass, and how many times each. +#[cfg(feature = "testing")] +pub fn last_pass_measure_asks(ctx: &Context) -> Vec<(&'static str, u32)> { + last_totals(ctx, |log| log.asks.clone(), Vec::new()) +} diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 90ed467df..9dcb90e6a 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -41,8 +41,9 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ - active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_pass_body_runs as last_pass_measuring_runs, - last_pass_runs, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, + Settle, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, + last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_runs, last_pass_settles, + last_pass_text_layouts, least_runs as shrink_least_runs, 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-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index f7dae2c36..317b8d902 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -13,7 +13,7 @@ use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Comm use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; -use craft_ui::testing::{Fixture, Frames, last_pass_measuring_runs, trial}; +use craft_ui::testing::{Fixture, Frames, Settle, last_pass_measuring_runs, last_pass_runs, last_pass_settles, last_pass_text_layouts, trial}; use egui::{Id, Pos2, Rect, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -36,6 +36,8 @@ struct Scene { versions: [Cell>; 2], repaints: Cell, app_repaints: Cell, + /// Whether the scene shows only what is outside the settling children. + bare: Cell, runs: [Cell; 2], buttons: [Cell<(Id, Rect)>; 2], seen: Seen, @@ -51,6 +53,7 @@ impl Scene { versions: Default::default(), repaints: Cell::new(false), app_repaints: Cell::new(false), + bare: Cell::new(false), runs: Default::default(), buttons: [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))], seen: Seen::default(), @@ -73,28 +76,30 @@ impl Scene { if self.editor_first { self.editor(ui); } - in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { - self.child("reader", 0).show(ui, |ui| { - self.runs[0].set(self.runs[0].get() + 1); - let response = Button::new("Alpha").show(ui).response; - self.buttons[0].set((response.id, response.rect)); - Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); - }); - self.child("other", 1).show(ui, |ui| { - self.runs[1].set(self.runs[1].get() + 1); - if self.repaints.get() { - frame::request_repaint(ui.ctx()); - } - // In a body, whose measure a run that is not settled takes from what its last run kept. - Stack::new().show(ui, |ui, _| { - let response = Button::new("Beta").show(ui).response; - self.buttons[1].set((response.id, response.rect)); + if !self.bare.get() { + in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { + self.child("reader", 0).show(ui, |ui| { + self.runs[0].set(self.runs[0].get() + 1); + let response = Button::new("Alpha").show(ui).response; + self.buttons[0].set((response.id, response.rect)); + Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); + }); + self.child("other", 1).show(ui, |ui| { + self.runs[1].set(self.runs[1].get() + 1); + if self.repaints.get() { + frame::request_repaint(ui.ctx()); + } + // In a body, whose measure a run that is not settled takes from what its last run kept. + Stack::new().show(ui, |ui, _| { + let response = Button::new("Beta").show(ui).response; + self.buttons[1].set((response.id, response.rect)); + }); + if self.spinner { + Spinner::new().show(ui); + } }); - if self.spinner { - Spinner::new().show(ui); - } }); - }); + } if !self.editor_first { self.editor(ui); } @@ -146,6 +151,31 @@ fn a_settled_child_does_not_run_and_still_paints() { } } +/// After two warm-up frames, an idle frame with no input runs nothing that settles: every keyed child replays, the +/// components that run are those outside every settling child, the frame takes one pass and lays out no text. +#[trial] +fn an_idle_frame_runs_nothing_that_settles() { + let scene = Scene::new(false, false); + scene.versions.iter().for_each(|version| version.set(Some(1))); + let mut frames = Frames::new(); + scene.settle(&mut frames); + let reference = Scene::new(false, false); + reference.bare.set(true); + let mut bare = Frames::new(); + reference.settle(&mut bare); + let outside = { + reference.frame(&mut bare, vec![]); + last_pass_runs(&bare.ctx).iter().map(|(_, runs)| runs).sum::() + }; + let passes = frames.frame(vec![], |ui| scene.show(ui)); + let ran = last_pass_settles(&frames.ctx).into_iter().filter(|(_, what)| *what == Settle::Ran).count(); + let runs = last_pass_runs(&frames.ctx); + assert_eq!(ran, 0, "an idle frame ran keyed children: {:?}", last_pass_settles(&frames.ctx)); + assert_eq!(runs.iter().map(|(_, runs)| runs).sum::(), outside, "components ran inside settling children: {runs:?}"); + assert_eq!(passes, 1, "an idle frame takes one pass"); + assert_eq!(last_pass_text_layouts(&frames.ctx), 0, "an idle frame laid out text"); +} + /// The pointer over a settled child runs it, and only it, in the frame it arrives, from the measures its last run /// kept; leaving, the child runs until its hover has faded out, then settles again. #[trial] From ce3513f84a3a8fd2403298d5adfc0c0920f5d999 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:41:32 +0000 Subject: [PATCH 2/4] Gate the counters on the testing feature --- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/runtime/egui/text_edit.rs | 1 + .../src/runtime/egui/text_layout.rs | 1 + crates/ui-contract/src/runtime/lazy.rs | 23 ++++++------ crates/ui-contract/src/runtime/measure.rs | 35 +++++++------------ 5 files changed, 29 insertions(+), 32 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 856259c7a..6ccec0dbf 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -27,6 +27,7 @@ pub(crate) fn measure_content( value: Option<&ValueOf>, ) -> (Vec2, Inputs) { let cx = measure_cx::(input, style, resolved, value); + #[cfg(feature = "testing")] crate::runtime::measure::count_measure_ask(input.ui.ctx(), std::any::type_name::()); layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index e75201bd6..237e116be 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -127,6 +127,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { } None => job.append(text, 0.0, plain), } + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ui.ctx()); ui.fonts_mut(|fonts| crate::runtime::egui::text_layout::layout_with(fonts, job)) }; diff --git a/crates/ui-contract/src/runtime/egui/text_layout.rs b/crates/ui-contract/src/runtime/egui/text_layout.rs index 1d64bf0df..d07364659 100644 --- a/crates/ui-contract/src/runtime/egui/text_layout.rs +++ b/crates/ui-contract/src/runtime/egui/text_layout.rs @@ -10,6 +10,7 @@ use std::sync::Arc; /// different logical heights at different interface scales (14.5 at scale 2, 15 at scale 1), and a wrapped text would /// change height with the scale. pub(crate) fn layout(ctx: &Context, job: LayoutJob) -> Arc { + #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ctx); ctx.fonts_mut(|fonts| layout_with(fonts, job)) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 7850311c1..b6fd3756c 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -256,6 +256,7 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - }; if skip { Decision::Skip(size) } else { Decision::Run } }); + #[cfg(feature = "testing")] if matches!(decision, Decision::Skip(_)) { crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::OutOfView); } @@ -302,17 +303,11 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - for a child with no content version: no input other than pointer motion this frame or the one before; /// - the run did nothing a replay cannot repeat (`runtime::replay`). pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { - use crate::runtime::measure::{Settle, count_memo_key_bytes, count_settle}; - // The 8 bytes of a keyed call's content version are the key fed in. + // Keyed calls feed their 8-byte content version into the key. + #[cfg(feature = "testing")] if content.is_some() { - count_memo_key_bytes(ctx, 8); + crate::runtime::measure::count_memo_key_bytes(ctx, 8); } - let size = decide_settled(ctx, owner, id, sizing, place, content); - count_settle(ctx, id, if size.is_some() { Settle::Replayed } else { Settle::Ran }); - size -} - -fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, content: Option) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); @@ -355,15 +350,23 @@ fn decide_settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: settled.map(|settled| (entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(settled.rect.size()), settled)) }); // The pointer over it, or a press that started on it, is read outside the store. - let (size, settled) = settled?; + let Some((size, settled)) = settled else { + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); + return None; + }; if engaged(ctx, &settled) { with(ctx, |store, pass_nr, _| { if let Some(entry) = store.entries.get_mut(&id) { entry.replays = Some((pass_nr, false)); } }); + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Ran); return None; } + #[cfg(feature = "testing")] + crate::runtime::measure::count_settle(ctx, id, crate::runtime::measure::Settle::Replayed); Some(size) } diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 5bed8a5e6..85afc682f 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -328,19 +328,15 @@ struct SettleLog { /// Counts the decision about the settling child `id` in this pass. Fed by `lazy::settled` (ran, replayed) and /// `lazy::decide` (out of view); a rename of that decision point moves both calls. +#[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { - #[cfg(feature = "testing")] - { - let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { - if log.pass != pass { - *log = SettleLog { pass, decisions: Vec::new() }; - } - log.decisions.push((id, what)); - }); - } - #[cfg(not(feature = "testing"))] - let _ = (ctx, id, what); + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = SettleLog { pass, decisions: Vec::new() }; + } + log.decisions.push((id, what)); + }); } /// The settled-test decisions of the last pass, by child id, in the order they were made; empty when that pass made none. @@ -377,12 +373,11 @@ fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } -/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`. +/// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes +/// per call with a content version). +#[cfg(feature = "testing")] pub(crate) fn count_memo_key_bytes(ctx: &Context, bytes: usize) { - #[cfg(feature = "testing")] totals(ctx, |log| log.key_bytes += bytes); - #[cfg(not(feature = "testing"))] - let _ = (ctx, bytes); } /// The bytes fed into memo keys in the last pass. @@ -392,11 +387,9 @@ pub fn last_pass_memo_key_bytes(ctx: &Context) -> usize { } /// 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) { - #[cfg(feature = "testing")] totals(ctx, |log| log.text_layouts += 1); - #[cfg(not(feature = "testing"))] - let _ = ctx; } /// The text layouts handed to egui in the last pass. @@ -406,14 +399,12 @@ pub fn last_pass_text_layouts(ctx: &Context) -> u32 { } /// Counts a measure call of a leaf component of the type `name` in this pass. +#[cfg(feature = "testing")] pub(crate) fn count_measure_ask(ctx: &Context, name: &'static str) { - #[cfg(feature = "testing")] totals(ctx, |log| match log.asks.iter_mut().find(|(ty, _)| *ty == name) { Some((_, count)) => *count += 1, None => log.asks.push((name, 1)), }); - #[cfg(not(feature = "testing"))] - let _ = (ctx, name); } /// The leaf types that were asked to measure in the last pass, and how many times each. From 972a86af6582034237877a0266097769f62b2baa Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:25:25 +0000 Subject: [PATCH 3/4] Keep the counters in pass-local state; mark Settle non_exhaustive --- crates/ui-contract/src/runtime/measure.rs | 13 +++++++------ crates/ui-contract/src/runtime/pass_state.rs | 4 ++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 85afc682f..912f37b57 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -309,6 +309,7 @@ pub fn least_runs(ctx: &Context) -> Vec<(Id, u32)> { /// What a settling child's decision was. #[cfg(feature = "testing")] #[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub enum Settle { /// The child ran. Ran, @@ -321,7 +322,7 @@ pub enum Settle { /// The settled-test decisions of one pass. #[cfg(feature = "testing")] #[derive(Default)] -struct SettleLog { +pub(crate) struct SettleLog { pass: u64, decisions: Vec<(Id, Settle)>, } @@ -331,7 +332,7 @@ struct SettleLog { #[cfg(feature = "testing")] pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = SettleLog { pass, decisions: Vec::new() }; } @@ -343,13 +344,13 @@ pub(crate) fn count_settle(ctx: &Context, id: Id, what: Settle) { #[cfg(feature = "testing")] pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) + pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) } /// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. #[cfg(feature = "testing")] #[derive(Default)] -struct PassTotals { +pub(crate) struct PassTotals { pass: u64, key_bytes: usize, text_layouts: u32, @@ -359,7 +360,7 @@ struct PassTotals { #[cfg(feature = "testing")] fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { let pass = ctx.cumulative_pass_nr(); - store::with::(ctx, |log| { + pass_state::with::(ctx, |log| { if log.pass != pass { *log = PassTotals { pass, ..PassTotals::default() }; } @@ -370,7 +371,7 @@ fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { #[cfg(feature = "testing")] fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { let last = ctx.cumulative_pass_nr().saturating_sub(1); - store::with::(ctx, |log| if log.pass == last { f(log) } else { none }) + pass_state::with::(ctx, |log| if log.pass == last { f(log) } else { none }) } /// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 9e0fb9443..18f837d8d 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -113,6 +113,10 @@ pass_state! { style_record: crate::testing::style::StyleRecord, #[cfg(feature = "testing")] type_runs: crate::runtime::measure::TypeRuns, + #[cfg(feature = "testing")] + settle_log: crate::runtime::measure::SettleLog, + #[cfg(feature = "testing")] + pass_totals: crate::runtime::measure::PassTotals, } records { focus: crate::runtime::focus::State, From fc8f48ff967337636db58de10e5605f8013a852a Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:31:24 +0000 Subject: [PATCH 4/4] Command board: maps for instances, modal roots and shown readers; node facts after the node check; chord texts from the keymap build --- .../ui-contract/src/contract/steps/report.rs | 72 ++++--- .../ui-contract/src/runtime/commands/board.rs | 190 ++++++++++++------ .../ui-contract/src/runtime/commands/mod.rs | 12 +- crates/ui-contract/src/runtime/measure.rs | 15 +- crates/ui-panels/src/rails/flyout.rs | 5 +- crates/ui-shell/tests/it/commands/board.rs | 61 +++++- crates/ui-shell/tests/it/commands/kit.rs | 31 +++ 7 files changed, 279 insertions(+), 107 deletions(-) diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index 2dd8a846d..7dafc2583 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -6,7 +6,7 @@ use crate::contract::cx::{CxCore, Decls}; use crate::contract::run::{ErasedPass, TypeFacts}; use crate::primitives::FaceRecord; use crate::runtime::access::{self, Access, FaceFacts, Own, Politeness, Role, SetPosition, SubDecl, SubNode, scope}; -use crate::runtime::commands::{self, ResolvedCommand}; +use crate::runtime::commands::ResolvedCommand; use crate::runtime::env::{Label, Message}; use crate::runtime::focus::{self}; use crate::runtime::keys; @@ -33,8 +33,15 @@ pub(crate) struct ReportIn<'a> { } /// The bound command's hint and shortcut text, which describe and key its node. -fn command_facts(command: &ResolvedCommand, platform: craft_keymap::Platform) -> (Option<&str>, Option) { - (command.hint.as_deref(), command.chord.as_ref().map(|chord| chord.display(platform))) +fn command_facts<'a>(ctx: &egui::Context, command: &'a ResolvedCommand) -> (Option<&'a str>, Option<&'a str>) { + let text = command.chord_text.as_deref(); + #[cfg(feature = "testing")] + if text.is_some() { + crate::runtime::measure::count_chord_text(ctx); + } + #[cfg(not(feature = "testing"))] + let _ = ctx; + (command.hint.as_deref(), text) } /// The message of a validity that warns, refuses or errs, and whether it warns. @@ -78,40 +85,10 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> } } *core.value_text.borrow_mut() = value_text; - for node in &mut access.nodes { - if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) { - node.expanded = Some(toggle.open); - } - } let role = access.role.unwrap_or(facts.role); - access.access_key = access.access_key.or(core.resolved.access_key); - if access.grid == access::GridPlace::default() { - access.grid = core.grid; - } debug_assert!(access.role.is_none_or(|alt| facts.alt_roles.contains(&alt)), "`Access::role` picks one of `ALT_ROLES`"); let flags = core.state.flags; let resolved = core.resolved; - let platform = commands::platform(ctx); - let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(command, platform)); - let shortcut = shortcut.as_deref(); - for (_, label) in &mut access.custom_actions { - *label = core.env.resolve(label); - } - let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text)); - let tooltip = tooltip_text.as_ref().map(Label::as_str); - if access.live.is_none() { - access.live = input.live; - } - if access.expanded.is_none() { - access.expanded = input.expanded; - } - if access.position.is_none() { - access.position = input.position; - } - if access.position.is_none() { - access.position = - input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position)); - } let paint = core.paint.borrow(); if role == Role::Merged { let facts = scope::Merged { @@ -132,6 +109,35 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> if !input.node { return; } + // Facts that only a node shows are built after the node check. + for node in &mut access.nodes { + if let Some(toggle) = core.toggles.iter().find(|toggle| toggle.part == node.part) { + node.expanded = Some(toggle.open); + } + } + access.access_key = access.access_key.or(core.resolved.access_key); + if access.grid == access::GridPlace::default() { + access.grid = core.grid; + } + let (hint, shortcut) = core.command.as_deref().map_or((None, None), |command| command_facts(ctx, command)); + for (_, label) in &mut access.custom_actions { + *label = core.env.resolve(label); + } + let tooltip_text = resolved.tooltip.map(|tooltip| core.env.resolve(&tooltip.spec().text)); + let tooltip = tooltip_text.as_ref().map(Label::as_str); + if access.live.is_none() { + access.live = input.live; + } + if access.expanded.is_none() { + access.expanded = input.expanded; + } + if access.position.is_none() { + access.position = input.position; + } + if access.position.is_none() { + access.position = + input.group.and_then(|group| focus::group_position(ctx, id, group)).or_else(|| core.env.facts_of(id).map(|facts| facts.position)); + } let inner_of = access::fold::owner_of(ctx, id); let folded = access::fold::take(ctx, id); if access.value.is_none() { diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 0c3d7f8a7..ca350161d 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -32,6 +32,44 @@ enum Declaration { Focused { inactive: bool }, } +/// The registered instances in registration order, which `pick_instance` ranks by, with their positions by id. +#[derive(Default)] +struct Instances { + list: Vec, + at: HashMap, +} + +impl Instances { + fn get(&self, id: Id) -> Option<&Instance> { + self.at.get(&id).map(|at| &self.list[*at]) + } + + fn iter(&self) -> std::slice::Iter<'_, Instance> { + self.list.iter() + } + + /// Registers `instance`, keeping the place of one already registered under the same id. + fn upsert(&mut self, instance: Instance) { + match self.at.get(&instance.id) { + Some(at) => self.list[*at] = instance, + None => { + self.at.insert(instance.id, self.list.len()); + self.list.push(instance); + } + } + } + + /// Keeps the instances `keep` accepts, in their order. + fn retain(&mut self, mut keep: impl FnMut(&Instance) -> bool) { + self.list.retain(|instance| keep(instance)); + self.at = self.list.iter().enumerate().map(|(at, instance)| (instance.id, at)).collect(); + } + + fn contains(&self, id: Id) -> bool { + self.at.contains_key(&id) + } +} + /// A container instance that receives scoped commands. struct Instance { id: Id, @@ -54,6 +92,8 @@ struct KeymapCache { edit_chords: Arc<[(EditCommand, Chord)]>, /// The chords bound to the window's keys, which the input hook takes before any component. window_shortcuts: Arc<[(WindowShortcut, Chord)]>, + /// `BuiltKeymap::shown_text`. + shown_text: Arc>>, } /// A momentary command whose key is down: its release fires the command again. @@ -85,7 +125,7 @@ pub(crate) struct Board { out: Vec, /// The commands instances took since the last `FrameOutput`, in order. delivered: Vec, - instances: Vec, + instances: Instances, /// The focused component of each viewport's last step 12 and the instances around it. chains: HashMap, /// The focused component and its chain before the one in `chains`, per viewport; while the focus is in the menus @@ -98,7 +138,7 @@ pub(crate) struct Board { matcher: Matcher, held: Vec, /// The top modal layer's root container of each viewport that has one. - modal_roots: Vec<(ViewportId, Id)>, + modal_roots: HashMap, /// The states published this pass, and the pass before, by an instance inside the top modal layer. modal_published: HashSet, modal_published_last: HashSet, @@ -129,7 +169,7 @@ fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool { } /// Who read a command's resolution: the vantage `begin` resolves it from again. -#[derive(Clone, PartialEq, Eq)] +#[derive(Clone, PartialEq, Eq, Hash)] enum Reader { /// A surface with no component of its own (`resolve_global`): the key focus of the running pass. Global, @@ -142,21 +182,19 @@ enum Reader { InMenu(Id, CommandChain), } -/// What a reader was shown the last time it resolved a command. -struct Shown { - reader: Reader, - resolved: ResolvedCommand, -} - -/// The readers of each state key in each viewport. -type ShownMap = HashMap<(StateKey, ViewportId), Vec>; +/// What each reader was shown the last time it resolved a command, by the viewport and the state key it read. The +/// readers of a key stay in the order they first read it: the gate is app code, and `wake_shown` asks it in that order. +type ShownMap = HashMap>>; /// Keeps `resolved` as what `reader` of `viewport` was shown under `key`, in place of what it was shown before. fn keep_shown(shown: &mut ShownMap, key: StateKey, viewport: ViewportId, reader: Reader, resolved: &ResolvedCommand) { - let readers = shown.entry((key, viewport)).or_default(); - match readers.iter_mut().find(|entry| entry.reader == reader) { - Some(entry) => entry.resolved.clone_from(resolved), - None => readers.push(Shown { reader, resolved: resolved.clone() }), + keep_in(shown.entry(viewport).or_default().entry(key).or_default(), reader, resolved); +} + +fn keep_in(readers: &mut Vec<(Reader, ResolvedCommand)>, reader: Reader, resolved: &ResolvedCommand) { + match readers.iter_mut().find(|(kept, _)| *kept == reader) { + Some((_, kept)) => kept.clone_from(resolved), + None => readers.push((reader, resolved.clone())), } } @@ -238,7 +276,7 @@ impl Board { /// The instance of `scope` a command routed to `at` goes to: `at` when it is an instance of the scope itself (a /// canvas), else the innermost instance in `around`, the chain of the context `at` was shown in. fn instance_around(&self, at: Id, around: &CommandChain, scope: &str) -> Option { - let own = self.instances.iter().any(|i| i.id == at && self.within(i.scope.name(), scope)); + let own = self.instances.get(at).is_some_and(|i| self.within(i.scope.name(), scope)); if own { Some(at) } else { self.innermost(around, scope) } } @@ -262,7 +300,7 @@ impl Board { } fn is_live(&self, ctx: &Context, id: Id) -> bool { - self.instances.iter().any(|i| i.id == id && self.live(ctx, i)) + self.instances.get(id).is_some_and(|i| self.live(ctx, i)) } /// The definition of the command `id`: the linked sets', else the frame's app catalog's. @@ -301,7 +339,7 @@ impl Board { /// is declared inside, after its own. fn scopes_around(&self, chain: &[Id]) -> Vec<&'static str> { let mut scopes: Vec<&'static str> = Vec::new(); - for instance in chain.iter().rev().filter_map(|id| self.instances.iter().find(|i| i.id == *id)) { + for instance in chain.iter().rev().filter_map(|id| self.instances.get(*id)) { let lineage = self.lineage(instance.scope.name()); scopes.push(lineage[0]); let parents: Vec<&'static str> = lineage[1..].iter().copied().filter(|scope| !scopes.contains(scope)).collect(); @@ -318,7 +356,7 @@ impl Board { } fn is_modal_root(&self, id: Id) -> bool { - self.modal_roots.iter().any(|(_, root)| *root == id) + self.modal_roots.values().any(|root| *root == id) } /// Where `command` goes when a source with no component of its own fires it: `None` for an app-scope command, @@ -398,10 +436,12 @@ impl Board { }; let live = app || instance.is_some_and(|id| self.is_live(ctx, id)); let chord = self.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command)); + let chord_text = chord.and_then(|chord| self.keymap.as_ref()?.shown_text.get(&chord).cloned()); let resolved = ResolvedCommand { label: state.and_then(|s| s.title_ref().cloned()).unwrap_or_else(|| Arc::from(def.map_or(command.id.as_str(), |def| def.label.as_str()))), icon: def.and_then(|def| def.icon.clone()), chord, + chord_text, enabled: flags.enabled && modal && live && !matches!(declaring, Some(Declaration::Focused { inactive: true })), checked: flags.checked, marked: state.is_some_and(CommandState::is_marked), @@ -464,6 +504,8 @@ struct BuiltKeymap { keymap: Arc, edit_chords: Arc<[(EditCommand, Chord)]>, window_shortcuts: Arc<[(WindowShortcut, Chord)]>, + /// The text of every chord the keymap shows, written once when the keymap is built. + shown_text: Arc>>, } /// The keymap of `defs` on `platform` under `overrides`. @@ -475,6 +517,19 @@ fn keymap_of(defs: Vec, scopes: Scopes, platform: Platform, override keymap } +#[cfg(feature = "testing")] +thread_local! { + static CHORD_TEXT_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many chord texts this thread's keymap builds have written: one per distinct shown chord per build, never one +/// per report. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn chord_text_builds() -> u64 { + CHORD_TEXT_BUILDS.with(std::cell::Cell::get) +} + #[cfg(feature = "testing")] thread_local! { static KEYMAP_BUILDS: std::cell::Cell = const { std::cell::Cell::new(0) }; @@ -558,7 +613,17 @@ fn build_keymap(registry: ®istry::Registry, app: Option<&AppCatalog>, platfor keymap.bindings(command).into_iter().filter(|binding| !binding.trigger.double).map(move |binding| (edit, binding.trigger.chord)) }) .collect(); - BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts } + let mut shown_text = HashMap::new(); + for def in keymap.catalog() { + if let Some(chord) = keymap.shown_chord(&def.command) { + shown_text.entry(chord).or_insert_with(|| { + #[cfg(feature = "testing")] + CHORD_TEXT_BUILDS.with(|builds| builds.set(builds.get() + 1)); + Arc::from(chord.display(platform)) + }); + } + } + BuiltKeymap { keymap: Arc::new(keymap), edit_chords, window_shortcuts, shown_text: Arc::new(shown_text) } } /// The keymap of each shared registry (with or without the stories' sets) on each platform with no overrides. It @@ -596,7 +661,7 @@ pub(crate) fn innermost(ctx: &Context, chain: &CommandChain, scope: &str) -> Opt } /// The platform the keymap and the chords shown are read for. -pub(crate) fn platform(ctx: &Context) -> Platform { +fn platform(ctx: &Context) -> Platform { crate::runtime::windows::os_of(ctx) } @@ -630,9 +695,10 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { }); let mut shadowed = Vec::new(); if stale { - let BuiltKeymap { keymap, edit_chords, window_shortcuts } = + let BuiltKeymap { keymap, edit_chords, window_shortcuts, shown_text } = keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref()); - board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts }); + board.keymap = + Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts, shown_text }); for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) { if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) { shadowed.push(def.command.id.clone()); @@ -699,15 +765,7 @@ fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_in(ctx, scope, id, layer)); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); - with(ctx, |board| match board.instances.iter_mut().find(|i| i.id == id) { - Some(instance) => { - instance.scope = scope; - instance.viewport = viewport; - instance.stamp = stamp; - instance.layer = layer; - } - None => board.instances.push(Instance { id, scope, viewport, stamp, layer }), - }); + with(ctx, |board| board.instances.upsert(Instance { id, scope, viewport, stamp, layer })); } /// Records the instances around the component `id`, which holds key focus in the running pass of its viewport. The @@ -731,14 +789,16 @@ pub(crate) fn note_focus(ctx: &Context, id: Id, chain: &CommandChain) { pub(crate) fn set_modal_open(ctx: &Context, open: bool, viewport: ViewportId, root: Option) { with(ctx, |board| { board.here.modal_open = open; - board.modal_roots.retain(|(of, _)| *of != viewport); - board.modal_roots.extend(root.map(|root| (viewport, root))); + match root { + Some(root) => board.modal_roots.insert(viewport, root), + None => board.modal_roots.remove(&viewport), + }; }); } /// The root of the top modal layer of `viewport`, if one is open. pub(crate) fn modal_root(ctx: &Context, viewport: ViewportId) -> Option { - with(ctx, |board| board.modal_roots.iter().find(|(of, _)| *of == viewport).map(|(_, root)| *root)) + with(ctx, |board| board.modal_roots.get(&viewport).copied()) } /// Which instances a resolution counts as inside the top modal layer, where `ModalRule::InDialogs` and `Blocked` @@ -897,35 +957,35 @@ fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> /// and what the first pass's call kept, so it wakes only the readers whose resolution the first pass changed (a modal /// layer it opened or closed), once. fn wake_shown(ctx: &Context, viewport: ViewportId) { - let mut shown = with(ctx, |board| std::mem::take(&mut board.shown)); + let mut table = with(ctx, |board| board.shown.remove(&viewport)).unwrap_or_default(); let mut changed = Vec::new(); - for ((key, of), readers) in &mut shown { - if *of != viewport { - continue; - } + for (key, readers) in &mut table { // A reader beneath a layer or inside a menu that is no longer shown is gone with it. - readers.retain(|entry| match entry.reader { - Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, layer), + readers.retain(|(reader, _)| match reader { + Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, *layer), _ => true, }); - for entry in readers.iter_mut() { + for (reader, kept) in readers.iter_mut() { // The gate is app code and may resolve commands itself, so no board lock is held here. - let (resolved, _) = resolve_as(ctx, &entry.reader, &entry.resolved.command); - if resolved != entry.resolved { - entry.resolved = resolved; + let (resolved, _) = resolve_as(ctx, reader, &kept.command); + if resolved != *kept { + *kept = resolved; changed.push(*key); } } } - shown.retain(|_, readers| !readers.is_empty()); + table.retain(|_, readers| !readers.is_empty()); with(ctx, |board| { // Reads the gate made while the entries were out of the board. - let added = std::mem::replace(&mut board.shown, shown); - for ((key, of), readers) in added { - for entry in readers { - keep_shown(&mut board.shown, key, of, entry.reader, &entry.resolved); + let added = board.shown.remove(&viewport).unwrap_or_default(); + for (key, readers) in added { + for (reader, resolved) in readers { + keep_in(table.entry(key).or_default(), reader, &resolved); } } + if !table.is_empty() { + board.shown.insert(viewport, table); + } }); for (number, instance) in changed { lazy::note_edit(ctx, BindKey::Command(number, instance)); @@ -1197,8 +1257,8 @@ pub(crate) fn begin(ctx: &Context) { board.chains.get(&viewport).filter(|(id, _)| Some(*id) == focused).map(|(_, chain)| chain.ids().collect()).unwrap_or_default() }); // Nothing focused inside a modal: the modal's root takes the commands, as a plain Enter goes to its default button. - let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.iter().find(|(of, _)| *of == viewport)) { - (true, Some((_, root))) => vec![*root], + let chain = match (chain.is_empty() && focused.is_none(), board.modal_roots.get(&viewport)) { + (true, Some(root)) => vec![*root], _ => chain, }; if !chain.is_empty() { @@ -1218,7 +1278,7 @@ pub(crate) fn begin(ctx: &Context) { } let mut keys = board.key_scopes(&chain)?; // The held-open canvas's scope is around the focus for matching: its commands fire from the dialog. - let held_scope = held_open.and_then(|id| board.instances.iter().find(|i| i.id == id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope)); + let held_scope = held_open.and_then(|id| board.instances.get(id)).map(|i| i.scope.name()).filter(|scope| !is_app(scope)); if let Some(scope) = held_scope && !keys.scopes.contains(&scope) { @@ -1295,7 +1355,7 @@ pub(crate) fn begin(ctx: &Context) { .iter() .filter(|fired| fired.phase == FirePhase::Press) .filter_map(|fired| fired.target) - .filter_map(|target| board.instances.iter().find(|instance| instance.id == target)?.layer) + .filter_map(|target| board.instances.get(target)?.layer) .collect() }); overlay::close_popups_outside(ctx, &inside); @@ -1313,18 +1373,22 @@ pub(crate) fn end(ctx: &Context) { let alive: Vec = board.instances.iter().map(|i| board.live(ctx, i) && live.contains(&i.viewport)).collect(); let mut keep = alive.iter(); board.instances.retain(|_| keep.next().copied().unwrap_or(false)); - let ids: Vec = board.instances.iter().map(|i| i.id).collect(); - board.queue.retain(|fired| fired.target.is_some_and(|id| ids.contains(&id))); - board.held.retain(|held| held.target.is_none_or(|id| ids.contains(&id))); + let instances = &board.instances; + let ids = |id: Id| instances.contains(id); + board.queue.retain(|fired| fired.target.is_some_and(ids)); + board.held.retain(|held| held.target.is_none_or(ids)); board.chains.retain(|viewport, _| live.contains(viewport)); board.before.retain(|viewport, _| live.contains(viewport)); board.here.focused.retain(|(viewport, _)| live.contains(viewport)); - board.shown.retain(|(_, viewport), readers| { - readers.retain(|entry| match &entry.reader { - Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(|id| ids.contains(&id)), - _ => true, + board.shown.retain(|viewport, table| { + table.retain(|_, readers| { + readers.retain(|(reader, _)| match reader { + Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(&ids), + _ => true, + }); + !readers.is_empty() }); - live.contains(viewport) && !readers.is_empty() + live.contains(viewport) && !table.is_empty() }); }); } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 1570c4ae1..a4cf272e8 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -19,16 +19,16 @@ pub use registry::{SetEntry, sets}; pub use board::declare_child; #[doc(hidden)] pub use board::focus_within; -#[cfg(feature = "testing")] -#[doc(hidden)] -pub use board::keymap_builds; pub(crate) use board::publish as publish_for; pub(crate) use board::take as take_for_instance; pub(crate) use board::{ - begin, binds_scoped, edit_chords, end, install, note_focus, platform, register_instance, set_input, take_delivered, take_fired, window_shortcuts, + begin, binds_scoped, edit_chords, end, install, note_focus, register_instance, set_input, take_delivered, take_fired, window_shortcuts, }; #[doc(hidden)] pub use board::{bound_around, take_around}; +#[cfg(feature = "testing")] +#[doc(hidden)] +pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; use craft_behavior::CommandFlags; @@ -261,6 +261,8 @@ pub struct ResolvedCommand { pub icon: Option>, /// The chord surfaces show: the first single-press binding that runs the command ([`chord`]). pub chord: Option, + /// `chord` as the platform writes it, from the table the keymap builds with its bindings. + pub chord_text: Option>, /// The state ANDed with the gate, the modal rule and the instance's liveness. pub enabled: bool, /// The checked state of a toggle or radio command. @@ -341,7 +343,7 @@ impl CommandInput { /// The chain of container instances that receive scoped commands, innermost last. A private inherited field of /// the env. #[doc(hidden)] -#[derive(Clone, Default, PartialEq, Eq)] +#[derive(Clone, Default, PartialEq, Eq, Hash)] pub struct CommandChain(Arc<[(CommandScope, Id)]>); impl CommandChain { diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 912f37b57..71e2cf685 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -285,6 +285,18 @@ pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) } +/// Counts a chord text an access report read for a node in this pass. +#[cfg(feature = "testing")] +pub(crate) fn count_chord_text(ctx: &Context) { + totals(ctx, |log| log.chord_texts += 1); +} + +/// The chord texts the access reports of the last pass read: one per command-bound node that exists. +#[cfg(feature = "testing")] +pub fn chord_texts(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.chord_texts, 0) +} + /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { @@ -347,13 +359,14 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { pass_state::with::(ctx, |log| if log.pass == last { log.decisions.clone() } else { Vec::new() }) } -/// Bytes fed into memo keys in one pass, and the layouts and measure asks of that pass. +/// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass. #[cfg(feature = "testing")] #[derive(Default)] pub(crate) struct PassTotals { pass: u64, key_bytes: usize, text_layouts: u32, + chord_texts: u32, asks: Vec<(&'static str, u32)>, } diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index 24d76a66d..dda5a9c5f 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -219,11 +219,10 @@ impl Component for FlyoutButton<'_, T> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let laid = self.resolve(cx); - let os = cx.env.shell().os; let face = cx.part(FACE, rect).priority(HitPriority::new(HitLevel::Body, 0)); if let Some(resolved) = self.lead(&laid) { - face.tooltip(match &resolved.chord { - Some(chord) => Label::from(format!("{} ({})", resolved.label, chord.display(os))), + face.tooltip(match &resolved.chord_text { + Some(chord) => Label::from(format!("{} ({chord})", resolved.label)), None => Label::Shared(resolved.label.clone()), }); } diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index 63dfc001e..d4bb19304 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -1,10 +1,11 @@ -use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Tap}; +use super::kit::{AppCommand, Dock, DockCommand, PaneCommand, Silent, Tap}; use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; use craft_ui::runtime::commands::{ - CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, fire, resolve, + CommandGate, CommandInput, CommandRef, CommandState, Commands as _, EditCommands, FireSource, Fired, chord_text_builds, fire, resolve, }; use craft_ui::runtime::focus::{FocusTarget, request}; use craft_ui::runtime::frame::take_output; +use craft_ui::runtime::measure::chord_texts; use craft_ui::testing::input::key_press; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Frames, trial}; @@ -193,3 +194,59 @@ fn undo_in_a_dialog_reaches_the_dialog_and_not_the_application() { assert_eq!(undone.get(), 1, "the dialog took the undo"); assert!(take_output(&frames.ctx).fired.is_empty(), "the application's undo stays blocked"); } + +/// Count relation: an access report reads a chord text for each command-bound node that exists, at any number of nodes, +/// never for a component with no node, and writes none; the texts are written when the keymap is built. +#[trial] +fn access_reports_read_chord_texts_for_their_nodes_and_write_none() { + let mut frames = Frames::new(); + let mut built = 0; + for count in [6, 12] { + let mut show = |ui: &mut Ui| { + for salt in 0..count { + Tap::new().id_salt(salt).command(AppCommand::Save).show(ui); + } + Tap::new().id_salt("go").command(AppCommand::Go).show(ui); + Silent::new().id_salt("silent").command(AppCommand::Save).show(ui); + }; + frames.idle(3, &mut show); + if built == 0 { + built = chord_text_builds(); + } + frames.idle(3, &mut show); + assert_eq!(chord_text_builds(), built, "passes write no chord text"); + assert_eq!(chord_texts(&frames.ctx), count, "one read per node whose command has a chord, none for a component with no node"); + } +} + +/// An instance that stops registering and registers again goes last in registration order, which a non-component +/// source's pick follows (the first live instance); lookups by id stay right throughout. +#[trial] +fn a_re_registered_instance_goes_last_in_the_pick() { + let a_shown = Cell::new(true); + let taker = Cell::new(""); + let mut show = |ui: &mut Ui| { + for name in ["a", "b", "c"] { + if name == "a" && !a_shown.get() { + continue; + } + super::kit::Pane::new().id_salt(name).show(ui, |_, cx| { + if cx.take_command::().is_some() { + taker.set(name); + } + }); + } + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette)); + frames.idle(2, &mut show); + assert_eq!(taker.get(), "a", "registered first"); + a_shown.set(false); + frames.idle(3, &mut show); + a_shown.set(true); + frames.idle(3, &mut show); + assert!(fire(&frames.ctx, PaneCommand::ZoomIn, FireSource::Palette)); + frames.idle(2, &mut show); + assert_eq!(taker.get(), "b", "a registered again after b and c"); +} diff --git a/crates/ui-shell/tests/it/commands/kit.rs b/crates/ui-shell/tests/it/commands/kit.rs index 0530f8cd4..551c77024 100644 --- a/crates/ui-shell/tests/it/commands/kit.rs +++ b/crates/ui-shell/tests/it/commands/kit.rs @@ -89,6 +89,37 @@ impl Component for Tap<'_> { } } +/// A `Tap` whose role gives it no access node. +#[derive(Component)] +pub struct Silent { + #[common] + common: Common, +} + +impl Silent { + pub fn new() -> Self { + Silent { common: Common::new() } + } +} + +impl Component for Silent { + const ROLE: Role = Role::None; + type Style = FixedStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: SilentStyleKey) -> FixedStyle { + FixedStyle::default() + } + + fn measure(&mut self, _: &craft_ui::contract::MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(40.0, 20.0) + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + /// A container that is an instance of the `trial.pane` scope. #[derive(Component)] #[component(container)]