diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index d04b9804ba..95b173950a 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -1548,6 +1548,8 @@ pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &Comma /// `command` as `reader` is shown it, noted as its read: the kept resolution while its inputs are unchanged, else a new /// one, kept. fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> Arc { + #[cfg(feature = "testing")] + measure::count_command_read(ctx); // The resolved command carries the chord the keymap shows, kept or made now. crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); let viewport = pass::current_viewport(ctx); diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index ff9a453e7c..6c5b643088 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -420,6 +420,18 @@ pub fn last_pass_resolves(ctx: &Context, what: Resolve) -> u32 { last_totals(ctx, |log| log.resolves[what as usize], 0) } +/// Counts a reader's read of a command's state in this pass, kept or resolved. +#[cfg(feature = "testing")] +pub(crate) fn count_command_read(ctx: &Context) { + totals(ctx, |log| log.command_reads += 1); +} + +/// The reads of command states the readers of the last pass made, kept or resolved. +#[cfg(feature = "testing")] +pub fn last_pass_command_reads(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.command_reads, 0) +} + /// Counts a kept resolution a wake walked to compare its key. #[cfg(feature = "testing")] pub(crate) fn count_wake_walk(ctx: &Context) { @@ -535,6 +547,7 @@ pub(crate) struct Totals { access_builds: u32, tip_texts: u32, resolves: [u32; 3], + command_reads: u32, wake_walks: u32, asks: Vec<(&'static str, u32)>, } diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 42225ed3dd..673b8d4ce3 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -59,9 +59,9 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; pub use crate::runtime::measure::{ MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_derived_builds, - last_frame_memo_runs, last_pass_access_builds, last_pass_body_runs as last_pass_measuring_runs, last_pass_derived_builds, last_pass_measure_asks, - last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, last_pass_tip_texts, least_runs as shrink_least_runs, - row_builds, row_measures, run as measuring_run, take_effects, widest_runs, + last_frame_memo_runs, last_pass_access_builds, last_pass_body_runs as last_pass_measuring_runs, last_pass_command_reads, + last_pass_derived_builds, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, + last_pass_tip_texts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, }; #[cfg(feature = "testing")] pub use crate::runtime::pass_state::unbound_reads as unbound_pass_state_reads; diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index 97aa8e81ad..6218acc49a 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -18,6 +18,7 @@ use crate::style::{ComponentStyle, FocusLook, GlyphRole, StyleColor, StyleCx}; use craft_behavior::overlay::{Align, Side}; use craft_behavior::{CursorIcon, HitLevel, HitPriority, IconId, Metrics, PartKey, PointerButton, PressPhase, Sense, Value}; use egui::{Pos2, Rect, Response, Vec2}; +use std::sync::Arc; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -102,9 +103,9 @@ struct Held(bool); /// What the parts step resolved for the tools this pass. struct Laid { - resolved: Vec>>, + resolved: Vec>>, /// The click command as resolved, when the button has one. - click: Option>, + click: Option>, shown: usize, } @@ -156,6 +157,10 @@ pub struct FlyoutButton<'a, T: Value + 'static> { /// The index of the tool among `tools` whose row wears the target mark while the flyout is open. #[prop(vis = "pub(crate)")] marked_row: Option, + /// The tools' commands as the rail resolved them in this pass, one per tool in order: the button shows these in + /// place of resolving each command again. + #[prop(vis = "pub(crate)")] + resolved: Option<&'a [Option>]>, laid: Option, picked: Option, open: bool, @@ -181,6 +186,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { tips: None, reveal_row: None, marked_row: None, + resolved: None, laid: None, picked: None, open: false, @@ -222,11 +228,11 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { } fn resolve(&self, cx: &MeasureCx<'_, Self>) -> Laid { - Laid { - resolved: self.tools.iter().map(|tool| cx.resolve_command(tool.command.clone())).collect(), - click: self.click.clone().and_then(|command| cx.resolve_command(command)), - shown: self.shown_at(), - } + let resolved = match self.resolved.filter(|resolved| resolved.len() == self.tools.len()) { + Some(resolved) => resolved.to_vec(), + None => self.tools.iter().map(|tool| cx.resolve_command(tool.command.clone())).collect(), + }; + Laid { resolved, click: self.click.clone().and_then(|command| cx.resolve_command(command)), shown: self.shown_at() } } /// The command the face stands for: the click command when there is one, else the shown tool's. diff --git a/crates/ui-panels/src/rails/tool.rs b/crates/ui-panels/src/rails/tool.rs index e90452e93f..c18ff08aa9 100644 --- a/crates/ui-panels/src/rails/tool.rs +++ b/crates/ui-panels/src/rails/tool.rs @@ -14,7 +14,7 @@ use crate::docking::{DockGrid, DockSizes}; use crate::layout::RowAlign; use crate::layout_components::{Row, Stack}; use crate::runtime::access::Name; -use crate::runtime::commands::resolver_in; +use crate::runtime::commands::{ResolvedCommand, resolver_in}; use crate::runtime::env::{AppValues, EnvValue, Label}; use crate::style::{ComponentStyle, GlyphRole, StyleCx, SurfaceKind, TypeRole, UiTokens}; use crate::tabs::TornOff; @@ -22,8 +22,10 @@ use craft_behavior::overlay::Side; use craft_behavior::{IconId, Metrics, NavShape, Proposal, Roving, Sense, Value}; use craft_theme::ControlSize; use egui::{Id, Rect, Response, Ui, Vec2}; +use std::borrow::Cow; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; mod data; mod drag; @@ -321,10 +323,27 @@ struct GridProps<'a, T: PlainData> { sent: Outbox<'a, RailEvent>, } -/// The host's tool tips, which the grid reads through a trait object: while the host sets them the grid runs every pass. +/// The host's tool tips, which the grid reads through a trait object, keyed by which of the slots' tools have a tip and +/// by the host's revision of them. #[derive(MemoProps)] -#[memo_props(every_pass = "the host's tips are a trait object, whose answers no key can follow")] -struct HostTips<'a, T>(&'a dyn ToolTips); +struct HostTips<'a, T> { + #[memo_props( + covered_by = "has", + reason = "away from the pointer the grid reads only which tools have a tip; a tip's body shows only while the pointer rests on its button, and the view runs in every pass the pointer is over it" + )] + tips: &'a dyn ToolTips, + /// Whether each tool of the slots, in order, has a tip. + has: Vec, + revision: u64, +} + +impl<'a, T> HostTips<'a, T> { + /// The tips of `tips` for the tools of `slots`. + fn new(tips: &'a dyn ToolTips, slots: &[ToolSlot]) -> Self { + let has = slots.iter().flat_map(|slot| &slot.tools).map(|tool| tips.has(&tool.id)).collect(); + HostTips { tips, has, revision: tips.revision() } + } +} /// What the body of one pass draws from. struct Draw<'a, T: PlainData> { @@ -348,7 +367,7 @@ impl Draw<'_, T> { /// Shows the grid as a memoized view; what the buttons report goes into `events` (nothing on a replay). Returns the /// Edit Toolbar button's id while the rail shows it, and the host's index and rect of each slot button. fn run(&self, ui: &mut Ui, events: &mut Vec>) -> (Option, Vec<(usize, Rect)>) { - let tips = self.tips.map(HostTips); + let tips = self.tips.map(|tips| HostTips::new(tips, self.slots)); let props = GridProps { slots: self.slots, current: self.current, @@ -375,11 +394,13 @@ impl Draw<'_, T> { /// each slot button, around which the rail takes drops. fn grid(props: &mut GridProps<'_, T>, ui: &mut Ui) -> (Option, Vec<(usize, Rect)>) { let GridProps { slots, current, last_used, hidden, editing, columns, opens, captions, tear_off, tips, mark, reveal, .. } = *props; - let tips = tips.map(|tips| tips.0); + let tips = tips.map(|tips| tips.tips); let visible = visible_slots(slots, hidden_in(hidden)); let cells = visible.len() + usize::from(props.edit_label.is_some()); + // Each visible tool's command, resolved once for the pass: the buttons show these and read none again. let resolve = resolver_in(ui); - let enabled = |tool: &RailTool| resolve(tool.command.clone()).is_some_and(|resolved| resolved.enabled); + let commands: Vec>>> = + visible.iter().map(|(_, tools)| tools.iter().map(|tool| resolve(tool.command.clone())).collect()).collect(); let at: Vec = visible.iter().map(|(index, _)| *index).collect(); // The first caption among a group's slots heads the group. let caption_of = |group: &[usize]| { @@ -404,13 +425,22 @@ fn grid(props: &mut GridProps<'_, T>, ui: &mut match visible.get(k) { Some((index, tools)) => { let slot = &slots[*index]; - let owned: Vec> = tools.iter().map(|tool| (*tool).clone()).collect(); + let states = commands.get(k).map_or(&[][..], Vec::as_slice); + let on = |at: usize| states.get(at).and_then(Option::as_ref).is_some_and(|resolved| resolved.enabled); + let enabled = |tool: &RailTool| tools.iter().position(|own| std::ptr::eq(*own, tool)).is_some_and(on); + // The slot's own tools, unless the host hides some of them. + let owned: Cow<'_, [RailTool]> = if tools.len() == slot.tools.len() { + Cow::Borrowed(slot.tools.as_slice()) + } else { + Cow::Owned(tools.iter().map(|tool| (*tool).clone()).collect()) + }; let Some(shown) = shown_tool(current, slot.id, tools, last_used, enabled) else { continue }; let selected = tools.iter().any(|tool| tool.id == *current); let mut button = FlyoutButton::new(&owned, &shown.id) .id_salt(("slot", slot.id)) .selected(selected) - .enabled(tools.iter().any(|tool| enabled(tool))) + .enabled((0..tools.len()).any(on)) + .resolved(states) .opens(opens); if editing { button = button.edit(SlotEdit::new(slot.id, *index, slot.tools.len(), columns == 1)); diff --git a/crates/ui-panels/src/rails/tool/data.rs b/crates/ui-panels/src/rails/tool/data.rs index cb0a1ed593..ede56102da 100644 --- a/crates/ui-panels/src/rails/tool/data.rs +++ b/crates/ui-panels/src/rails/tool/data.rs @@ -74,12 +74,22 @@ impl ToolSlot { /// The tips of a rail's tools: where a tool `has` one, its button (and the flyout's row) shows it in place of the /// command tooltip. +/// +/// The rail's grid replays its last run while the pointer is away from it and its inputs are unchanged. Its key holds +/// which tools `has` a tip and the [`revision`](ToolTips::revision); a tip's body shows only while the pointer rests on +/// a button, and the grid runs in every pass the pointer is over it. pub trait ToolTips { /// Whether `tool` has a tip. fn has(&self, tool: &T) -> bool; /// Shows the tip of `tool`. fn show(&self, tool: &T, ui: &mut Ui); + + /// A number the host changes when a tip's body changes while the tip may show without the pointer over the rail. + /// `0` unless the host sets one. + fn revision(&self) -> u64 { + 0 + } } /// The tool each slot showed last. Plain data the host keeps with its workspace. diff --git a/crates/ui-panels/tests/it/rails/mod.rs b/crates/ui-panels/tests/it/rails/mod.rs index 75f5937b7d..feacf2f095 100644 --- a/crates/ui-panels/tests/it/rails/mod.rs +++ b/crates/ui-panels/tests/it/rails/mod.rs @@ -3,6 +3,7 @@ pub(crate) mod drawer; pub(crate) mod locate; +pub(crate) mod work; use craft_behavior::{GesturePhase, Mixed, PartKey}; use craft_ui::contract::overlay::{PlacementChange, PlacementKind}; diff --git a/crates/ui-panels/tests/it/rails/work.rs b/crates/ui-panels/tests/it/rails/work.rs new file mode 100644 index 0000000000..8ca2ed9106 --- /dev/null +++ b/crates/ui-panels/tests/it/rails/work.rs @@ -0,0 +1,95 @@ +//! The work a rail does in a pass: its grid replays while the pointer is away, tips included, and a grid that runs reads +//! each tool's command once. + +use super::{CUT, REDO, UNDO, tools}; +use craft_ui::contract::tooltip::DELAY; +use craft_ui::contract::{Role, Show as _, Tracked}; +use craft_ui::display::Text; +use craft_ui::rails::{LastUsed, ToolRail, ToolSlot, ToolTips}; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::{Fixture, MemoRun, audit_replays, last_pass_command_reads, last_pass_memo_runs, trial}; +use egui::Ui; +use std::cell::Cell; +use std::rc::Rc; + +/// Undo's tip, while `on`. +struct Tips { + on: bool, +} + +impl ToolTips for Tips { + fn has(&self, tool: &u8) -> bool { + self.on && *tool == UNDO + } + + fn show(&self, _: &u8, ui: &mut Ui) { + Text::new("Steps back one edit").show(ui); + } +} + +/// A rail of two slots, Undo and Redo then Cut, with Undo's tip while `on` holds. +fn rig(on: Rc>) -> Fixture { + let slots = Tracked::new(vec![ToolSlot::new(0, tools(&[UNDO, REDO])), ToolSlot::new(1, tools(&[CUT]))]); + let last = Tracked::new(LastUsed::default()); + let mut fixture = Fixture::new(move |ui| { + let tips = Tips { on: on.get() }; + ToolRail::new("Tools", &slots, &UNDO, &last).tips(&tips).show_rail(ui, |_, _| {}); + }); + fixture.settle(); + fixture +} + +/// How the slot grid took part in the last pass: `(ran, replayed)`. +fn grid_runs(fixture: &Fixture) -> (u32, u32) { + let runs = last_pass_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, _)| name.contains("GridProps")); + runs.fold((0, 0), |(ran, replayed), (_, _, run)| match run { + MemoRun::Ran => (ran + 1, replayed), + MemoRun::Replayed => (ran, replayed + 1), + _ => (ran, replayed), + }) +} + +#[trial] +fn a_rail_with_tips_replays_its_grid_while_the_pointer_is_away_and_still_shows_the_tip() { + let on = Rc::new(Cell::new(true)); + let mut fixture = rig(Rc::clone(&on)); + fixture.frame(vec![]); + assert_eq!(grid_runs(&fixture), (0, 1), "with the pointer away and nothing changed, the grid replays"); + + let undo = fixture.by_role(Role::BUTTON).into_iter().next().expect("the Undo slot's button shows"); + fixture.frame(vec![moved(undo.center())]); + fixture.advance(DELAY); + fixture.settle(); + assert!(fixture.texts().iter().any(|run| run.text == "Steps back one edit"), "resting on Undo's button shows its tip"); + + // The grid runs on while the hover it ended winds down, about a second. + fixture.frame(vec![egui::Event::PointerGone]); + fixture.advance(2.0); + fixture.settle(); + fixture.frame(vec![]); + assert_eq!(grid_runs(&fixture), (0, 1), "once the pointer has left, the grid replays again"); + + // The audit runs the grid where it would replay and fails on any difference between the two. + audit_replays(fixture.ctx(), true); + fixture.idle(3); + audit_replays(fixture.ctx(), false); + + on.set(false); + fixture.frame(vec![]); + assert_eq!(grid_runs(&fixture), (1, 0), "a change in which tools have a tip runs the grid"); +} + +#[trial] +fn a_grid_that_runs_reads_each_tool_command_once() { + let mut fixture = rig(Rc::new(Cell::new(false))); + let undo = fixture.by_role(Role::BUTTON).into_iter().next().expect("the Undo slot's button shows"); + fixture.frame(vec![moved(undo.center())]); + fixture.frame(vec![moved(undo.center() + egui::vec2(1.0, 0.0))]); + assert_eq!(grid_runs(&fixture).0, 1, "with the pointer over it, the grid runs"); + let reads = last_pass_command_reads(fixture.ctx()); + assert!(reads <= READS, "a pass of the grid reads {reads} command states, at most {READS}"); +} + +/// The command reads of a pass in which the grid runs: each of the 3 tools once, and those of the two buttons' faces. +/// A grid whose buttons resolve each tool again reads 18. +const READS: u32 = 9;