diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 3d1204ce5e..a852119d72 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -202,7 +202,7 @@ fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { .zip(&labels.menus) .map(|((menu, title), level)| { // The commands the title holds, for the palette's callout; a built-in has no command of the app. - let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect(); + let held = menu.children.iter().flat_map(node_commands).filter(|command| Builtin::of(command).is_none()).collect::>(); let row = MenuTitle::new(title.label.clone(), move |ui| shared.show(ui, &menu.children, level)).holds(held); match title.hidden { Some(letter) => row.mnemonic(letter), diff --git a/crates/ui-contract/src/contract/steps/report.rs b/crates/ui-contract/src/contract/steps/report.rs index d7cfe572c9..5a7b1873fc 100644 --- a/crates/ui-contract/src/contract/steps/report.rs +++ b/crates/ui-contract/src/contract/steps/report.rs @@ -115,7 +115,7 @@ fn report_access(p: &dyn ErasedPass<'_>, facts: &TypeFacts, input: &ReportIn<'_> let resolved = core.resolved; // Before any return: a component without an AccessKit node (merged, or AccessKit off) still records its command // for the inspected region, which keytips place their badges by. - inspect::note_command(ctx, id, core.command.as_deref().map(|command| command.command.clone())); + inspect::note_command(ctx, id, core.command.as_deref().map(|command| (*command.command).clone())); let paint = core.paint.borrow(); if role == Role::Merged { let facts = scope::Merged { diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 8d3474f5cd..2cb20ce175 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -413,7 +413,7 @@ impl Shown { /// The entry `reader` keeps for `command`. fn find(&self, reader: &Reader, number: u32, command: &CommandRef) -> Option { let ids = self.by_reader.get(reader)?.get(&number)?; - ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| entry.kept.resolved.command == *command)) + ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| *entry.kept.resolved.command == *command)) } /// Keeps `kept` for `reader`, in place of what it kept for the same command. @@ -841,7 +841,7 @@ impl Board { hint_alone: state.is_some_and(CommandState::is_hint_alone), kind: def.map_or(CommandKind::Command, |def| def.kind.clone()), edit: self.registry.edit_of(&command.id).is_some(), - command: command.clone(), + command: Arc::new(command.clone()), instance, }; (resolved, key) @@ -1809,7 +1809,10 @@ pub(crate) fn fire_resolved(ctx: &Context, command: &ResolvedCommand, source: Fi if !command.enabled || !crate::runtime::measure::effect(ctx, "board::fire_resolved") { return false; } - queue(ctx, Fired { target: command.instance, ..Fired::new(command.command.clone(), source, FirePhase::Press, pass::now(ctx)) }.mods(mods)); + queue( + ctx, + Fired { target: command.instance, ..Fired::new(CommandRef::clone(&command.command), source, FirePhase::Press, pass::now(ctx)) }.mods(mods), + ); true } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index dc6a98264b..f95bf0bde8 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -407,7 +407,8 @@ pub struct ResolvedCommand { /// The command is an edit a focused component takes as its own (it has an `EditCommand` link): a control bound to /// it keeps the focus where it is on a press, so the edit reaches the focused component. pub edit: bool, - pub(crate) command: CommandRef, + /// Shared by every fact that shows this resolution, so a settled view's facts copy no command. + pub(crate) command: Arc, /// Something besides the command's own state refuses it: the gate, the modal rule, the instance's liveness or a /// focused component whose edit does nothing now. A key whose app-scope command its state alone disables is /// declined (`FrameOutput::declined`); a refused one is not. @@ -781,7 +782,7 @@ struct ShownFact { /// What a [`ShownFact`] shows: a bound component's command, or the commands a container holds. #[derive(Clone, Debug, PartialEq)] enum ShownCommands { - Bound(CommandRef), + Bound(Arc), Held(Arc<[CommandRef]>), } @@ -789,7 +790,7 @@ impl ShownFact { /// Whether the fact shows `command`. fn shows(&self, command: &CommandRef) -> bool { match &self.commands { - ShownCommands::Bound(bound) => bound == command, + ShownCommands::Bound(bound) => **bound == *command, ShownCommands::Held(held) => held.contains(command), } } @@ -813,17 +814,17 @@ fn register_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label /// Records that a container at `rect` holds `commands`, for this pass and viewport. Not [`CommandInput::holds`], which /// turns hold bindings on. -pub fn holds(ctx: &Context, layer: LayerKey, rect: egui::Rect, commands: &[CommandRef], label: Label) { +pub fn holds(ctx: &Context, layer: LayerKey, rect: egui::Rect, commands: &Arc<[CommandRef]>, label: Label) { if !commands.is_empty() { - register_shown(ctx, layer, rect, label, ShownCommands::Held(commands.into())); + register_shown(ctx, layer, rect, label, ShownCommands::Held(Arc::clone(commands))); } } /// Records that the bound component of `command` was shown at `rect` in `layer`, with `label`, for this pass and /// viewport: the report step calls it for a component wholly inside its clip. // PLAN: the caller is the report step (menus-w3); until it lands nothing in this crate calls it. -pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label, command: &CommandRef) { - register_shown(ctx, layer, rect, label, ShownCommands::Bound(command.clone())); +pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label: Label, command: &Arc) { + register_shown(ctx, layer, rect, label, ShownCommands::Bound(Arc::clone(command))); } /// How many shown-command registrations the running viewport's last pass made: one per bound component and one per @@ -831,7 +832,23 @@ pub(crate) fn note_shown(ctx: &Context, layer: LayerKey, rect: egui::Rect, label #[cfg(feature = "testing")] #[doc(hidden)] pub fn shown_registrations(ctx: &Context) -> usize { - Facts::::of_last_pass(ctx).len() + Facts::::with_last_pass(ctx, <[ShownFact]>::len) +} + +/// The commands the bound components of the running viewport's last pass showed, in registration order: the values +/// the facts hold, so two passes that copied no command give the same allocations. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn shown_commands(ctx: &Context) -> Vec> { + Facts::::with_last_pass(ctx, |facts| { + facts + .iter() + .filter_map(|fact| match &fact.commands { + ShownCommands::Bound(command) => Some(Arc::clone(command)), + ShownCommands::Held(_) => None, + }) + .collect() + }) } /// Where `command` was shown in the last pass: a bound component's clipped rect or a holder's rect. `None` unless it @@ -839,11 +856,14 @@ pub fn shown_registrations(ctx: &Context) -> usize { pub fn shown(ctx: &Context, command: &CommandRef) -> Option { let viewport = pass::current_viewport(ctx); let scrim = overlay::top_modal_in(ctx, viewport).and_then(|top| top.cover); - Facts::::of_last_pass(ctx) - .into_iter() - .filter(|fact| fact.shows(command)) - .find(|fact| !areas::rects_over(ctx, fact.layer, scrim).iter().any(|over| over.intersects(fact.rect))) - .map(|fact| Shown { rect: fact.rect, viewport, label: fact.label, holder: matches!(fact.commands, ShownCommands::Held(_)) }) + // The rects over a fact are read outside the facts' record, which `with_last_pass` holds. + let showing: Vec = Facts::::with_last_pass(ctx, |facts| facts.iter().filter(|fact| fact.shows(command)).cloned().collect()); + showing.into_iter().find(|fact| !areas::rects_over(ctx, fact.layer, scrim).iter().any(|over| over.intersects(fact.rect))).map(|fact| Shown { + rect: fact.rect, + viewport, + label: fact.label, + holder: matches!(fact.commands, ShownCommands::Held(_)), + }) } /// Where a command was shown, from [`shown`]. diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index fb53719828..c4927a38c1 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -950,17 +950,22 @@ impl Facts { Self::with_record(ctx, |record| record.this.push(fact)); } - /// The facts the running viewport's previous pass registered, in registration order. + /// `f` on the facts the running viewport's previous pass registered, in registration order. `f` reaches no + /// service: the record is held while it runs. #[doc(hidden)] - pub fn of_last_pass(ctx: &Context) -> Vec { - Self::with_record(ctx, |record| record.last.clone()) + pub fn with_last_pass(ctx: &Context, f: impl FnOnce(&[T]) -> R) -> R { + Self::with_record(ctx, |record| f(&record.last)) } fn with_record(ctx: &Context, f: impl FnOnce(&mut FactRecord) -> R) -> R { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); let advance = |record: &mut FactRecord, step: PassStep| match step { - PassStep::Next => record.last = std::mem::take(&mut record.this), + // The buffers swap, so a pass reuses the room the pass before it grew. + PassStep::Next => { + std::mem::swap(&mut record.last, &mut record.this); + record.this.clear(); + } PassStep::Skipped => { record.last.clear(); record.this.clear(); diff --git a/crates/ui-contract/src/testing/memory.rs b/crates/ui-contract/src/testing/memory.rs index 5f029eb593..e2f9745b87 100644 --- a/crates/ui-contract/src/testing/memory.rs +++ b/crates/ui-contract/src/testing/memory.rs @@ -95,7 +95,7 @@ pub fn register_fact(ctx: &Context) -> Vec { - Facts::of_last_pass(ctx) + Facts::with_last_pass(ctx, <[T]>::to_vec) } /// Runs `f` on a child `Ui` of `ui`. diff --git a/crates/ui-contract/tests/it/runtime/shown.rs b/crates/ui-contract/tests/it/runtime/shown.rs index f74d64a108..835a7639b2 100644 --- a/crates/ui-contract/tests/it/runtime/shown.rs +++ b/crates/ui-contract/tests/it/runtime/shown.rs @@ -1,8 +1,14 @@ //! Where commands were shown (`commands::holds`, `commands::shown`). +use craft_ui::contract::{CommandSet, MemoProps, MemoView, Props as _, Show as _}; use craft_ui::runtime::commands::{self, CommandRef}; use craft_ui::runtime::env::Label; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::{Fixture, Frames, MemoRun, last_frame_memo_runs, trial}; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::RefCell; +use std::sync::Arc; /// A container that holds a hundred commands, as a menu title holds its menu's, registers once per pass: a replay of /// the menu bar then makes one registration per title, not one per command (photocraft#15493). Each command is still @@ -10,7 +16,7 @@ use craft_ui::testing::{Fixture, trial}; #[trial] fn a_container_registers_its_commands_once() { let held: Vec = (0..100).map(|i| CommandRef::new(format!("test.held{i}"))).collect(); - let shown = held.clone(); + let shown: Arc<[CommandRef]> = held.clone().into(); let mut fixture = Fixture::new(move |ui| { let rect = egui::Rect::from_min_size(ui.max_rect().min, egui::vec2(40.0, 20.0)); commands::holds(ui.ctx(), ui.layer_id(), rect, &shown, Label::from("Image")); @@ -24,3 +30,52 @@ fn a_container_registers_its_commands_once() { } assert!(commands::shown(fixture.ctx(), &CommandRef::new("test.other")).is_none(), "a command nothing holds is not shown"); } + +/// The command every probe of the leaves view is bound to. +#[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] +#[command(prefix = "shownTrial")] +#[non_exhaustive] +enum Bound { + #[command(label = "Apply")] + Apply, +} + +/// A memoized view of `count` probes bound to `Bound::Apply`. +#[derive(MemoProps)] +struct Leaves { + count: usize, +} + +fn leaves(props: &mut Leaves, ui: &mut Ui) { + for _ in 0..props.count { + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).command(Bound::Apply).show(ui); + } +} + +/// A settled view's replay registers where its bound components show their commands with the very commands the run +/// registered, so a settled pass copies no command, however many it shows. +#[trial] +fn a_settled_pass_shows_its_commands_without_copying_them() { + for count in [10, 40] { + let mut frames = Frames::new(); + frames.screen(Vec2::new(400.0, 1400.0)); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(200.0, 1300.0)), |ui| { + MemoView::new("leaves", Leaves { count }, leaves).show(ui); + }); + }; + frames.idle(30, &mut show); + frames.frame(vec![], &mut show); + let before = commands::shown_commands(&frames.ctx); + frames.frame(vec![], &mut show); + let after = commands::shown_commands(&frames.ctx); + assert!(last_frame_memo_runs(&frames.ctx).iter().all(|(_, _, run)| *run != MemoRun::Ran), "the view of {count} probes is settled"); + assert_eq!(before.len(), count, "each of the {count} probes is shown"); + assert_eq!(after.len(), count, "the settled pass registers each of the {count} probes again"); + assert!( + before.iter().zip(&after).all(|(before, after)| Arc::ptr_eq(before, after)), + "a settled pass of {count} probes shows the commands the pass before it showed, not copies" + ); + } +} diff --git a/crates/ui-patterns/tests/it/panels/palette.rs b/crates/ui-patterns/tests/it/panels/palette.rs index ecfd5ea24a..4be3f59a23 100644 --- a/crates/ui-patterns/tests/it/panels/palette.rs +++ b/crates/ui-patterns/tests/it/panels/palette.rs @@ -14,6 +14,7 @@ use craft_ui::testing::{Fixture, Registry, trial}; use egui::{Key, Modifiers, Pos2, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; +use std::sync::Arc; /// App commands with the default modal rule: blocked while a dialog is open. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] @@ -488,7 +489,7 @@ fn the_active_row_marks_its_shown_control_and_a_hidden_home_goes_to_the_footer() // Flip is held by a rect in the corner, the way a menu title holds its commands; Rotate has a bound button. let mut rig = rig(entries, Some(vec![TrialCommand::Flip.into()]), false, |ui| { let corner = egui::Rect::from_min_size(ui.max_rect().min, Vec2::new(60.0, 20.0)); - commands::holds(ui.ctx(), ui.layer_id(), corner, &[TrialCommand::Flip.into()], Label::from("Rail slot")); + commands::holds(ui.ctx(), ui.layer_id(), corner, &Arc::from([CommandRef::from(TrialCommand::Flip)]), Label::from("Rail slot")); ui.add_space(24.0); Button::command(TrialCommand::Rotate).show(ui); }); diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index 39d3fded6c..1348430404 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -45,6 +45,7 @@ use craft_host::target::MenuPlacement; use craft_keymap::mnemonic; use craft_theme::Flags; use egui::{Context, Pos2, Rect, Response, Ui, Vec2}; +use std::sync::Arc; const TITLE: PartKey = PartKey::new("title"); const MORE: PartKey = PartKey::new("more"); @@ -207,7 +208,7 @@ type TitleText = (String, Option<(char, Option)>); pub struct MenuTitle<'a> { label: Label, body: Box, - holds: Vec, + holds: Arc<[CommandRef]>, /// The letter that opens the menu in place of the bar's own pick. mnemonic: Option, } @@ -215,7 +216,7 @@ pub struct MenuTitle<'a> { impl<'a> MenuTitle<'a> { /// A menu titled `label` (a `&` marks the mnemonic) whose rows `body` shows. pub fn new(label: impl Into