From 2dc15b3ec21d2ae4595d0b8d0f642a1e7a4cfe87 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:39:51 +0000 Subject: [PATCH 001/110] 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 be39bb38573e967e11cba4db119f88e0173596d5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 06:41:32 +0000 Subject: [PATCH 002/110] 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 1e7aff56386a27cb59507accbbc26f7b73b49246 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:25:25 +0000 Subject: [PATCH 003/110] 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 f9c149b497fd66b091bfdf99f7c986ac86ee12a3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 07:37:16 +0000 Subject: [PATCH 004/110] craft-ui: journal entries are data, comparable by call and arguments `runtime::journal(ctx, args, again)` notes a registration as its arguments and a capture-free `again` (a function or a closure without captures; a capture fails to compile). Two entries are equal when they come from the same `again` with equal arguments, and `Debug` names the call and its arguments, so a replay can be compared with a real run. The focus `Transcript` and the records it holds (`StopRec`, `ScopeRec`, `RowGroups`, `Stop`, `Group`, `KeyUse`, `KeyRole`) derive `PartialEq`. The journal's argument types gain `PartialEq` or `Debug` where they lacked them; `UiTokens` compares by its content key. The docking generics that journal drop spots require `PartialEq + Debug` of the panel type. --- crates/behavior/src/keys.rs | 2 +- crates/ui-contract/src/contract/lazy.rs | 2 +- crates/ui-contract/src/primitives/sensing.rs | 26 +++---- .../ui-contract/src/runtime/commands/board.rs | 11 +-- .../ui-contract/src/runtime/commands/mod.rs | 2 +- crates/ui-contract/src/runtime/drag.rs | 9 ++- crates/ui-contract/src/runtime/egui/access.rs | 6 +- crates/ui-contract/src/runtime/focus.rs | 10 +-- .../ui-contract/src/runtime/focus/policy.rs | 2 +- .../src/runtime/focus/registration.rs | 4 +- crates/ui-contract/src/runtime/keys/nodes.rs | 10 ++- .../ui-contract/src/runtime/layout_memory.rs | 14 ++-- crates/ui-contract/src/runtime/memory.rs | 2 +- crates/ui-contract/src/runtime/pointer.rs | 22 +++--- crates/ui-contract/src/runtime/reads.rs | 7 +- crates/ui-contract/src/runtime/replay.rs | 77 ++++++++++++++++--- crates/ui-contract/src/runtime/wheel.rs | 2 +- crates/ui-contract/src/runtime/windows/hit.rs | 2 +- crates/ui-contract/src/style/tokens.rs | 9 +++ crates/ui-panels/src/docking/dock_column.rs | 18 +++-- crates/ui-panels/src/docking/frame.rs | 3 +- crates/ui-panels/src/docking/group.rs | 9 ++- crates/ui-panels/src/docking/iconic.rs | 9 ++- crates/ui-panels/src/docking/targets.rs | 38 +++++---- crates/ui-patterns/src/patterns/dock/area.rs | 7 +- 25 files changed, 202 insertions(+), 101 deletions(-) diff --git a/crates/behavior/src/keys.rs b/crates/behavior/src/keys.rs index 5c8bf19da..a24e52bf5 100644 --- a/crates/behavior/src/keys.rs +++ b/crates/behavior/src/keys.rs @@ -8,7 +8,7 @@ use craft_host::target::Os; use craft_keymap::{Chord, Key, Mods}; /// What the focused stop is, as far as the table's rows differ. -#[derive(Clone, Copy, Debug, Default)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct KeyRole { /// A value control with a reset value and no text part: Delete resets it. diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index c65a6cf75..1e9045c55 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -137,7 +137,7 @@ impl Lazy { let real = !sizing && !crate::runtime::measure::active(&ctx); let owner = view.map(|view| view.owner); // A run around this one that is replayed later keeps the child's entry. - replay::journal(&ctx, || move |ctx: &egui::Context| lazy::keep(ctx, owner, id)); + replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); if let Some(view) = view { let at = |size: Vec2| { let x = if rtl { available.max.x - size.x } else { available.min.x }; diff --git a/crates/ui-contract/src/primitives/sensing.rs b/crates/ui-contract/src/primitives/sensing.rs index 8a6fe8269..7397d0fe5 100644 --- a/crates/ui-contract/src/primitives/sensing.rs +++ b/crates/ui-contract/src/primitives/sensing.rs @@ -113,7 +113,7 @@ impl TextOutcome { /// A part as the sensing core registers it. // F2-MERGE: F3 (`PartBuilder` adds tooltip and `pointer_only`) -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct PartDecl { pub key: PartKey, pub index: Option, @@ -153,7 +153,7 @@ impl PartDecl { } /// One member's registration for this pass. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] pub(crate) struct MemberDecl { pub id: Id, pub rect: Rect, @@ -174,7 +174,7 @@ impl MemberDecl { } /// What a root registers at step 8: its id and rect. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq)] struct RootInfo { id: Id, rect: Rect, @@ -396,7 +396,7 @@ pub fn cancel_press_of(ctx: &Context, owner: Id) { /// Records the transformed body's egui layer. pub(crate) fn set_layer(ctx: &Context, arena: ArenaId, layer: Layer) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| set_layer(ctx, arena, layer)); + crate::runtime::replay::journal(ctx, || (arena, layer), |ctx, &(arena, layer)| set_layer(ctx, arena, layer)); let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); with_arena(ctx, arena, pass_nr, |state| state.layer = Some(layer)); } @@ -408,7 +408,7 @@ pub(crate) fn set_layer(ctx: &Context, arena: ArenaId, layer: Layer) { // names their shapes as the press winner. /// What a root registers in its arena at step 8, kept for a replay. -#[derive(Clone)] +#[derive(Clone, Debug, PartialEq)] struct RootRegistration { info: RootInfo, own: Vec, @@ -419,10 +419,11 @@ struct RootRegistration { /// Notes a root's step-8 registration in the open records. fn journal_root(ctx: &Context, arena: ArenaId, info: RootInfo, own: &[PartDecl], widgets: &[Id], (layer, sense): (Layer, Sense)) { - crate::runtime::replay::journal(ctx, || { - let registration = RootRegistration { info, own: own.to_vec(), widgets: widgets.to_vec(), layer, sense }; - move |ctx: &Context| register_root_again(ctx, arena, registration.clone()) - }); + crate::runtime::replay::journal( + ctx, + || (arena, RootRegistration { info, own: own.to_vec(), widgets: widgets.to_vec(), layer, sense }), + |ctx, (arena, registration)| register_root_again(ctx, *arena, registration.clone()), + ); } /// A replayed root's step-8 registration: its own parts, rect, widgets, layer and sense, with no press run. @@ -441,10 +442,7 @@ fn register_root_again(ctx: &Context, arena: ArenaId, registration: RootRegistra /// Notes in the open records the members that joined `arena`, as they joined. fn journal_join(ctx: &Context, arena: ArenaId, joined: &[MemberDecl]) { - crate::runtime::replay::journal(ctx, || { - let joined = joined.to_vec(); - move |ctx: &Context| join_again(ctx, arena, joined.clone()) - }); + crate::runtime::replay::journal(ctx, || (arena, joined.to_vec()), |ctx, (arena, joined)| join_again(ctx, *arena, joined.clone())); } /// Replayed members join their arena again. @@ -463,7 +461,7 @@ fn join_again(ctx: &Context, arena: ArenaId, joined: Vec) { /// Places the `over` parts of the root of `arena` (`member` None) or of its member `member` above the members joined /// so far, as `place_over_widgets` does; journaled for a replay. fn place_over(ctx: &Context, arena: ArenaId, member: Option) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| place_over(ctx, arena, member)); + crate::runtime::replay::journal(ctx, || (arena, member), |ctx, &(arena, member)| place_over(ctx, arena, member)); let pass_nr = pass::pass_nr(ctx, pass::current_viewport(ctx)); with_arena(ctx, arena, pass_nr, |state| { rotate(state, pass_nr); diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 0c3d7f8a7..05853c05a 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -696,7 +696,7 @@ pub(crate) fn register_instance(ctx: &Context, scope: CommandScope, id: Id) { /// `register_instance` in the layer `layer`, which a replay of the registration keeps. 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)); + crate::runtime::replay::journal(ctx, || (scope, id, layer), |ctx, &(scope, id, layer)| 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) { @@ -1019,10 +1019,11 @@ pub(crate) fn publish(ctx: &Context, chain: &CommandChain, command: &CommandRef, if !measure::effect(ctx, "commands::publish") { return; } - replay::journal(ctx, || { - let (chain, command, state) = (chain.clone(), command.clone(), state.clone()); - move |ctx: &Context| publish(ctx, &chain, &command, state.clone()) - }); + replay::journal( + ctx, + || (chain.clone(), command.clone(), state.clone()), + |ctx, (chain, command, state)| publish(ctx, chain, command, state.clone()), + ); let changed = with(ctx, |board| { let scope = board.scope_of(command); let declared = board.def(&command.id).is_some_and(|def| def.modal == ModalRule::Declared); diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 1570c4ae1..40c43af07 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -341,7 +341,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, Debug, Default, PartialEq, Eq)] pub struct CommandChain(Arc<[(CommandScope, Id)]>); impl CommandChain { diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index 3e161c614..fdfea4948 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -505,10 +505,11 @@ pub(crate) fn show_mark(ctx: &Context, mark: Option) { /// Records that `owner`'s `ordinal`th target on `layer` accepts at the pointer, with its mark in layer space and the /// tokens of the target's region. A `window` target covers the whole window. pub(crate) fn register(ctx: &Context, owner: Id, layer: Layer, mark: DropMark, tokens: Arc, window: bool) { - crate::runtime::replay::journal(ctx, || { - let tokens = tokens.clone(); - move |ctx: &Context| register(ctx, owner, layer, mark, tokens.clone(), window) - }); + crate::runtime::replay::journal( + ctx, + || (owner, layer, mark, tokens.clone(), window), + |ctx, (owner, layer, mark, tokens, window)| register(ctx, *owner, *layer, *mark, tokens.clone(), *window), + ); let mark = match areas::layer_map(ctx, layer) { Some(map) => mark.mapped(|point| map.to_screen(point)), None => mark, diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 8eee24e44..030a76695 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -139,7 +139,7 @@ pub(crate) fn register_parent(ctx: &Context, id: Id, parent: Id) { /// Notes that the runtime emitted the node of `id`. fn emit(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| emitted.emit(id)); - crate::runtime::replay::journal(ctx, || move |ctx: &Context| emit(ctx, id)); + crate::runtime::replay::journal(ctx, || id, |ctx, &id| emit(ctx, id)); } /// Notes that the node of the text widget `widget` folds into the node of `owner`. @@ -147,7 +147,7 @@ fn note_folded(ctx: &Context, widget: Id, owner: Id) { with_emitted(ctx, |emitted| { emitted.folded.insert(widget, owner); }); - crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_folded(ctx, widget, owner)); + crate::runtime::replay::journal(ctx, || (widget, owner), |ctx, &(widget, owner)| note_folded(ctx, widget, owner)); } /// Notes that the runtime wrote the node of `id`. @@ -155,7 +155,7 @@ pub(crate) fn note_written(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| { emitted.written.insert(id); }); - crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_written(ctx, id)); + crate::runtime::replay::journal(ctx, || id, |ctx, &id| note_written(ctx, id)); } /// The pass-end step: the children of each node the runtime wrote follow the order the runtime emitted them in, diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index e4615e280..803cd2572 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -42,7 +42,7 @@ pub enum FocusShape { pub(crate) type StopKey = (Id, Option); /// A registered stop with its place in the scope tree. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] #[doc(hidden)] pub struct StopRec { #[doc(hidden)] @@ -50,7 +50,7 @@ pub struct StopRec { pub(crate) scope: Option, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct ScopeRec { pub(crate) policy: FocusPolicy, pub(crate) parent: Option, @@ -116,7 +116,7 @@ pub(crate) struct BeginIn { /// The row groups of one collection's visible rows in a pass: every one is a flat roving group of the same owner /// and direction, so the collection registers them as one record. -#[derive(Clone)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(crate) struct RowGroups { owner: Id, rtl: bool, @@ -261,7 +261,7 @@ pub(crate) struct Mark { /// What one run of a child registered with the focus service: its stops, the scopes it pushed, the roving groups /// its stops belong to and its collections' row groups. A child out of view registers it again without running /// (`runtime::lazy`), so its stops keep their place in Tab and F6 order. -#[derive(Clone, Default)] +#[derive(Clone, Debug, Default, PartialEq, Eq)] pub(crate) struct Transcript { stops: Vec, scopes: Vec<(Id, ScopeRec)>, @@ -431,7 +431,7 @@ pub(crate) fn pop_scope(ctx: &Context) { /// Registers that the menu bar `bar` takes the menu-bar keys of the next input hook (spec 9.7). A settled bar /// registers again when it replays its last run, and the keys it takes run it (`keys::routed_to`). pub(crate) fn register_menu_bar(ctx: &Context, bar: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_menu_bar(ctx, bar)); + crate::runtime::replay::journal(ctx, || bar, |ctx, &bar| register_menu_bar(ctx, bar)); with(ctx, |state| state.menu_bar = Some(bar)); } diff --git a/crates/ui-contract/src/runtime/focus/policy.rs b/crates/ui-contract/src/runtime/focus/policy.rs index 93e8500b0..db028b674 100644 --- a/crates/ui-contract/src/runtime/focus/policy.rs +++ b/crates/ui-contract/src/runtime/focus/policy.rs @@ -250,7 +250,7 @@ pub enum EndKey { } /// A component's declared keys. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct KeyUse { /// The keys kept from the key stage. diff --git a/crates/ui-contract/src/runtime/focus/registration.rs b/crates/ui-contract/src/runtime/focus/registration.rs index 5c525d8f7..f2d9fb531 100644 --- a/crates/ui-contract/src/runtime/focus/registration.rs +++ b/crates/ui-contract/src/runtime/focus/registration.rs @@ -8,7 +8,7 @@ use craft_behavior::{KeyRole, PartRef}; use egui::{Context, Id}; /// A stop as registered at step 7 of the pipeline. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Stop { /// The component. @@ -124,7 +124,7 @@ impl Stop { } /// A roving group's registration: one Tab stop whose members take moves. -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Group { /// The group. diff --git a/crates/ui-contract/src/runtime/keys/nodes.rs b/crates/ui-contract/src/runtime/keys/nodes.rs index f6e13fbac..2266a989b 100644 --- a/crates/ui-contract/src/runtime/keys/nodes.rs +++ b/crates/ui-contract/src/runtime/keys/nodes.rs @@ -10,7 +10,7 @@ use egui::{Context, Id}; pub(crate) fn redirect_node(ctx: &Context, node: Id, owner: Id, part: PartRef) { // Journaled after the `register_node` it amends, so a settled region's replay leaves the row's node with the // collection, as a run does. - crate::runtime::replay::journal(ctx, || move |ctx: &Context| redirect_node(ctx, node, owner, part)); + crate::runtime::replay::journal(ctx, || (node, owner, part), |ctx, &(node, owner, part)| redirect_node(ctx, node, owner, part)); current(ctx, |stage| { if let Some(entry) = stage.nodes.get_mut(&node_key(node)) { entry.owner = owner; @@ -22,7 +22,7 @@ pub(crate) fn redirect_node(ctx: &Context, node: Id, owner: Id, part: PartRef) { /// Records the expanded state of the node registered by `register_node`: an `Expand` or `Collapse` request on a node /// with the state asks to change it, and acts as the node's activation. pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_expanded(ctx, node, expanded)); + crate::runtime::replay::journal(ctx, || (node, expanded), |ctx, &(node, expanded)| register_expanded(ctx, node, expanded)); current(ctx, |stage| { if let Some(entry) = stage.nodes.get_mut(&node_key(node)) { entry.expanded = expanded; @@ -32,7 +32,11 @@ pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option) /// Registers an AccessKit node so a request that targets it reaches `owner`. pub(crate) fn register_node(ctx: &Context, node: Id, owner: Id, part: Option, focusable: bool) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_node(ctx, node, owner, part, focusable)); + crate::runtime::replay::journal( + ctx, + || (node, owner, part, focusable), + |ctx, &(node, owner, part, focusable)| register_node(ctx, node, owner, part, focusable), + ); current(ctx, |stage| { stage.nodes.insert(node_key(node), Node { owner, part, focusable, expanded: None }); }); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index e2c4c79a3..a1b6b9832 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1117,19 +1117,21 @@ pub(crate) fn ask_discard(ctx: &Context) { /// Notes in the run records open around the running code that a replay keeps the entry and the kept transcript of /// `id`: the replayed run does not reach them, and an entry no pass touched in a frame is dropped. fn journal_keep(ctx: &Context, id: Id) { - crate::runtime::replay::journal(ctx, || { - move |ctx: &Context| { + crate::runtime::replay::journal( + ctx, + || id, + |ctx, id| { let moment = Moment::of(ctx); with(ctx, &moment, |memory| { - if let Some(entry) = memory.entries.get_mut(&id) { + if let Some(entry) = memory.entries.get_mut(id) { entry.touched = moment.frame; } - if let Some(kept) = memory.kept.get_mut(&id) { + if let Some(kept) = memory.kept.get_mut(id) { kept.touched = moment.frame; } }); - } - }); + }, + ); } /// The end hook: asks egui for at most one discard pass per frame, and for a repaint when a change cannot get one, so diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 4ebedc657..4088ec89c 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -230,7 +230,7 @@ struct Seen(u64); /// Registers `owner`'s pass, at step 3: eviction tests only owners. Shown entries of an owner not registered /// for 3 passes of the viewport that last showed it and 0.5 s are evicted by `evict`. pub(crate) fn register_owner(ctx: &Context, owner: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_owner(ctx, owner)); + crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| register_owner(ctx, owner)); let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now }); diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index beeb9b20f..b2511074e 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -369,10 +369,11 @@ pub(crate) fn record_shapes(ctx: &Context, layer: Layer, root: Id, clip: Rect, s /// `record_shapes` for a caller that already read the running viewport. pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, clip: Rect, shapes: impl IntoIterator>) { let shapes: Vec> = shapes.into_iter().collect(); - crate::runtime::replay::journal(ctx, || { - let shapes = shapes.clone(); - move |ctx: &Context| record_shapes(ctx, layer, root, clip, shapes.iter().cloned()) - }); + crate::runtime::replay::journal( + ctx, + || (layer, root, clip, shapes.clone()), + |ctx, (layer, root, clip, shapes)| record_shapes(ctx, *layer, *root, *clip, shapes.iter().cloned()), + ); PerViewport::::with(ctx, viewport, |record| { let order = record.next; record.next += 1; @@ -385,7 +386,7 @@ pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer /// Records the egui widget `widget` that the component `owner` made for its own text (a field's text, a selection /// part): a press egui gives it is the widget's own and goes to no root, and the hover goes to `owner`. pub(crate) fn record_text_widget(ctx: &Context, widget: Id, owner: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| record_text_widget(ctx, widget, owner)); + crate::runtime::replay::journal(ctx, || (widget, owner), |ctx, &(widget, owner)| record_text_widget(ctx, widget, owner)); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { record.this_texts.insert(widget, owner); }); @@ -403,7 +404,7 @@ pub(crate) fn record_layer_widget(ctx: &Context, widget: Id) { /// Records that `layer` shows the transformed body of the root `root`, which is itself shown on `parent`: a press on /// the body layer reaches the root's own shapes beneath the body's. pub(crate) fn record_body_layer(ctx: &Context, layer: Layer, parent: Layer, root: Id) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| record_body_layer(ctx, layer, parent, root)); + crate::runtime::replay::journal(ctx, || (layer, parent, root), |ctx, &(layer, parent, root)| record_body_layer(ctx, layer, parent, root)); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { record.this_bodies.insert(layer, (root, parent)); }); @@ -417,10 +418,11 @@ pub(crate) fn record_widgets(ctx: &Context, layer: Layer, root: Id, widgets: &[I /// `record_widgets` for a caller that already read the running viewport. pub(crate) fn record_widgets_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, widgets: &[Id], click: bool) { - crate::runtime::replay::journal(ctx, || { - let widgets = widgets.to_vec(); - move |ctx: &Context| record_widgets(ctx, layer, root, &widgets, click) - }); + crate::runtime::replay::journal( + ctx, + || (layer, root, widgets.to_vec(), click), + |ctx, (layer, root, widgets, click)| record_widgets(ctx, *layer, *root, widgets, *click), + ); PerViewport::::with(ctx, viewport, |record| { let entry = record.this.entry(layer).or_default().entry(root).or_default(); entry.widgets.extend_from_slice(widgets); diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index ce184f479..4b3cf72e1 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -35,7 +35,7 @@ pub(crate) struct Sample { pub took: Vec2, } -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] struct Read { key: BindKey, reader: Id, @@ -94,10 +94,7 @@ pub(crate) fn note(ctx: &Context, key: BindKey, reader: Id, measuring: bool, sam } else { let read = Read { key, reader, measuring, runs, samples }; crate::runtime::replay::note_read(ctx, key); - crate::runtime::replay::journal(ctx, || { - let read = read.clone(); - move |ctx: &Context| with(ctx, |reads| reads.reads.push(read.clone())) - }); + crate::runtime::replay::journal(ctx, || read.clone(), |ctx, read| with(ctx, |reads| reads.reads.push(read.clone()))); with(ctx, |reads| reads.reads.push(read)); } } diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index f4a317b18..0c248849e 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -16,12 +16,63 @@ use crate::runtime::frame; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; use egui::{Context, IdSet}; +use std::any::Any; use std::collections::HashSet; +use std::fmt; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; -/// A registration of the recorded run, made again by calling it. -type Entry = Arc; +/// A registration of the recorded run: the call that makes it again and what it is called with. Two entries are equal +/// when they come from the same call (the same `again` of [`journal`]) with equal arguments. +#[derive(Clone)] +pub(crate) struct Entry(Arc); + +trait Noted: Send + Sync { + fn call(&self, ctx: &Context); + fn as_any(&self) -> &dyn Any; + fn same(&self, other: &dyn Noted) -> bool; + fn describe(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result; +} + +struct Note { + args: A, + again: F, +} + +impl Noted for Note +where + A: PartialEq + fmt::Debug + Send + Sync + 'static, + F: Fn(&Context, &A) + Send + Sync + 'static, +{ + fn call(&self, ctx: &Context) { + (self.again)(ctx, &self.args); + } + + fn as_any(&self) -> &dyn Any { + self + } + + fn same(&self, other: &dyn Noted) -> bool { + // `F` is capture-free, so its type names the call: the same type is the same call. + other.as_any().downcast_ref::().is_some_and(|other| other.args == self.args) + } + + fn describe(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}({:?})", std::any::type_name::(), self.args) + } +} + +impl PartialEq for Entry { + fn eq(&self, other: &Self) -> bool { + self.0.same(&*other.0) + } +} + +impl fmt::Debug for Entry { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.describe(f) + } +} /// Records open across all contexts, so a registration made while none is open takes no lock. static OPEN: AtomicUsize = AtomicUsize::new(0); @@ -68,7 +119,7 @@ pub(crate) struct Facts { /// What one real run of a region added to its pass. pub(crate) struct Record { pub(crate) focus: Transcript, - journal: Vec, + pub(crate) journal: Vec, egui: egui::PassRecords, /// The egui widgets of the run. pub(crate) widgets: IdSet, @@ -136,7 +187,7 @@ pub(crate) fn replay(ctx: &Context, record: &Record) { ctx.replay_pass_records(&record.egui); focus::replay(ctx, &record.focus); for entry in &record.journal { - entry(ctx); + entry.0.call(ctx); } if let Some(at) = record.facts.wake { crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx)); @@ -160,12 +211,20 @@ fn with_open(ctx: &Context, f: impl FnOnce(&mut Facts)) { } } -/// Notes, in the records open around the running code, the registration `make` builds: called again, it registers -/// what the running code registered. A service outside this crate that keeps registrations per pass (a dock's drop -/// spots) notes each one here, so a settled region's replay makes it again. -pub fn journal(ctx: &Context, make: impl FnOnce() -> F) { +/// Notes, in the records open around the running code, the registration the running code made: `again(ctx, &args)` +/// registers it again. `args` builds the arguments only while a record is open. `again` captures nothing (a function +/// or a closure without captures; a capture does not compile), so everything the registration depends on is in the +/// arguments, and two notes of the same `again` with equal arguments are the same registration. A service outside +/// this crate that keeps registrations per pass (a dock's drop spots) notes each one here, so a settled region's replay +/// makes it again. +pub fn journal(ctx: &Context, args: impl FnOnce() -> A, again: F) +where + A: PartialEq + fmt::Debug + Send + Sync + 'static, + F: Fn(&Context, &A) + Send + Sync + 'static, +{ + const { assert!(std::mem::size_of::() == 0, "`journal`'s `again` captures nothing: pass its state in `args`") }; if recording(ctx) { - let entry: Entry = Arc::new(make()); + let entry = Entry(Arc::new(Note { args: args(), again })); pass_state::with::(ctx, |recorder| recorder.journal.push(entry)); } } diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index f9763b1aa..6ad4df5e2 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -25,7 +25,7 @@ pub(crate) struct State { /// Registers a taker for next pass's split. pub(crate) fn register(ctx: &Context, taker: WheelTaker) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| register(ctx, taker)); + crate::runtime::replay::journal(ctx, || taker, |ctx, &taker| register(ctx, taker)); PerViewport::::with(ctx, pass::current_viewport(ctx), |state| state.this.push(taker)); } diff --git a/crates/ui-contract/src/runtime/windows/hit.rs b/crates/ui-contract/src/runtime/windows/hit.rs index c4dadbb42..c09d143a5 100644 --- a/crates/ui-contract/src/runtime/windows/hit.rs +++ b/crates/ui-contract/src/runtime/windows/hit.rs @@ -311,7 +311,7 @@ pub(super) fn with_exclusive(ctx: &Context, viewport: ViewportId, f: impl FnO /// A part declared again in the same pass replaces its entry. A settled region that replays its last run declares /// its parts again, so a settled title bar keeps its caption regions. pub(crate) fn note_exclusive(ctx: &Context, owner: Id, part: PartRef, hit: WindowHit, rect: Rect) { - crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_exclusive(ctx, owner, part, hit, rect)); + crate::runtime::replay::journal(ctx, || (owner, part, hit, rect), |ctx, &(owner, part, hit, rect)| note_exclusive(ctx, owner, part, hit, rect)); with_exclusive(ctx, pass::current_viewport(ctx), |exclusive| { let entry = ExclusivePart { owner, part, hit, rect }; match exclusive.current.iter_mut().find(|held| held.owner == owner && held.part == part) { diff --git a/crates/ui-contract/src/style/tokens.rs b/crates/ui-contract/src/style/tokens.rs index 504731b04..2f0cc8428 100644 --- a/crates/ui-contract/src/style/tokens.rs +++ b/crates/ui-contract/src/style/tokens.rs @@ -42,6 +42,15 @@ pub struct UiTokens { key: u64, } +/// Two sets are equal when their content keys are: equal sets share a key. +impl PartialEq for UiTokens { + fn eq(&self, other: &Self) -> bool { + self.key == other.key + } +} + +impl Eq for UiTokens {} + impl UiTokens { /// A token set resolved under `contrast` and `density`, with no theme values for token groups, drawing the default /// icon set. diff --git a/crates/ui-panels/src/docking/dock_column.rs b/crates/ui-panels/src/docking/dock_column.rs index 190d78a49..36c90de32 100644 --- a/crates/ui-panels/src/docking/dock_column.rs +++ b/crates/ui-panels/src/docking/dock_column.rs @@ -20,6 +20,7 @@ use craft_behavior::divider::{self as push, Segment}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_behavior::{Axis, DockSide, Flow, Metrics, PartKey, Sense, Value}; use egui::{Context, Id, Pos2, Rect, Response, Ui}; +use std::fmt::Debug; use std::hash::Hash; #[cfg(feature = "testing")] @@ -207,7 +208,7 @@ pub struct DockColumn<'a, P: Value + Hash + 'static> { collapse: bool, } -impl<'a, P: Value + Hash + 'static> DockColumn<'a, P> { +impl<'a, P: Value + Hash + Debug + 'static> DockColumn<'a, P> { /// A column named `label` of the dock `dock`, over `column`; `spec` reads each panel's limits and heights. pub fn new(label: impl Into