diff --git a/crates/story-render/src/main.rs b/crates/story-render/src/main.rs index f3214431f..2af9566eb 100644 --- a/crates/story-render/src/main.rs +++ b/crates/story-render/src/main.rs @@ -25,7 +25,7 @@ //! contrast without them). A value that is not one of these is refused. `stories.tsv` lists the scale of every image. use craft_behavior::ColumnWidth; -use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface}; +use craft_ui::contract::{Pad, Scroll, ShowContainer as _, Surface, Tracked}; use craft_ui::fonts::{I18nScripts, UiFonts}; use craft_ui::layout_components::{Grid, Stack}; use craft_ui::runtime::commands::CommandInput; @@ -312,7 +312,7 @@ fn render(job: &Job, renderer: &mut Renderer, env: &RootEnv, options: &Options) // The command states of the story shown, as the gallery gives them, before the first frame. The Overview gives its // cards none, so a card is rendered under none. frames.commands(match &job.shown { - Shown::Story(registration) => Story::command_input([®istration.story]), + Shown::Story(registration) => CommandInput::new().states(&Tracked::new(Story::command_states([®istration.story]))), Shown::Card(_) => CommandInput::new(), }); let (shown, dialog) = match &job.shown { diff --git a/crates/ui-canvas/tests/it/canvas/tool.rs b/crates/ui-canvas/tests/it/canvas/tool.rs index c4844b832..b5f9dd435 100644 --- a/crates/ui-canvas/tests/it/canvas/tool.rs +++ b/crates/ui-canvas/tests/it/canvas/tool.rs @@ -1082,7 +1082,7 @@ fn a_held_space_pans_over_a_canvas_control_and_leaves_it_unchanged() { fn a_queued_space_whose_hand_the_gate_refuses_leaves_the_press_to_the_selected_tool() { let log = Log::default(); let (mut fixture, view, canvas) = momentary_canvas(Probe::new("main", &log)); - fixture.gate(CommandGate::new(|command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle(); + fixture.gate(CommandGate::new((), |_: &(), command| !matches!(MomentaryCommands::from_ref(command), Some(MomentaryCommands::Hand)))).settle(); let at = fixture.by_role(Role::CANVAS)[0].rect.center(); let before = view.get().expect("the canvas ran").center; let space = craft_keymap::Key::Space; diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index d6ee47c52..701f2643e 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -52,7 +52,7 @@ impl MeasureCx<'_, C> { /// `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above /// the component, and the enabled state of its instance. `None` when the command is scoped and no instance of /// its scope is above the component. - pub fn resolve_command(&self, command: impl Into) -> Option { + pub fn resolve_command(&self, command: impl Into) -> Option> { commands::resolve_scoped(self.ui.ctx(), self.env.command_chain(), &command.into()) } diff --git a/crates/ui-contract/src/contract/steps/env.rs b/crates/ui-contract/src/contract/steps/env.rs index 1fa643e51..cbb9d58de 100644 --- a/crates/ui-contract/src/contract/steps/env.rs +++ b/crates/ui-contract/src/contract/steps/env.rs @@ -33,7 +33,7 @@ pub(crate) fn variants(asked: Option) -> (Variant, Varian /// size; variant; label. /// `(requested, variant)` comes from `variants`. pub(crate) fn env(ctx: &Context, env: &Env, common: &Common, (requested, variant): (Variant, Variant)) -> EnvStep { - let command = common.command.as_ref().map(|command| Arc::new(commands::resolve_bound(ctx, &env.commands, command))); + let command = common.command.as_ref().map(|command| commands::resolve_bound(ctx, &env.commands, command)); let label = match (&common.label, &command) { (Label::Empty, Some(command)) => Label::Shared(command.label.clone()), (label, _) => label.resolved(&env.words), diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index ca350161d..641445c16 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -5,9 +5,12 @@ use super::{ AppCatalog, CommandChain, CommandGate, CommandInput, CommandScope, CommandSet, CommandState, EditCommands, FirePhase, FireSource, Fired, ResolvedCommand, WindowShortcut, registry, }; +use crate::contract::Revision; use crate::runtime::egui::sizing::{Rerun, request_discard}; use crate::runtime::egui::{pass, repaint}; use crate::runtime::focus::EditSet; +#[cfg(feature = "testing")] +use crate::runtime::measure::Resolve; use crate::runtime::pass_state; use crate::runtime::reads::{self, BindKey}; use crate::runtime::{focus, frame, keys, lazy, measure, overlay, replay, sampler}; @@ -48,13 +51,20 @@ impl Instances { self.list.iter() } - /// Registers `instance`, keeping the place of one already registered under the same id. - fn upsert(&mut self, instance: Instance) { + /// Registers `instance`, keeping the place of one already registered under the same id. Returns whether a + /// resolution can see the difference: the id is new, or its scope, viewport or layer changed. + fn upsert(&mut self, instance: Instance) -> bool { match self.at.get(&instance.id) { - Some(at) => self.list[*at] = instance, + Some(at) => { + let held = &self.list[*at]; + let seen = held.scope != instance.scope || held.viewport != instance.viewport || held.layer != instance.layer; + self.list[*at] = instance; + seen + } None => { self.at.insert(instance.id, self.list.len()); self.list.push(instance); + true } } } @@ -110,13 +120,23 @@ pub(crate) struct Board { app: Option, keymap: Option, gate: Option, - /// The gate's answers in this frame, by command key (`CommandRef::key`). The gate answers from what the app knew - /// before the frame, so the board asks it once per command per frame, whichever readers and passes resolve it. + /// The gate's answers under its current key, by command key (`CommandRef::key`). The gate is a `fn` of its props, + /// so the board asks it once per command until the key moves, whichever readers, passes and frames resolve it. gate_answers: HashMap, /// Command ids by number, so a state lookup allocates nothing. numbers: HashMap, + /// The app-scope states of the app's `Tracked`, by command number, and the revision they are of. + app_states: HashMap, + app_revision: Option, + /// The states instances published this frame and last frame; a resolution reads this frame's, else last frame's. this: HashMap, last: HashMap, + /// The revision of each state key that has changed: the value of `state_seq` when it last did. + revisions: HashMap, + /// Moves with every state change. + state_seq: u64, + /// The generations of the inputs every resolution reads and of the focus vantage. + gens: Gens, /// What the frame's input changed, under the root frame it arrived for (`set_input`). changed: (u64, InputChanges), /// Scoped commands waiting for their instance. @@ -149,8 +169,8 @@ pub(crate) struct Board { unknown: HashSet, /// App catalog ids that a linked set also defines, already logged. shadowed: HashSet, - /// What each reader was shown, by the state key it read and its viewport (`note_read`). - shown: ShownMap, + /// What each reader was shown, by viewport (`read`). + shown: HashMap, /// The scope each child scope is declared inside: an instance of the child is also an instance of the parent. parents: HashMap<&'static str, &'static str>, } @@ -168,7 +188,7 @@ fn same_state(a: Option<&CommandState>, b: Option<&CommandState>) -> bool { a.cloned().unwrap_or_default() == b.cloned().unwrap_or_default() } -/// Who read a command's resolution: the vantage `begin` resolves it from again. +/// Who read a command's resolution: the vantage it is resolved from again. #[derive(Clone, PartialEq, Eq, Hash)] enum Reader { /// A surface with no component of its own (`resolve_global`): the key focus of the running pass. @@ -182,36 +202,135 @@ enum Reader { InMenu(Id, CommandChain), } -/// 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>>; +impl Reader { + /// The reader's kind, for the testing check's message. + #[cfg(feature = "testing")] + fn kind(&self) -> &'static str { + match self { + Reader::Global => "global", + Reader::Beneath(_) => "beneath-layer", + Reader::Chain(_) => "component", + Reader::InMenu(..) => "in-menu", + } + } -/// 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) { - 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())), + /// The layer or menu whose vantage this reader is judged from, which the reader goes with when it closes. + fn layer(&self) -> Option { + match self { + Reader::Beneath(layer) | Reader::InMenu(layer, _) => Some(*layer), + _ => None, + } } } -/// Notes, in the read record, that the running code showed the state under `key`, and keeps what `reader` was shown: a -/// settled region that showed it runs when `begin` resolves the command from the same reader to something else (a -/// state, the gate, a modal layer or an instance changed), and a change published after it in the pass runs the pass -/// again. -fn note_read(ctx: &Context, key: Option, reader: Reader, resolved: &ResolvedCommand) { +/// The generations of what resolutions read beside states and the gate. +#[derive(Clone, Copy, Default, PartialEq)] +struct Gens { + /// Read by every resolution: the keymap, the app catalog and the registry, the scope parents, the instances and + /// their liveness, and the modal facts (open layers, their roots, the states published inside them, a dialog + /// owning the keys, the held-open canvas). + shared: u64, + /// Read by a resolution that picks an instance or reaches by focus: the instances around the focus, in each + /// viewport and last focused, and those inside the top modal layer. + focus: u64, +} + +/// What a resolution read besides the board's own generation and the gate. +#[derive(Default)] +struct Reads { + /// It picked an instance for a source with no component of its own, or reached by the focus. + focus: bool, + /// It read the edits of the stop that holds key focus as the resolution ran (`None` when that stop takes none). + edits: Option>, +} + +/// The inputs a kept resolution was made from: it holds while each is unchanged. +#[derive(Clone, PartialEq)] +struct ResolveKey { + shared: u64, + /// The focus generation, when the resolution read the focus. + focus: Option, + /// The state key read and its revision. + state: Option<(StateKey, u64)>, + /// The gate's key and its answer, with a gate. + gate: Option<(u128, bool)>, + /// The focused stop's edits, when the resolution read them. + edits: Option>, + /// The vantage of a reader under a layer or inside a menu (`None` inside: no stop to return to). + vantage: Option>, +} + +/// A resolution a reader was shown, and what it was made from. +struct Kept { + resolved: Arc, + key: ResolveKey, +} + +/// The inputs as a viewport's last wake saw them. +#[derive(Clone, Copy, Default, PartialEq)] +struct Woke { + gens: Gens, + state_seq: u64, + gate: Option, + edits: Option<(EditSet, EditSet)>, +} + +/// What each reader of a viewport was shown, by reader and command number (a command's parameter variants share the +/// number). +#[derive(Default)] +struct Shown { + kept: HashMap>>, + /// The inputs at the last wake. + woke: Option, + /// A reader under a layer or inside a menu is kept: its vantage is read again at every wake. + layered: bool, + /// A kept resolution read the focused stop's edits. + edits: bool, +} + +/// Whether `key` still holds under the board's `gens`, `revisions` and current `gate` answer, the focused stop's edits +/// `edits` and the reader's `vantage`. A gate whose key moved but whose answer is the same keeps the resolution, under +/// the new key. +fn holds( + key: &mut ResolveKey, + gens: Gens, + revisions: &HashMap, + gate: Option<(u128, bool)>, + edits: impl FnOnce() -> Option<(EditSet, EditSet)>, + vantage: Option<&Option>, +) -> bool { + let same = key.shared == gens.shared + && key.focus.is_none_or(|focus| focus == gens.focus) + && key.state.is_none_or(|(state, revision)| revisions.get(&state).copied().unwrap_or(0) == revision) + && key.vantage.as_ref() == vantage + && key.edits.is_none_or(|kept| kept == edits()); + let gate = match (key.gate, gate) { + (kept, now) if kept == now => true, + (Some((_, kept)), Some((now, answer))) if kept == answer => { + key.gate = Some((now, answer)); + true + } + _ => false, + }; + same && gate +} + +/// The edits of the stop that holds key focus in `viewport`, and those of them that do nothing now. +fn focused_edits(ctx: &Context, viewport: ViewportId) -> Option<(EditSet, EditSet)> { + focus::record(ctx, viewport).keys.map(|keys| (keys.edits, keys.inactive)) +} + +/// Notes, in the read record, that the running code showed the state under `key`: a settled region that showed it +/// runs when `begin` resolves the command from the same reader to something else (a state, the gate, a modal layer or +/// an instance changed), and a change published after it in the pass runs the pass again. +fn note_read(ctx: &Context, key: Option) { let Some((number, instance)) = key else { return }; reads::note(ctx, BindKey::Command(number, instance), Id::NULL, measure::active(ctx), &[]); - let viewport = pass::current_viewport(ctx); - with(ctx, |board| keep_shown(&mut board.shown, (number, instance), viewport, reader, resolved)); } /// Where a resolution judges a command from: the modal facts and the focus. The board's own is the key focus of the /// running pass; a surface that closes before its command runs (the palette) judges from the window under it. -#[derive(Clone, Default)] +#[derive(Clone, Default, PartialEq)] struct Vantage { /// A modal layer blocks a window. modal_open: bool, @@ -234,7 +353,70 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Board) -> R) -> R { pass_state::with::(ctx, f) } +/// What a reader's lookup found. +enum Lookup { + /// A kept resolution whose inputs are unchanged, and the state key it read. + Fresh(Arc, Option), + /// A kept resolution some input of which changed. + Stale, + /// None. + Missing, +} + impl Board { + /// Notes that the state under `key` changed: the readers of it resolve again. + fn bump_state(&mut self, key: StateKey) { + self.state_seq += 1; + self.revisions.insert(key, self.state_seq); + } + + /// The gate's key and its answer for `command`, asking it once per command under each key. + fn gate_answer(&mut self, command: &CommandRef) -> Option<(u128, bool)> { + let gate = self.gate.as_ref()?; + let answer = match self.gate_answers.get(command.key_text().as_ref()) { + Some(answer) => *answer, + None => { + let answer = gate.allows(command); + self.gate_answers.insert(command.key(), answer); + answer + } + }; + Some((gate.key(), answer)) + } + + /// What `reader` of `viewport` was shown of `command`, judged from `vantage` (a layered reader's). + fn lookup(&mut self, ctx: &Context, viewport: ViewportId, reader: &Reader, command: &CommandRef, vantage: Option<&Option>) -> Lookup { + let Some(&number) = self.numbers.get(command.id.as_str()) else { return Lookup::Missing }; + let gate = self.gate_answer(command); + let Some(kept) = self + .shown + .get_mut(&viewport) + .and_then(|shown| shown.kept.get_mut(reader)) + .and_then(|by_number| by_number.get_mut(&number)) + .and_then(|list| list.iter_mut().find(|kept| kept.resolved.command == *command)) + else { + return Lookup::Missing; + }; + if holds(&mut kept.key, self.gens, &self.revisions, gate, || focused_edits(ctx, viewport), vantage) { + Lookup::Fresh(Arc::clone(&kept.resolved), kept.key.state.map(|(state, _)| state)) + } else { + Lookup::Stale + } + } + + /// Keeps `resolved`, made from `key`, as what `reader` of `viewport` was shown. + fn keep(&mut self, viewport: ViewportId, reader: Reader, resolved: Arc, key: ResolveKey) { + let Some(&number) = self.numbers.get(resolved.command.id.as_str()) else { return }; + let shown = self.shown.entry(viewport).or_default(); + shown.layered |= reader.layer().is_some(); + shown.edits |= key.edits.is_some(); + let list = shown.kept.entry(reader).or_default().entry(number).or_default(); + match list.iter_mut().find(|kept| kept.resolved.command == resolved.command) { + Some(kept) => *kept = Kept { resolved, key }, + None => list.push(Kept { resolved, key }), + } + } + fn live(&self, ctx: &Context, instance: &Instance) -> bool { instance.stamp + 1 >= pass::pass_nr(ctx, instance.viewport) } @@ -370,7 +552,8 @@ impl Board { /// Who answers for `command` ahead of the app: an instance inside the top modal layer that published its state, /// else the focused component when it takes the command as an edit (inside a modal layer, only when the focus /// is in it). - fn declaring(&self, ctx: &Context, command: &CommandRef, from: &Vantage) -> Option { + fn declaring(&self, ctx: &Context, command: &CommandRef, from: &Vantage, reads: &mut Reads) -> Option { + reads.focus = true; let dialog_open = from.modal_open || from.dialog_keys; let number = *self.numbers.get(command.id.as_str())?; let published = self.modal_published.iter().chain(&self.modal_published_last).find(|(published, _)| *published == number); @@ -378,10 +561,10 @@ impl Board { return Some(Declaration::Instance(id)); } let edit = self.registry.edit_of(&command.id)?; - let keys = from - .edits - .map(|edits| (edits, from.inactive.unwrap_or(EditSet::NONE))) - .or_else(|| focus::record(ctx, pass::current_viewport(ctx)).keys.map(|keys| (keys.edits, keys.inactive))); + let keys = match from.edits { + Some(edits) => Some((edits, from.inactive.unwrap_or(EditSet::NONE))), + None => *reads.edits.insert(focused_edits(ctx, pass::current_viewport(ctx))), + }; let in_reach = !dialog_open || !from.inside_modal.is_empty(); let (edits, inactive) = keys.filter(|_| in_reach)?; edits.contains(edit).then_some(Declaration::Focused { inactive: inactive.contains(edit) }) @@ -396,6 +579,7 @@ impl Board { instance: Option, reach: Reach<'_>, from: &Vantage, + reads: &mut Reads, ) -> (ResolvedCommand, Option) { let def = self.def(&command.id); let app = self.to_app(self.scope_of(command)); @@ -404,7 +588,7 @@ impl Board { // A command no set registers is never blocked. let rule = def.map(|def| def.modal); // The instance inside the top modal that declares the command, which then answers for it. - let declaring = (rule == Some(ModalRule::Declared)).then(|| self.declaring(ctx, command, from)).flatten(); + let declaring = (rule == Some(ModalRule::Declared)).then(|| self.declaring(ctx, command, from, reads)).flatten(); // The declaring instance answers for the command: it is where the command is delivered. The focused component // answers for itself, so the app's state of the command does not apply. let instance = match declaring { @@ -416,13 +600,20 @@ impl Board { Some(Declaration::Focused { .. }) => None, None => self.state_key(command, instance), }; - let this = key.and_then(|key| self.this.get(&key)); - let last = key.and_then(|key| self.last.get(&key)); + // An app-scope state is the app's held one; an instance's is this frame's publish, else last frame's. + let (this, last) = match key { + Some((number, None)) => (self.app_states.get(&number), None), + Some(key) => (self.this.get(&key), self.last.get(&key)), + None => (None, None), + }; let state = this.or(last); let flags = resolve_flags(this.map(CommandState::flags), last.map(CommandState::flags)); let reached = declaring.is_some() || instance.is_some_and(|id| match reach { - Reach::Focus => from.inside_modal.contains(&id), + Reach::Focus => { + reads.focus = true; + from.inside_modal.contains(&id) + } Reach::Chain(chain) => chain.ids().skip_while(|at| !self.is_modal_root(*at)).any(|at| at == id), }); let modal = !dialog_open @@ -494,7 +685,10 @@ fn chord_input(chord: &Chord) -> KeyInput { /// Loads the linked command sets; the stories' sets only with `stories`. pub(crate) fn install(ctx: &Context, stories: bool) -> Result<(), registry::CommandDefError> { let registry = registry::Registry::shared(stories)?; - with(ctx, |board| board.registry = registry); + with(ctx, |board| { + board.registry = registry; + board.gens.shared += 1; + }); Ok(()) } @@ -651,7 +845,9 @@ fn keymap_for(registry: &Arc, app: Option<&AppCatalog>, plat #[doc(hidden)] pub fn declare_child(ctx: &Context, child: CommandScope, parent: CommandScope) { with(ctx, |board| { - board.parents.insert(child.name(), parent.name()); + if board.parents.insert(child.name(), parent.name()) != Some(parent.name()) { + board.gens.shared += 1; + } }); } @@ -665,24 +861,48 @@ fn platform(ctx: &Context) -> Platform { crate::runtime::windows::os_of(ctx) } -/// Before each frame: last frame's state is the fallback, the app's states, gate and catalog are this frame's, and the -/// keymap follows the user's overrides and the catalog's generation. The readers of a state that changed run from -/// `begin`, which resolves again what each was shown. +/// Before each frame: the states instances published last frame are the fallback, the app's states are read again +/// when their revision moved, the gate and the catalog are this frame's, and the keymap follows the user's overrides +/// and the catalog's generation. The readers of an input that changed run from `begin`, which resolves again what each +/// was shown. pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { let platform = platform(ctx); let frame = pass::root_frame_nr(ctx); let generation = input.catalog.as_ref().map(AppCatalog::generation); let shadowed = with(ctx, |board| { - let mut states = HashMap::new(); - for (command, state) in &input.states { - let number = board.number(&command.id); - states.insert((number, None), state.clone()); + // A published state resolves from this frame's, else the last frame's: one published last frame and not again + // is gone now. + let gone: Vec = board.last.keys().filter(|key| !board.this.contains_key(key)).copied().collect(); + board.last = std::mem::take(&mut board.this); + for key in gone { + board.bump_state(key); + } + if board.modal_published_last.iter().any(|key| !board.modal_published.contains(key)) { + board.gens.shared += 1; } - // A state resolves from this frame's, else the last frame's. - board.last = std::mem::replace(&mut board.this, states); board.modal_published_last = std::mem::take(&mut board.modal_published); + let revision = input.states.as_ref().map(|(revision, _)| *revision); + if revision != board.app_revision { + board.app_revision = revision; + let mut states = HashMap::new(); + for (command, state) in input.states.iter().flat_map(|(_, states)| states.iter()) { + states.insert(board.number(&command.id), state.clone()); + } + let changed: Vec = states + .iter() + .filter(|(number, state)| board.app_states.get(number) != Some(*state)) + .map(|(number, _)| *number) + .chain(board.app_states.keys().filter(|number| !states.contains_key(number)).copied()) + .collect(); + board.app_states = states; + for number in changed { + board.bump_state((number, None)); + } + } + if input.gate.as_ref().map(CommandGate::key) != board.gate.as_ref().map(CommandGate::key) { + board.gate_answers.clear(); + } board.gate = input.gate.clone(); - board.gate_answers.clear(); board.app = input.catalog.clone(); let stale = board.keymap.as_ref().is_none_or(|cache| { cache.platform != platform @@ -699,6 +919,7 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { 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, shown_text }); + board.gens.shared += 1; 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()); @@ -765,7 +986,11 @@ 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| board.instances.upsert(Instance { id, scope, viewport, stamp, layer })); + with(ctx, |board| { + if board.instances.upsert(Instance { id, scope, viewport, stamp, layer }) { + board.gens.shared += 1; + } + }); } /// Records the instances around the component `id`, which holds key focus in the running pass of its viewport. The @@ -788,11 +1013,14 @@ 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; - match root { + let held = match root { Some(root) => board.modal_roots.insert(viewport, root), None => board.modal_roots.remove(&viewport), }; + if board.here.modal_open != open || held != root { + board.gens.shared += 1; + } + board.here.modal_open = open; }); } @@ -849,51 +1077,48 @@ fn vantage_under(ctx: &Context, layer: Id, stop: Option<(focus::StopRec, Vec } /// `command` as seen by `instance` (`None` for the app) from `from` (`None`: the key focus of the running pass), with -/// the gate applied outside the board's lock, and the key of the state it read. +/// the gate applied, and the inputs it was made from; `reads` holds what the caller read to find the instance. fn resolve_in( ctx: &Context, command: &CommandRef, instance: Option, reach: Reach<'_>, from: Option<&Vantage>, -) -> (ResolvedCommand, Option) { - let ((mut resolved, key), first_unknown, gate) = with(ctx, |board| { + mut reads: Reads, +) -> (ResolvedCommand, ResolveKey) { + let (resolved, key, first_unknown) = with(ctx, |board| { let first_unknown = board.def(&command.id).is_none() && board.unknown.insert(command.id.clone()); // A command no state named yet has a key too, so a state given later reaches the regions that read it. board.number(&command.id); - let resolved = board.resolve(ctx, command, instance, reach, from.unwrap_or(&board.here)); - // This frame's answer, else the gate to ask. - let gate = board.gate.as_ref().map(|gate| board.gate_answers.get(command.key_text().as_ref()).copied().ok_or_else(|| gate.clone())); - (resolved, first_unknown, gate) + let (mut resolved, state) = board.resolve(ctx, command, instance, reach, from.unwrap_or(&board.here), &mut reads); + let gate = board.gate_answer(command); + if gate.is_some_and(|(_, allowed)| !allowed) { + resolved.enabled = false; + } + let key = ResolveKey { + shared: board.gens.shared, + focus: reads.focus.then_some(board.gens.focus), + state: state.map(|state| (state, board.revisions.get(&state).copied().unwrap_or(0))), + gate, + edits: reads.edits, + vantage: None, + }; + (resolved, key, first_unknown) }); if first_unknown { log::warn!("the command {} is in no registered command set: it is an app command with its id as its label", command.id); } - let allowed = match gate { - None => true, - Some(Ok(answer)) => answer, - Some(Err(gate)) => { - let answer = gate.allows(command); - with(ctx, |board| { - board.gate_answers.insert(command.key(), answer); - }); - answer - } - }; - if !allowed { - resolved.enabled = false; - } (resolved, key) } /// `command` for a surface with no component of its own: against the instance that `fire` would target. -pub(crate) fn resolve_global(ctx: &Context, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_global(ctx: &Context, command: &CommandRef) -> Arc { read(ctx, Reader::Global, command) } /// `command` for a surface with no component of its own that closes before its command runs, from the window under /// the modal layer `layer` (`beneath`). -pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> Arc { read(ctx, Reader::Beneath(layer), command) } @@ -903,7 +1128,7 @@ pub(crate) fn resolve_beneath(ctx: &Context, layer: Id, command: &CommandRef) -> /// group whose button opened it, focused or not), judged from the stop focus returns to once the menus close, which /// gives the edits, the modal facts and the instance when the chain holds none (Cut in a text field's edit menu follows /// the field's selection; an Edit menu row reaches the field that held focus); its activation fires that resolution. -pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> ResolvedCommand { +pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Arc { let reader = match focus::running_menu(ctx) { Some(menu) => Reader::InMenu(menu, chain.clone()), None => Reader::Chain(chain.clone()), @@ -911,79 +1136,142 @@ pub(crate) fn resolve_bound(ctx: &Context, chain: &CommandChain, command: &Comma read(ctx, reader, command) } -/// `command` as `reader` is shown it, noted as its read. -fn read(ctx: &Context, reader: Reader, command: &CommandRef) -> ResolvedCommand { - let (resolved, key) = resolve_as(ctx, &reader, command); - note_read(ctx, key, reader, &resolved); +/// `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 { + let viewport = pass::current_viewport(ctx); + let vantage = vantage_of(ctx, &reader); + let found = with(ctx, |board| board.lookup(ctx, viewport, &reader, command, vantage.as_ref())); + let (resolved, state) = match found { + Lookup::Fresh(resolved, state) => (resolved, state), + found => { + #[cfg(feature = "testing")] + measure::count_resolve(ctx, if matches!(found, Lookup::Stale) { Resolve::Again } else { Resolve::New }); + let _ = found; + let (resolved, key) = resolve_as(ctx, &reader, command, vantage); + let (resolved, state) = (Arc::new(resolved), key.state.map(|(state, _)| state)); + with(ctx, |board| board.keep(viewport, reader, Arc::clone(&resolved), key)); + (resolved, state) + } + }; + note_read(ctx, state); resolved } -/// `command` from the vantage of `reader`, and the key of the state it read. The readers' first resolution and the one -/// `begin` makes again both come from here. -fn resolve_as(ctx: &Context, reader: &Reader, command: &CommandRef) -> (ResolvedCommand, Option) { +/// The vantage a layered reader is judged from: the window under its layer, or where focus goes once its menus close +/// (`None` when no stop is there). `None` for the other readers, which are judged from the board's own. +fn vantage_of(ctx: &Context, reader: &Reader) -> Option> { match reader { - Reader::Global => resolve_from(ctx, command, None), - Reader::Beneath(layer) => { - let from = beneath(ctx, *layer); - resolve_from(ctx, command, Some(&from)) - } - Reader::Chain(chain) => resolve_chain(ctx, command, chain), - Reader::InMenu(menu, chain) => { - let from = out_of_menu(ctx, *menu); - let instance = with(ctx, |board| { - board.innermost(chain, board.scope_of(command)).or_else(|| board.target_of(ctx, command, from.as_ref().unwrap_or(&board.here)).1) - }); - resolve_in(ctx, command, instance, Reach::Chain(chain), from.as_ref()) - } + Reader::Beneath(layer) => Some(Some(beneath(ctx, *layer))), + Reader::InMenu(menu, _) => Some(out_of_menu(ctx, *menu)), + Reader::Global | Reader::Chain(_) => None, } } -/// `command` against the instances of `chain`. -fn resolve_chain(ctx: &Context, command: &CommandRef, chain: &CommandChain) -> (ResolvedCommand, Option) { - let instance = with(ctx, |board| board.innermost(chain, board.scope_of(command)).or_else(|| board.target_of(ctx, command, &board.here).1)); - resolve_in(ctx, command, instance, Reach::Chain(chain), None) +/// `command` from the vantage of `reader` (`vantage`, from `vantage_of`), and the inputs it was made from. The +/// readers' first resolution and the one `begin` makes again both come from here. +fn resolve_as(ctx: &Context, reader: &Reader, command: &CommandRef, vantage: Option>) -> (ResolvedCommand, ResolveKey) { + let from = vantage.as_ref().and_then(Option::as_ref); + let (resolved, mut key) = match reader { + Reader::Global | Reader::Beneath(_) => resolve_from(ctx, command, from), + Reader::Chain(chain) => resolve_chain(ctx, command, chain, None), + Reader::InMenu(_, chain) => resolve_chain(ctx, command, chain, from), + }; + key.vantage = vantage; + (resolved, key) } -fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> (ResolvedCommand, Option) { - let (_, instance) = with(ctx, |board| board.target_of(ctx, command, from.unwrap_or(&board.here))); - resolve_in(ctx, command, instance, Reach::Focus, from) +/// The instance a source with no component of its own delivers `command` to from `from`, noting in `reads` that it +/// read the focus when it picked one. +fn target_read(ctx: &Context, board: &Board, command: &CommandRef, from: &Vantage, reads: &mut Reads) -> (bool, Option) { + let (app, instance) = board.target_of(ctx, command, from); + reads.focus |= !app; + (app, instance) } -/// fx.F23: resolves every command a reader of `viewport` was shown again, from that reader's own vantage under this -/// pass's gate, states, modal facts and instances, and notes an edit of the state key of each whose resolution differs -/// in any shown part (label, chord, enabled, checked, marked, hint), so a settled region that shows it runs; the entry -/// keeps the new resolution. Readers of regions that did not run keep their entries: a settled region is the reader -/// this exists for. It reads no input: a second pass of a frame compares against what the first pass's runs were shown -/// 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. +/// `command` against the instances of `chain`, judged from `from` (`None`: the board's own vantage). +fn resolve_chain(ctx: &Context, command: &CommandRef, chain: &CommandChain, from: Option<&Vantage>) -> (ResolvedCommand, ResolveKey) { + let mut reads = Reads::default(); + let instance = with(ctx, |board| { + board.innermost(chain, board.scope_of(command)).or_else(|| target_read(ctx, board, command, from.unwrap_or(&board.here), &mut reads).1) + }); + resolve_in(ctx, command, instance, Reach::Chain(chain), from, reads) +} + +fn resolve_from(ctx: &Context, command: &CommandRef, from: Option<&Vantage>) -> (ResolvedCommand, ResolveKey) { + let mut reads = Reads::default(); + let (_, instance) = with(ctx, |board| target_read(ctx, board, command, from.unwrap_or(&board.here), &mut reads)); + resolve_in(ctx, command, instance, Reach::Focus, from, reads) +} + +/// `command` resolved once, for a key press or a fire: nothing keeps it. +fn resolve_once(ctx: &Context, command: &CommandRef, instance: Option, reach: Reach<'_>, from: Option<&Vantage>) -> ResolvedCommand { + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::New); + resolve_in(ctx, command, instance, reach, from, Reads::default()).0 +} + +/// fx.F23: resolves again what a reader of `viewport` was shown when an input of it changed since the viewport's last +/// wake, from that reader's own vantage under this pass's gate, states, modal facts and instances, and notes an edit of +/// the state key of each whose resolution differs in any shown part (label, chord, enabled, checked, marked, hint), so a +/// settled region that shows it runs; the entry keeps the new resolution. Readers of regions that did not run keep +/// their entries: a settled region is the reader this exists for. With no input changed and no reader under a layer +/// or in a menu (whose vantage it reads again), it walks nothing. A second pass of a frame compares against what the +/// first pass's runs were shown, 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 table = with(ctx, |board| board.shown.remove(&viewport)).unwrap_or_default(); + let edits = focused_edits(ctx, viewport); + let taken = with(ctx, |board| { + let now = Woke { gens: board.gens, state_seq: board.state_seq, gate: board.gate.as_ref().map(CommandGate::key), edits }; + let shown = board.shown.get(&viewport)?; + let moved = shown.woke.is_none_or(|woke| Woke { edits: if shown.edits { woke.edits } else { edits }, ..woke } != now); + if !moved && !shown.layered { + return None; + } + Some((moved, now, board.shown.remove(&viewport)?)) + }); + let Some((moved, now, mut table)) = taken else { return }; let mut changed = Vec::new(); - 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(|(reader, _)| match reader { - Reader::Beneath(layer) | Reader::InMenu(layer, _) => overlay::is_open(ctx, *layer), - _ => true, - }); - 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, reader, &kept.command); - if resolved != *kept { - *kept = resolved; - changed.push(*key); + // A reader beneath a layer or inside a menu that is no longer shown is gone with it. + table.kept.retain(|reader, _| reader.layer().is_none_or(|layer| overlay::is_open(ctx, layer))); + for (reader, by_number) in &mut table.kept { + // With no input changed, only the layered readers' vantages may have. + if !moved && reader.layer().is_none() { + continue; + } + let vantage = vantage_of(ctx, reader); + for kept in by_number.values_mut().flatten() { + let command = &kept.resolved.command; + let fresh = with(ctx, |board| { + let gate = board.gate_answer(command); + holds(&mut kept.key, board.gens, &board.revisions, gate, || edits, vantage.as_ref()) + }); + if fresh { + continue; } + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::Again); + let (resolved, key) = resolve_as(ctx, reader, command, vantage.clone()); + if resolved != *kept.resolved { + changed.extend(kept.key.state.map(|(state, _)| state)); + changed.extend(key.state.map(|(state, _)| state).filter(|state| Some(*state) != kept.key.state.map(|(kept, _)| kept))); + kept.resolved = Arc::new(resolved); + } + kept.key = key; } } - table.retain(|_, readers| !readers.is_empty()); + table.kept.retain(|_, by_number| !by_number.is_empty()); + table.layered = table.kept.keys().any(|reader| reader.layer().is_some()); + table.edits = table.kept.values().flat_map(HashMap::values).flatten().any(|kept| kept.key.edits.is_some()); + table.woke = Some(now); with(ctx, |board| { - // Reads the gate made while the entries were out of the board. - 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); + // Resolutions read nothing into the table while it is out of the board; keep any that arrived all the same. + if let Some(added) = board.shown.remove(&viewport) { + for (reader, by_number) in added.kept { + table.kept.entry(reader).or_default().extend(by_number); } } - if !table.is_empty() { + if !table.kept.is_empty() { board.shown.insert(viewport, table); } }); @@ -992,8 +1280,40 @@ fn wake_shown(ctx: &Context, viewport: ViewportId) { } } +/// Testing check, every 100th pass of a viewport: every kept resolution of `viewport` equals a full resolution from its +/// reader, the gate asked again. A difference is an input the keys miss. +#[cfg(feature = "testing")] +fn check_kept(ctx: &Context, viewport: ViewportId) { + let Some(table) = with(ctx, |board| { + board.gate_answers.clear(); + board.shown.remove(&viewport) + }) else { + return; + }; + for (reader, by_number) in &table.kept { + if reader.layer().is_some_and(|layer| !overlay::is_open(ctx, layer)) { + continue; + } + let vantage = vantage_of(ctx, reader); + for kept in by_number.values().flatten() { + measure::count_resolve(ctx, Resolve::Checked); + let (fresh, _) = resolve_as(ctx, reader, &kept.resolved.command, vantage.clone()); + assert!( + fresh == *kept.resolved, + "the kept resolution of {} for a {} reader differs from a full resolve: kept {:?}, resolved {fresh:?}", + kept.resolved.command, + reader.kind(), + kept.resolved, + ); + } + } + with(ctx, |board| { + board.shown.insert(viewport, table); + }); +} + /// Step-1 resolution for a context in `chain`; `None` when the command's scope has no instance in the chain. -pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Option { +pub(crate) fn resolve_scoped(ctx: &Context, chain: &CommandChain, command: &CommandRef) -> Option> { let (found, app) = with(ctx, |board| { let scope = board.scope_of(command); (board.innermost(chain, scope).is_some(), board.to_app(scope)) @@ -1023,7 +1343,9 @@ fn queue(ctx: &Context, fired: Fired) { pub(crate) fn fall_through(ctx: &Context, command: craft_behavior::EditCommand) { let Some(command) = EditCommands::of(command) else { return }; let command = CommandRef::from(command); - let target = with(ctx, |board| board.resolve(ctx, &command, None, Reach::Focus, &board.here).0.instance); + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::New); + let target = with(ctx, |board| board.resolve(ctx, &command, None, Reach::Focus, &board.here, &mut Reads::default()).0.instance); let fired = Fired { target, ..Fired::new(command, FireSource::Key, FirePhase::Press, pass::now(ctx)) }; with(ctx, |board| if fired.target.is_some() { board.queue.push(fired) } else { board.out.push(fired) }); repaint::request_of(ctx, ViewportId::ROOT); @@ -1059,7 +1381,7 @@ fn fire_in(ctx: &Context, command: &CommandRef, source: FireSource, from: Option if !app && instance.is_none() { return false; } - let (resolved, _) = resolve_in(ctx, command, instance, Reach::Focus, from); + let resolved = resolve_once(ctx, command, instance, Reach::Focus, from); if !resolved.enabled { return false; } @@ -1098,11 +1420,14 @@ pub(crate) fn publish(ctx: &Context, chain: &CommandChain, command: &CommandRef, let key = (number, Some(instance)); // The pass that publishes is the one that knows the layers around the caller. let in_modal = chain.ids().any(|id| board.is_modal_root(id)); - if in_modal { - board.modal_published.insert(key); + if in_modal && board.modal_published.insert(key) && !board.modal_published_last.contains(&key) { + board.gens.shared += 1; } let changed = !same_state(board.this.get(&key).or_else(|| board.last.get(&key)), Some(&state)); board.this.insert(key, state); + if changed { + board.bump_state(key); + } changed.then_some((number, instance)) }); if let Some((number, instance)) = changed { @@ -1164,7 +1489,7 @@ pub fn bound_around(ctx: &Context, at: Id, around: &CommandChain, S::from_ref(&hit.command)?; Some((hit.command, board.instance_around(at, around, S::SCOPE.name()))) })?; - let (resolved, _) = resolve_in(ctx, &command, instance, Reach::Chain(around), None); + let resolved = resolve_once(ctx, &command, instance, Reach::Chain(around), None); if resolved.enabled { S::from_ref(&command) } else { None } } @@ -1185,7 +1510,7 @@ pub(crate) fn binds_scoped(ctx: &Context, chord: &Chord) -> bool { let (_, instance) = board.target_of(ctx, &command, &board.here); Some((command, instance)) }); - found.is_some_and(|(command, instance)| resolve_in(ctx, &command, instance, Reach::Focus, None).0.enabled) + found.is_some_and(|(command, instance)| resolve_once(ctx, &command, instance, Reach::Focus, None).enabled) } /// Where a shortcut pressed with focus in a menu or on a menu bar matches, and where a hit gives the focus back. The @@ -1248,7 +1573,10 @@ pub(crate) fn begin(ctx: &Context) { let returning = focused.filter(|_| !shortcuts.keys.is_empty()).and_then(|focused| Returning::of(ctx, focused)); let shell = frame::shell_root(ctx, viewport); let taken = with(ctx, |board| { - board.held_open = held_open; + if board.held_open != held_open { + board.held_open = held_open; + board.gens.shared += 1; + } let returned = returning .map(Returning::id) .and_then(|held| [board.before.get(&viewport), board.chains.get(&viewport)].into_iter().flatten().find(|(id, _)| *id == held)) @@ -1261,18 +1589,33 @@ pub(crate) fn begin(ctx: &Context) { (true, Some(root)) => vec![*root], _ => chain, }; - if !chain.is_empty() { + if !chain.is_empty() && board.last_focused != chain { board.last_focused.clone_from(&chain); + board.gens.focus += 1; } // Nothing focused outside a modal: the window's shell root takes the commands, so a window command's key comes // before an app command's. Nothing holds focus there, so the chain last focused stays. let chain = if chain.is_empty() && focused.is_none() { shell.into_iter().collect() } else { chain }; match board.here.focused.iter_mut().find(|(v, _)| *v == viewport) { - Some(entry) => entry.1.clone_from(&chain), - None => board.here.focused.push((viewport, chain.clone())), + Some(entry) if entry.1 == chain => {} + Some(entry) => { + entry.1.clone_from(&chain); + board.gens.focus += 1; + } + None => { + board.here.focused.push((viewport, chain.clone())); + board.gens.focus += 1; + } + } + if board.here.dialog_keys != shortcuts.dialog { + board.here.dialog_keys = shortcuts.dialog; + board.gens.shared += 1; + } + let inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); + if board.here.inside_modal != inside_modal { + board.here.inside_modal = inside_modal; + board.gens.focus += 1; } - board.here.dialog_keys = shortcuts.dialog; - board.here.inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); if shortcuts.keys.is_empty() { return None; } @@ -1288,6 +1631,10 @@ pub(crate) fn begin(ctx: &Context) { }); // With this pass's vantage set, what the readers were shown is resolved again before any of them runs. wake_shown(ctx, viewport); + #[cfg(feature = "testing")] + if pass::pass_nr(ctx, viewport) % 100 == 0 { + check_kept(ctx, viewport); + } let Some((keys, mut matcher)) = taken else { return }; let mut fired = Vec::new(); for shortcut in &shortcuts.keys { @@ -1315,7 +1662,7 @@ pub(crate) fn begin(ctx: &Context) { continue; }; let (app, instance) = with(ctx, |board| board.target_of(ctx, &hit.command, &board.here)); - let (resolved, _) = resolve_in(ctx, &hit.command, instance, Reach::Focus, None); + let resolved = resolve_once(ctx, &hit.command, instance, Reach::Focus, None); if !resolved.enabled { continue; } @@ -1371,6 +1718,13 @@ pub(crate) fn end(ctx: &Context) { with(ctx, |board| { let live = pass::live_viewports(ctx); let alive: Vec = board.instances.iter().map(|i| board.live(ctx, i) && live.contains(&i.viewport)).collect(); + // An instance this pass did not register is dead from its viewport's next pass, and one of a closed viewport + // is gone now, live or not: resolutions see either. + let dies = + board.instances.iter().zip(&alive).any(|(i, alive)| if *alive { i.stamp < pass::pass_nr(ctx, i.viewport) } else { board.live(ctx, i) }); + if dies { + board.gens.shared += 1; + } let mut keep = alive.iter(); board.instances.retain(|_| keep.next().copied().unwrap_or(false)); let instances = &board.instances; @@ -1381,14 +1735,11 @@ pub(crate) fn end(ctx: &Context) { board.before.retain(|viewport, _| live.contains(viewport)); board.here.focused.retain(|(viewport, _)| live.contains(viewport)); 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() + table.kept.retain(|reader, _| match reader { + Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_none_or(&ids), + _ => true, }); - live.contains(viewport) && !table.is_empty() + live.contains(viewport) && !table.kept.is_empty() }); }); } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index a4cf272e8..94ec8f8e1 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -31,6 +31,7 @@ pub use board::{bound_around, take_around}; pub use board::{chord_text_builds, keymap_builds}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; +use crate::contract::{MemoKey, MemoProps, PlainData, Revision, Tracked}; use craft_behavior::CommandFlags; use craft_behavior::edit_history::Step; use craft_keymap::{Chord, Overrides}; @@ -280,17 +281,72 @@ pub struct ResolvedCommand { /// The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an /// operation is pending. A command the gate refuses resolves disabled and does not fire. +/// +/// The gate is a `fn` of its props, as a memoized view's `show` is: the props hold everything the gate reads, so the +/// runtime asks it once per command while the props' key stays the same, and again only when it changes. #[derive(Clone)] -pub struct CommandGate(Arc bool + Send + Sync>); +pub struct CommandGate { + key: u128, + allows: Arc bool + Send + Sync>, +} impl CommandGate { - /// A gate that lets `allows` commands through. - pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self { - CommandGate(Arc::new(allows)) + /// A gate that lets through the commands `allows` accepts under `props`. + pub fn new(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self { + let mut key = MemoKey::new(); + key.feed_hash(&std::any::TypeId::of::

()); + key.write(&(allows as usize).to_le_bytes()); + props.key(&mut key); + CommandGate { key: key.finish(), allows: Arc::new(move |command| allows(&props, command)) } + } + + /// The key of the gate's props and `fn`: equal keys give equal answers. + pub(crate) fn key(&self) -> u128 { + self.key } pub(crate) fn allows(&self, command: &CommandRef) -> bool { - (self.0)(command) + (self.allows)(command) + } +} + +/// The app-scope command states an app holds, in a [`Tracked`] it hands to [`CommandInput::states`] every frame. The +/// runtime reads them again only when the revision moves. +#[derive(Clone, Debug, Default, PartialEq, PlainData)] +pub struct CommandStates { + #[plain_data(assume = "command refs and states are plain values; the list is copied on write")] + states: Arc>, +} + +impl CommandStates { + /// No states. + pub fn new() -> Self { + CommandStates::default() + } + + /// Gives `command` `state`, in place of the state it had. + pub fn set(&mut self, command: impl Into, state: CommandState) { + let command = command.into(); + let states = Arc::make_mut(&mut self.states); + match states.iter_mut().find(|(held, _)| *held == command) { + Some((_, held)) => *held = state, + None => states.push((command, state)), + } + } + + /// Removes the state of `command`, which then resolves with its own label, enabled. + pub fn remove(&mut self, command: &CommandRef) -> Option { + let at = self.states.iter().position(|(held, _)| held == command)?; + Some(Arc::make_mut(&mut self.states).remove(at).1) + } + + /// The state of `command`. + pub fn get(&self, command: &CommandRef) -> Option<&CommandState> { + self.states.iter().find(|(held, _)| held == command).map(|(_, state)| state) + } + + pub(crate) fn iter(&self) -> impl Iterator { + self.states.iter() } } @@ -298,7 +354,7 @@ impl CommandGate { #[derive(Clone, Default)] #[non_exhaustive] pub struct CommandInput { - pub(crate) states: Vec<(CommandRef, CommandState)>, + pub(crate) states: Option<(Revision, CommandStates)>, pub(crate) overrides: Option>, pub(crate) gate: Option, pub(crate) catalog: Option, @@ -310,10 +366,11 @@ impl CommandInput { CommandInput::default() } - /// The state of an app-scope command. + /// The app-scope command states the app holds. The runtime keeps the revision and reads the states again only + /// when it moves. #[must_use] - pub fn state(mut self, command: impl Into, state: CommandState) -> Self { - self.states.push((command.into(), state)); + pub fn states(mut self, states: &Tracked) -> Self { + self.states = Some((states.revision(), (**states).clone())); self } @@ -331,8 +388,8 @@ impl CommandInput { self } - /// The one gate over commands. It answers from what the app knew before the frame: the runtime asks it once per - /// command per frame, whichever components and passes resolve the command. + /// The one gate over commands. The runtime asks it once per command while the gate's props keep their key, whichever + /// components, passes and frames resolve the command. #[must_use] pub fn gate(mut self, gate: CommandGate) -> Self { self.gate = Some(gate); @@ -438,7 +495,7 @@ pub trait Commands: CommandAccess { /// `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above /// the context, and the enabled state of its instance. `None` when the command is scoped and no instance of its /// scope is above the context. - fn resolve_command(&self, command: impl Into) -> Option { + fn resolve_command(&self, command: impl Into) -> Option> { board::resolve_scoped(self.command_ctx(), self.command_chain(), &command.into()) } } @@ -457,7 +514,7 @@ pub fn fire(ctx: &Context, command: impl Into, source: FireSource) - /// `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state /// and hint, against the instance that [`fire`] would deliver it to. A scoped command with no live instance /// resolves disabled. -pub fn resolve(ctx: &Context, command: impl Into) -> ResolvedCommand { +pub fn resolve(ctx: &Context, command: impl Into) -> Arc { board::resolve_global(ctx, &command.into()) } @@ -485,7 +542,7 @@ pub fn holder(ctx: &Context, chord: &Chord) -> Option { /// once the layer closes: for a surface that closes before its command runs (the command palette), whose own layer /// does not block the command. Outside a modal layer it is [`resolve`]. #[doc(hidden)] -pub fn resolve_beneath(ctx: &Context, command: impl Into) -> ResolvedCommand { +pub fn resolve_beneath(ctx: &Context, command: impl Into) -> Arc { match crate::runtime::overlay::modal_drawing(ctx) { Some(layer) => board::resolve_beneath(ctx, layer, &command.into()), None => resolve(ctx, command), diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 71e2cf685..262ada807 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -297,6 +297,31 @@ pub fn chord_texts(ctx: &Context) -> u32 { last_totals(ctx, |log| log.chord_texts, 0) } +/// What a command resolution was for. +#[cfg(feature = "testing")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub enum Resolve { + /// A resolution nothing kept: a reader's first, or one for a key press or a fire. + New, + /// A kept resolution made again because an input of it changed. + Again, + /// A kept resolution compared with a full one by the testing check every 100th pass. + Checked, +} + +/// Counts a command resolution in this pass. +#[cfg(feature = "testing")] +pub(crate) fn count_resolve(ctx: &Context, what: Resolve) { + totals(ctx, |log| log.resolves[what as usize] += 1); +} + +/// The command resolutions of the last pass of kind `what`. +#[cfg(feature = "testing")] +pub fn last_pass_resolves(ctx: &Context, what: Resolve) -> u32 { + last_totals(ctx, |log| log.resolves[what as usize], 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) { @@ -367,6 +392,7 @@ pub(crate) struct PassTotals { key_bytes: usize, text_layouts: u32, chord_texts: u32, + resolves: [u32; 3], asks: Vec<(&'static str, u32)>, } diff --git a/crates/ui-contract/src/testing/fixture.rs b/crates/ui-contract/src/testing/fixture.rs index aff8228e8..5065b8d83 100644 --- a/crates/ui-contract/src/testing/fixture.rs +++ b/crates/ui-contract/src/testing/fixture.rs @@ -2,8 +2,9 @@ use super::Frames; use super::story::{Story, StoryData, StoryOutput}; +use crate::contract::Tracked; use crate::runtime::access::Role; -use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState}; +use crate::runtime::commands::{CommandGate, CommandInput, CommandRef, CommandState, CommandStates}; use crate::runtime::egui::access::{AccessTree, NodeKey}; use crate::runtime::egui::fixture::{self, AccessActionKind}; use crate::runtime::egui::injected; @@ -114,6 +115,8 @@ pub struct Fixture { show: Box, root: RootEnv, commands: CommandInput, + /// The app-scope command states, held as an app holds them. + states: Tracked, room: Vec2, tree: AccessTree, shown: Rect, @@ -153,6 +156,7 @@ impl Fixture { show: Box::new(show), root: RootEnv::default(), commands: CommandInput::new(), + states: Tracked::default(), room: Vec2::new(400.0, 300.0), tree: AccessTree::none(), shown: Rect::NOTHING, @@ -203,7 +207,8 @@ impl Fixture { fixture.data = data; fixture.outputs = outputs; fixture.root_id = root_id; - fixture.commands = Story::command_input([story]); + fixture.states = Tracked::new(Story::command_states([story])); + fixture.commands = CommandInput::new().states(&fixture.states); fixture.frames.commands(fixture.commands.clone()); fixture } @@ -230,9 +235,8 @@ impl Fixture { /// Gives app-scope `command` this state in every following pass, as an app's `FrameInput.commands` does; a later /// call for the same command replaces the earlier one. pub fn command_state(&mut self, command: impl Into, state: CommandState) -> &mut Self { - let command = command.into(); - self.commands.states.retain(|(held, _)| *held != command); - self.commands.states.push((command, state)); + self.states.set(command, state); + self.commands = self.commands.clone().states(&self.states); self.frames.commands(self.commands.clone()); self } diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index d58471713..a93c9c42b 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -2,7 +2,7 @@ use super::Fixture; use crate::contract::{CollectionEvent, Inner, Outcome, TooltipSpec}; -use crate::runtime::commands::CommandInput; +use crate::runtime::commands::CommandStates; use craft_behavior::{EditEvent, EditEvents, PartKey, PartRef, Value}; use egui::{Id, Response, Ui, Vec2}; use std::any::{Any, TypeId}; @@ -102,9 +102,9 @@ pub struct Story { pub drive: Drive, /// The reason a disabled control shows (`disabled_text` of its tooltip), when the story gives its control one. pub disabled_text: Option<&'static str>, - /// Adds this story's app-scope command states to the frame's command input; runners fold the shown stories' - /// functions over `CommandInput::new()` before the first frame. - pub commands: Option CommandInput>, + /// Sets this story's app-scope command states; runners apply the shown stories' functions in order to one + /// `CommandStates` before the first frame and hold it as the app's. + pub commands: Option, /// The caption a viewer shows over the story; `None` for the title made of its name (`contract::story_title`). pub title: Option<&'static str>, /// The group a viewer shows the story in, with the other stories of the type that name it, as the cases of one @@ -118,16 +118,20 @@ impl Story { Story { name, covers: &[], show, drive: Drive::Auto, disabled_text: None, commands: None, title: None, group: None } } - /// Sets the function that adds the story's command states to the frame's command input. - pub const fn commands(mut self, add: fn(CommandInput) -> CommandInput) -> Self { + /// Sets the function that sets the story's app-scope command states. + pub const fn commands(mut self, add: fn(&mut CommandStates)) -> Self { self.commands = Some(add); self } - /// The command input of `stories` shown together: each story's command function applied in order over an empty - /// input, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame. - pub fn command_input<'a>(stories: impl IntoIterator) -> CommandInput { - stories.into_iter().filter_map(|story| story.commands).fold(CommandInput::new(), |input, add| add(input)) + /// The command states of `stories` shown together: each story's command function applied in order to empty + /// states, so a later story's state for a command replaces an earlier one's. Runners call this before the first frame. + pub fn command_states<'a>(stories: impl IntoIterator) -> CommandStates { + let mut states = CommandStates::new(); + for add in stories.into_iter().filter_map(|story| story.commands) { + add(&mut states); + } + states } /// The caption a viewer shows over the story. diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index 78eea00a9..16ae912b5 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -94,9 +94,9 @@ enum Shown { Apply, } -/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new closure. +/// A gate that refuses `Shown::Apply` when `refuses`, else lets every command through. Each call makes a new gate. fn gate(refuses: bool) -> CommandInput { - CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| !refuses || Shown::from_ref(command).is_none())) + CommandInput::new().gate(CommandGate::new(refuses, |refuses: &bool, command: &CommandRef| !*refuses || Shown::from_ref(command).is_none())) } /// A modal layer with an empty body. diff --git a/crates/ui-gallery/src/chrome/shell.rs b/crates/ui-gallery/src/chrome/shell.rs index 1be5fbced..8fc707763 100644 --- a/crates/ui-gallery/src/chrome/shell.rs +++ b/crates/ui-gallery/src/chrome/shell.rs @@ -9,10 +9,11 @@ use crate::viewer::{Browser, Catalog, GalleryCommands, GallerySettings, PanelId, use craft_behavior::dock::{PanelState, Workspace as Dock}; use craft_theme::AppSizes; use craft_theme_editor::{ThemeSubject, parse_sizes}; -use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _}; +use craft_ui::contract::{Bind, BodyCx, CommandSet as _, ShowContainer as _, Tracked}; use craft_ui::docking::DockConfig; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; +use craft_ui::runtime::commands::{CommandInput, CommandStates}; use craft_ui::runtime::drag::OsFile; use craft_ui::runtime::env::WindowKey; use craft_ui::runtime::frame::{FrameInput, FrameOutput}; @@ -34,6 +35,9 @@ pub struct Gallery { noted: HashSet, /// A command changed the viewer since the settings were last compared. command_ran: bool, + /// The app-scope command states of the front component's stories, and that component: rebuilt only when another + /// component comes to the front, so an idle frame keeps one revision. + command_states: (Option<&'static str>, Tracked), } impl Gallery { @@ -45,7 +49,7 @@ impl Gallery { /// The viewer of `catalog` over `persisted`. pub fn new(catalog: Catalog, persisted: Persisted) -> Self { let viewer = Viewer::new(catalog, persisted.get()); - Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false } + Gallery { viewer, persisted, drop_note: None, noted: HashSet::new(), command_ran: false, command_states: (None, Tracked::default()) } } /// Shows what the settings and a dropped file have to say, once each, as toasts. @@ -143,10 +147,14 @@ impl ShellApp for Gallery { // App-scope command states are one input per frame, so only the stories of the component shown reach it; the // Overview, the Theme dock and a frame with no such tab give none. let browser = &self.viewer.browser; - let stories = front_component(&self.viewer) - .into_iter() - .flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story)); - FrameInput::new(self.viewer.env.clone()).commands(craft_ui::testing::Story::command_input(stories)) + let front = front_component(&self.viewer); + if front != self.command_states.0 { + let stories = front + .into_iter() + .flat_map(|type_name| browser.catalog.stories_of(type_name).iter().map(|&at| &browser.catalog.entries[at].registration.story)); + self.command_states = (front, Tracked::new(craft_ui::testing::Story::command_states(stories))); + } + FrameInput::new(self.viewer.env.clone()).commands(CommandInput::new().states(&self.command_states.1)) } fn output(&mut self, output: FrameOutput) { diff --git a/crates/ui-gallery/src/mock/editor.rs b/crates/ui-gallery/src/mock/editor.rs index 2cc3757c7..dfa079698 100644 --- a/crates/ui-gallery/src/mock/editor.rs +++ b/crates/ui-gallery/src/mock/editor.rs @@ -212,7 +212,7 @@ fn pick(ui: &Ui, state: &mut MockState, tool: Tool, step: PickStep) { /// Makes `tool` the current tool and says so in the status bar. fn select(ui: &Ui, state: &mut MockState, tool: Tool) { state.tool = tool; - let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label; + let name = commands::resolve(ui.ctx(), CommandRef::from(tool)).label.clone(); let text = Env::of(ui).words::().tool_status.fill(&[("tool", &*name)]); state.status = Some(StatusMessage::new(text)); } diff --git a/crates/ui-macros/src/lib.rs b/crates/ui-macros/src/lib.rs index 7db0607d2..761eb0d93 100644 --- a/crates/ui-macros/src/lib.rs +++ b/crates/ui-macros/src/lib.rs @@ -223,7 +223,7 @@ impl Parse for StoryArgs { /// reason to show while disabled, which the story takes from `StoryData::tooltip`. `title = ".."` is the caption a /// viewer shows over the story. `group = ".."` puts the story in a named group with the type's other stories that /// name it, in declaration order; a viewer shows a group together, each story under its caption. -/// `commands = ` names a `fn(CommandInput) -> CommandInput` that sets the command states the story runs under. +/// `commands = ` names a `fn(&mut CommandStates)` that sets the app-scope command states the story runs under. /// The type's registration and the story meet by the type's registered name. #[proc_macro_attribute] pub fn story(attr: TokenStream, item: TokenStream) -> TokenStream { diff --git a/crates/ui-panels/src/rails/drawer.rs b/crates/ui-panels/src/rails/drawer.rs index 833ba59a8..bef693ce6 100644 --- a/crates/ui-panels/src/rails/drawer.rs +++ b/crates/ui-panels/src/rails/drawer.rs @@ -167,11 +167,11 @@ enum DrawerKey { /// headings. struct Rows<'a> { keys: Vec, - resolved: &'a [Vec], + resolved: &'a [Vec>], } impl<'a> Rows<'a> { - fn new(resolved: &'a [Vec]) -> Self { + fn new(resolved: &'a [Vec>]) -> Self { let mut keys = Vec::new(); for (group, tools) in resolved.iter().enumerate().filter(|(_, tools)| !tools.is_empty()) { keys.push(DrawerKey::Group(group)); @@ -221,7 +221,7 @@ impl ToolbarDrawer<'_, T> { let words = env.words::(); let os = os_of(ui.ctx()); let ctx = ui.ctx().clone(); - let resolved: Vec> = + let resolved: Vec>> = groups.iter().map(|group| group.tools.iter().map(|tool| commands::resolve(&ctx, tool.command.clone())).collect()).collect(); let mut edits: Vec> = dropped.and_then(|dropped| drop_edit(dropped.drag, dropped.at, groups, toolbar)).into_iter().collect(); let mut select: Option = None; diff --git a/crates/ui-panels/src/rails/flyout.rs b/crates/ui-panels/src/rails/flyout.rs index dda5a9c5f..9bc9aab91 100644 --- a/crates/ui-panels/src/rails/flyout.rs +++ b/crates/ui-panels/src/rails/flyout.rs @@ -90,9 +90,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, } @@ -185,7 +185,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> { /// The command the face stands for: the click command when there is one, else the shown tool's. fn lead<'l>(&self, laid: &'l Laid) -> Option<&'l ResolvedCommand> { - if self.click.is_some() { laid.click.as_ref() } else { laid.resolved.get(laid.shown).and_then(Option::as_ref) } + if self.click.is_some() { laid.click.as_deref() } else { laid.resolved.get(laid.shown).and_then(Option::as_deref) } } } diff --git a/crates/ui-patterns/src/patterns/panels/palette/stories.rs b/crates/ui-patterns/src/patterns/panels/palette/stories.rs index da81dbb08..c15197308 100644 --- a/crates/ui-patterns/src/patterns/panels/palette/stories.rs +++ b/crates/ui-patterns/src/patterns/panels/palette/stories.rs @@ -3,7 +3,7 @@ use super::CommandPalette; use crate::contract::Bind; use crate::menu::search::HelpEntry; -use crate::runtime::commands::{CommandInput, CommandRef, CommandState, EditCommands}; +use crate::runtime::commands::{CommandRef, CommandState, CommandStates, EditCommands}; use crate::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use std::sync::LazyLock; @@ -69,8 +69,8 @@ fn palette(ui: &mut Ui, data: &mut StoryData, recents: Vec) -> Story } /// The command states the stories run under: Redo is disabled, as the entries list it. -fn commands(input: CommandInput) -> CommandInput { - input.state(EditCommands::Redo, CommandState::new().enabled(false)) +fn commands(states: &mut CommandStates) { + states.set(EditCommands::Redo, CommandState::new().enabled(false)); } #[story(CommandPalette<'static>, covers = [], drive = Drive::Never, title = "PhotoCraft", commands = commands)] diff --git a/crates/ui-shell/tests/it/commands/app_catalog.rs b/crates/ui-shell/tests/it/commands/app_catalog.rs index ef6ecaff4..d8e3a6b03 100644 --- a/crates/ui-shell/tests/it/commands/app_catalog.rs +++ b/crates/ui-shell/tests/it/commands/app_catalog.rs @@ -2,9 +2,10 @@ //! rules every app command follows, and a frame builds a keymap only for a catalog generation it has not built. // The catalog is given through `Frames::commands`, which keeps it for every later frame. -use craft_ui::contract::{Bind, Props as _, Show as _}; +use craft_ui::contract::{Bind, Props as _, Show as _, Tracked}; use craft_ui::runtime::commands::{ - AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, EditCommands, FirePhase, Scope, keymap_builds, + AppCatalog, Binding, CommandDef, CommandInput, CommandKind, CommandRef, CommandState, CommandStates, EditCommands, FirePhase, Scope, + keymap_builds, }; use craft_ui::runtime::env::WindowKey; use craft_ui::runtime::frame::take_output; @@ -198,11 +199,9 @@ fn a_press_without_a_physical_key_fires_its_command_once() { fn an_app_catalogs_alternate_key_for_a_registry_command_runs_it() { let cut = CommandRef::from(EditCommands::Cut); let alternate = CommandDef::new(cut.clone(), "Cut", Scope::app()).with_default(Binding::parse("F2").expect("the trial's chord parses")); - let input = || { - CommandInput::new() - .catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid")) - .state(cut.clone(), CommandState::new()) - }; + let mut states = Tracked::new(CommandStates::new()); + states.set(cut.clone(), CommandState::new()); + let input = || CommandInput::new().catalog(AppCatalog::new(vec![alternate.clone()], 1).expect("the trial's catalog is valid")).states(&states); let mut show = |ui: &mut Ui| { AppShell::new(WindowKey::main()).show(ui, &mut ()); }; diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index d4bb19304..2b5beb33a 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -1,8 +1,6 @@ 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, chord_text_builds, fire, resolve, -}; +use craft_ui::runtime::commands::{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; @@ -82,58 +80,6 @@ fn an_enclosing_scopes_shortcut_beats_the_applications() { assert_eq!((closed.get(), ids(&take_output(&frames.ctx).fired)), (1, vec!["trial.jump"]), "outside the dock the application's command fires"); } -/// 1.8 and 7.2: the gate is app code, so it runs with no runtime lock held and may use the board. -#[trial] -fn the_gate_may_resolve_commands() { - let mut frames = Frames::new(); - let ctx = frames.ctx.clone(); - let inside = std::sync::atomic::AtomicBool::new(false); - frames.commands(CommandInput::new().gate(CommandGate::new(move |_: &CommandRef| { - // The nested `resolve` runs the gate again, which stops here. - inside.swap(true, std::sync::atomic::Ordering::SeqCst) || { - let enabled = resolve(&ctx, AppCommand::Go).enabled; - inside.store(false, std::sync::atomic::Ordering::SeqCst); - enabled - } - }))); - let mut show = |ui: &mut Ui| { - Tap::new().id_salt("go").command(AppCommand::Save).show(ui); - }; - frames.idle(2, &mut show); - frames.frame(vec![key_press(Key::K, Modifiers::COMMAND)], &mut show); - assert_eq!(ids(&take_output(&frames.ctx).fired), ["trial.save"]); -} - -/// The gate answers from what the app knew before the frame: a frame asks it once per command, however many components -/// show the command and however many passes and readers resolve it. -#[trial] -fn a_frame_asks_the_gate_once_per_command() { - use std::sync::{Arc, Mutex}; - let asked = Arc::new(Mutex::new(Vec::::new())); - let log = Arc::clone(&asked); - let mut frames = Frames::new(); - frames.commands(CommandInput::new().gate(CommandGate::new(move |command: &CommandRef| { - log.lock().expect("the gate's log").push(command.key()); - true - }))); - let mut show = |ui: &mut Ui| { - for salt in ["a", "b", "c"] { - Tap::new().id_salt(salt).command(AppCommand::Save).show(ui); - } - }; - frames.idle(2, &mut show); - for at in [5.0, 6.0, 7.0] { - asked.lock().expect("the gate's log").clear(); - frames.frame(vec![moved(Pos2::new(at, at))], &mut show); - let asked = asked.lock().expect("the gate's log").clone(); - let mut once = asked.clone(); - once.sort(); - once.dedup(); - assert!(once.contains(&"trial.save".to_owned()), "the frame resolves the taps' command: {asked:?}"); - assert_eq!(asked.len(), once.len(), "a frame asked the gate for a command twice: {asked:?}"); - } -} - /// 11.3: a scoped entry waits for its instance and is dropped when the instance stops being live. #[trial] fn an_untaken_scoped_entry_is_dropped_with_its_instance() { diff --git a/crates/ui-shell/tests/it/commands/mod.rs b/crates/ui-shell/tests/it/commands/mod.rs index 3c8a37d28..0df0ca31e 100644 --- a/crates/ui-shell/tests/it/commands/mod.rs +++ b/crates/ui-shell/tests/it/commands/mod.rs @@ -4,3 +4,4 @@ mod app_catalog; mod app_scope; mod board; mod kit; +mod resolve; diff --git a/crates/ui-shell/tests/it/commands/resolve.rs b/crates/ui-shell/tests/it/commands/resolve.rs new file mode 100644 index 000000000..de6006fc0 --- /dev/null +++ b/crates/ui-shell/tests/it/commands/resolve.rs @@ -0,0 +1,214 @@ +//! Command resolution runs only when an input of it changed: count trials over fifty shown commands. + +use super::kit::{AppCommand, Pane, PaneCommand, Tap}; +use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Tracked}; +use craft_ui::runtime::commands::{ + AppCatalog, Binding, CommandDef, CommandGate, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Commands as _, Scope, +}; +use craft_ui::runtime::focus::{FocusTarget, request}; +use craft_ui::runtime::measure::{Resolve, last_pass_resolves}; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::{Frames, trial}; +use egui::{Id, Pos2, Ui}; +use std::cell::{Cell, RefCell}; + +/// The panes: each is an instance of the pane scope, so each is its own reader of the commands its taps show. +const PANES: [&str; 5] = ["a", "b", "c", "d", "e"]; + +/// The commands the taps of a pane show, each by two taps. +fn shown(at: usize) -> CommandRef { + match at % 5 { + 0 => AppCommand::Save.into(), + 1 => AppCommand::Go.into(), + 2 => AppCommand::Play.into(), + 3 => AppCommand::Jump.into(), + _ => PaneCommand::ZoomIn.into(), + } +} + +/// Readers kept: one per pane and command. +const KEPT: u32 = 25; +/// Readers of Save: one per pane. +const SAVE_READERS: u32 = 5; +/// Distinct commands shown. +const COMMANDS: u32 = 5; + +/// Fifty taps in five panes; pane `a` publishes Zoom In enabled as `zoom` says. `ids` gets each tap's id. +struct Scene { + zoom: Cell, + ids: RefCell>, +} + +impl Scene { + fn new() -> Self { + Scene { zoom: Cell::new(true), ids: RefCell::new(Vec::new()) } + } + + fn show(&self, ui: &mut Ui) { + self.ids.borrow_mut().clear(); + for (pane, salt) in PANES.iter().enumerate() { + Pane::new().id_salt(*salt).show(ui, |ui, cx| { + if pane == 0 { + cx.publish(PaneCommand::ZoomIn, CommandState::new().enabled(self.zoom.get())); + } + for at in 0..10 { + let id = Tap::new().id_salt(at).command(shown(at)).show(ui).id; + self.ids.borrow_mut().push(id); + } + }); + } + } +} + +fn counts(ctx: &egui::Context) -> (u32, u32) { + (last_pass_resolves(ctx, Resolve::New), last_pass_resolves(ctx, Resolve::Again)) +} + +/// One frame of `scene`, and its new and repeated resolutions summed over every pass of the frame: each pass after +/// the first reads the one before it as it starts, and the last is read after the frame. +fn frame(frames: &mut Frames, scene: &Scene) -> (u32, u32) { + let ctx = frames.ctx.clone(); + let (mut new, mut again, mut pass) = (0, 0, 0); + frames.frame(vec![], |ui| { + if pass > 0 { + let (n, a) = counts(&ctx); + (new, again) = (new + n, again + a); + } + pass += 1; + scene.show(ui); + }); + let (n, a) = counts(&ctx); + (new + n, again + a) +} + +thread_local! { + static ASKS: Cell = const { Cell::new(0) }; +} + +/// The gate: refuses Save while `refuses`; counts its asks. +fn refuse_save(refuses: &bool, command: &CommandRef) -> bool { + ASKS.with(|asks| asks.set(asks.get() + 1)); + !(*refuses && AppCommand::from_ref(command) == Some(AppCommand::Save)) +} + +fn gated(states: &Tracked, refuses: bool) -> CommandInput { + CommandInput::new().states(states).gate(CommandGate::new(refuses, refuse_save)) +} + +/// An idle frame with fifty shown commands resolves nothing, and neither does a pointer move over none of them. +#[trial] +fn an_idle_frame_resolves_no_command() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + assert_eq!(scene.ids.borrow().len(), 50, "fifty commands are shown"); + assert_eq!(frames.frame(vec![], |ui| scene.show(ui)), 1, "an idle frame takes one pass"); + assert_eq!(counts(&frames.ctx), (0, 0), "an idle frame resolves nothing"); + assert_eq!(frames.frame(vec![moved(Pos2::new(900.0, 900.0))], |ui| scene.show(ui)), 1, "so does a pointer move"); + assert_eq!(counts(&frames.ctx), (0, 0), "a pointer move away from the taps resolves nothing"); +} + +/// Editing one app-scope state resolves again only that command's readers, once. +#[trial] +fn one_state_change_resolves_only_its_readers() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let mut states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + states.set(AppCommand::Save, CommandState::new().enabled(false)); + frames.commands(gated(&states, false)); + assert_eq!(frame(&mut frames, &scene), (0, SAVE_READERS), "only Save's readers resolve again"); + assert_eq!(frame(&mut frames, &scene), (0, 0), "the next frame resolves nothing"); +} + +/// An instance publishing a new state resolves again only the readers of that instance's state. +#[trial] +fn a_published_state_change_resolves_only_its_readers() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + scene.zoom.set(false); + assert_eq!(frame(&mut frames, &scene), (0, 1), "only pane a's Zoom In reader resolves again"); + assert_eq!(frame(&mut frames, &scene), (0, 0), "publishing the same state again resolves nothing"); +} + +/// A change of the gate's props asks the gate once per shown command and resolves again only the readers whose answer +/// changed; a new gate with the same props asks nothing. +#[trial] +fn a_gate_props_change_resolves_only_the_readers_whose_answer_changed() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + ASKS.with(|asks| asks.set(0)); + frames.commands(gated(&states, true)); + assert_eq!(frame(&mut frames, &scene), (0, SAVE_READERS), "only Save's readers, which the gate now refuses, resolve again"); + assert_eq!(ASKS.with(Cell::get), COMMANDS, "the gate is asked once per shown command"); + ASKS.with(|asks| asks.set(0)); + frames.commands(gated(&states, true)); + assert_eq!(frame(&mut frames, &scene), (0, 0), "a gate with the same props resolves nothing"); + assert_eq!(ASKS.with(Cell::get), 0, "and is not asked"); +} + +/// Moving the focus between taps resolves none of them: each finds its command's instance in its own chain, or the +/// command is the app's, so none reads the focus. +#[trial] +fn a_focus_move_resolves_no_reader_that_does_not_read_the_focus() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + frames.idle(3, |ui| scene.show(ui)); + for at in [0, 17, 42] { + let id = scene.ids.borrow()[at]; + request(&frames.ctx, FocusTarget::Id(id)); + for _ in 0..2 { + assert_eq!(frame(&mut frames, &scene), (0, 0), "focusing tap {at} resolves nothing"); + } + } +} + +/// The testing check every 100th pass compares every kept resolution with a full one, over state, gate, keymap, +/// publish and focus changes; a kept resolution that missed an input fails it. +#[trial] +fn the_hundredth_pass_check_finds_every_kept_resolution_current() { + let scene = Scene::new(); + let mut frames = Frames::new(); + let mut states = Tracked::new(CommandStates::new()); + let mut refuses = false; + // A new catalog generation rebuilds the keymap. + let mut generation = 1; + let input = |states: &Tracked, refuses: bool, generation: u64| { + let extra = CommandDef::new(CommandRef::new("trial.extra"), "Extra", Scope::app()) + .with_default(Binding::parse(if generation % 2 == 0 { "F7" } else { "F6" }).expect("the trial's chord parses")); + gated(states, refuses).catalog(AppCatalog::new(vec![extra], generation).expect("the trial's catalog is valid")) + }; + frames.commands(input(&states, refuses, generation)); + let mut checked = Vec::new(); + for frame in 0..250 { + match frame % 50 { + 10 => states.set(AppCommand::Go, CommandState::new().checked(frame % 100 == 10)), + 20 => refuses = !refuses, + 30 => generation += 1, + 40 => scene.zoom.set(!scene.zoom.get()), + 45 => { + let id = scene.ids.borrow()[frame % 50]; + request(&frames.ctx, FocusTarget::Id(id)); + } + _ => {} + } + frames.commands(input(&states, refuses, generation)); + frames.frame(vec![], |ui| scene.show(ui)); + let compared = last_pass_resolves(&frames.ctx, Resolve::Checked); + if compared > 0 { + checked.push(compared); + } + } + assert_eq!(checked, [KEPT, KEPT], "two checks ran, each over every kept resolution"); +} diff --git a/crates/ui-widgets/src/bars/items.rs b/crates/ui-widgets/src/bars/items.rs index 471a841f2..97163b91e 100644 --- a/crates/ui-widgets/src/bars/items.rs +++ b/crates/ui-widgets/src/bars/items.rs @@ -108,7 +108,7 @@ pub struct BarItemsStyle { #[derive(Clone)] struct Present { item: BarItem, - resolved: ResolvedCommand, + resolved: std::sync::Arc, } /// Where the parts of a strip sit this pass. diff --git a/crates/ui-widgets/src/notices/notice.rs b/crates/ui-widgets/src/notices/notice.rs index 0cfb90755..9c3bdce04 100644 --- a/crates/ui-widgets/src/notices/notice.rs +++ b/crates/ui-widgets/src/notices/notice.rs @@ -343,7 +343,7 @@ impl<'a> Notice<'a> { self.actions .iter() .map(|action| match &action.command { - Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label)), + Some(command) => cx.resolve_command(command.clone()).map_or(Label::Empty, |resolved| Label::from(resolved.label.clone())), None => action.label.clone(), }) .collect() diff --git a/crates/ui-widgets/src/table/view.rs b/crates/ui-widgets/src/table/view.rs index 697e9edaf..6f11bd7e0 100644 --- a/crates/ui-widgets/src/table/view.rs +++ b/crates/ui-widgets/src/table/view.rs @@ -161,7 +161,7 @@ impl Component for Table<'_, K> { Divider::horizontal().show(ui); } for (command, enabled) in &commands { - let label = crate::runtime::commands::resolve(&ctx, *command).label; + let label = crate::runtime::commands::resolve(&ctx, *command).label.clone(); if MenuItem::new(label.to_string()).enabled(*enabled).show(ui).ran { picks.push(ColumnRequest::Command(*command)); } diff --git a/crates/ui-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs index 317b8d902..7774f7a8c 100644 --- a/crates/ui-widgets/tests/it/body/settle.rs +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -6,10 +6,10 @@ use crate::values::kit::{AT, INITIAL, Scrub, Seen}; use craft_theme::{Contrast, Mode, Size}; use craft_ui::buttons::Button; use craft_ui::choice::{Radio, RadioGroup}; -use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, CommandSet, Lazy, Props as _, Show as _, ShowContainer as _, Sizing, Tracked}; use craft_ui::display::Spinner; use craft_ui::layout_components::Stack; -use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, Commands as _}; +use craft_ui::runtime::commands::{CommandInput, CommandScope, CommandState, CommandStates, Commands as _}; use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::layout::in_region; use craft_ui::testing::pointer::{moved, press, release}; @@ -381,7 +381,11 @@ fn an_app_command_state_runs_the_settled_child_that_shows_it() { let mut frames = Frames::new(); scene.settle(&mut frames); assert!(!scene.disabled(&mut frames, 0), "Shown starts enabled"); - let disable = |enabled: bool| CommandInput::new().state(Shown::Visible, CommandState::new().enabled(enabled)); + let mut states = Tracked::new(CommandStates::new()); + let mut disable = |enabled: bool| { + states.set(Shown::Visible, CommandState::new().enabled(enabled)); + CommandInput::new().states(&states) + }; frames.commands(disable(false)); let (_, [reader, beside]) = scene.frame(&mut frames); assert!(reader > 0 && beside == 0, "only the child that shows Shown runs: {reader}, {beside}"); @@ -425,7 +429,9 @@ fn a_command_read_in_a_measured_body_settles_and_runs_when_its_state_changes() { let mut frames = Frames::new(); scene.settle(&mut frames); assert_eq!(scene.frame(&mut frames).1, [0, 0], "the child holding the measured body settles"); - frames.commands(CommandInput::new().state(Shown::Measured, CommandState::new().enabled(false))); + let mut states = Tracked::new(CommandStates::new()); + states.set(Shown::Measured, CommandState::new().enabled(false)); + frames.commands(CommandInput::new().states(&states)); let (_, [reader, beside]) = scene.frame(&mut frames); assert!(reader > 0 && beside == 0, "only the child that shows Measured runs: {reader}, {beside}"); assert!(scene.disabled(&mut frames, 3), "it shows Measured disabled in the frame the app disables it"); diff --git a/docs/contract-api.md b/docs/contract-api.md index 5dab0dbaa..b69e2aac7 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2134,7 +2134,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `craft_ui::contract::MeasureCx`: `pub struct MeasureCx<'a, C: Component> { pub env: EnvView<'a>, pub style: &'a C::Style, pub resolved: &'a Resolved<'a>, pub proposal: Proposal, pub room: Option, pub ui: &'a Ui, pub tokens: &'a UiTokens, pub id: Id }`. What `measure` reads: step 5's view of the environment, the style, the resolved props and the shown value. - `pub fn value(&self) -> Option<&'a ValueOf>`. The shown value; it has the stage's lifetime, so a borrow of `cx` is not held. - `pub fn command(&self) -> Option<&ResolvedCommand>`. The bound command as step 1 resolved it, with the scoped bindings of the scopes above the component. - - `pub fn resolve_command(&self, command: impl Into) -> Option`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above + - `pub fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this component shows it: the label, icon and chord with the scoped bindings of the scopes above - `pub fn column_room(&self) -> Option`. The width a component whose height follows its width (wrapped text, a square plot) sizes at: the room the - `pub fn picture_width(&self, least: f32, most: f32) -> f32`. The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up - `pub fn label(&self) -> Label`. The label as given. @@ -3107,10 +3107,12 @@ Per-pass and per-frame services and the one egui adapter. The command board: the registry and typed sets, per-frame state, the queue, firing and the gate (spec 11). - `craft_ui::runtime::commands::CommandGate`: `pub struct CommandGate`. The app's one gate over commands: a dialog is open, a workspace is not ready, a recorder has the keys or an - - `pub fn new(allows: impl Fn(&CommandRef) -> bool + Send + Sync + 'static) -> Self`. A gate that lets `allows` commands through. + - `pub fn new(props: P, allows: fn(&P, &CommandRef) -> bool) -> Self`. A gate that lets through the commands `allows` accepts under `props`; the runtime asks it once per command while the props' key stays the same. +- `craft_ui::runtime::commands::CommandStates`: `pub struct CommandStates`. The app-scope command states an app holds, in a `Tracked` it hands to `CommandInput::states`. + - `pub fn new() -> Self`, `pub fn set(&mut self, command: impl Into, state: CommandState)`, `pub fn remove(&mut self, command: &CommandRef) -> Option`, `pub fn get(&self, command: &CommandRef) -> Option<&CommandState>`. - `craft_ui::runtime::commands::CommandInput`: `pub struct CommandInput`. App-scope command state for this frame, set from app state before the pass. - `pub fn new() -> Self`. No state, no overrides and no gate. - - `pub fn state(mut self, command: impl Into, state: CommandState) -> Self`. The state of an app-scope command. + - `pub fn states(mut self, states: &Tracked) -> Self`. The app-scope command states the app holds; the runtime reads them again only when the revision moves. - `pub fn overrides(mut self, overrides: Arc) -> Self`. The user's binding overrides; the keymap is rebuilt when the `Arc` changes. - `pub fn gate(mut self, gate: CommandGate) -> Self`. The one gate over commands. - `craft_ui::runtime::commands::CommandSet`: `pub trait CommandSet: Copy + Send + Sync + 'static`. A typed set of commands, written by `#[derive(CommandSet)]`. @@ -3133,13 +3135,13 @@ The command board: the registry and typed sets, per-frame state, the queue, firi - `fn publish(&mut self, command: impl Into, state: CommandState)`. This frame's state of a scoped command, for this instance. Publishing an app-scope command here is a - `fn take_command(&mut self) -> Option<(S, Fired)>`. The next command of set `S` routed to this instance this pass; each is taken once, so a discard pass does - `fn take_step(&mut self, can_undo: bool, can_redo: bool) -> Option`. Declares Undo and Redo on the innermost instance around this context, enabled as `can_undo` and `can_redo` - - `fn resolve_command(&self, command: impl Into) -> Option`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above + - `fn resolve_command(&self, command: impl Into) -> Option>`. `command` as this context shows it: the label, icon and chord with the scoped bindings of the scopes above - `craft_ui::runtime::commands::FirePhase`: `pub enum FirePhase { Press, Repeat, Release }`. The phase of the key press that fired a command. - `craft_ui::runtime::commands::FireSource`: `pub enum FireSource { Key, Menu, Palette, Pointer, Automation, Access }`. Where a fired command came from. - `craft_ui::runtime::commands::Fired`: `pub struct Fired { pub command: CommandRef, pub target: Option, pub source: FireSource, pub phase: FirePhase, pub cycle: bool, pub alt_variant: bool }`. A command a surface or a key fired, as the instance or the app takes it. - `craft_ui::runtime::commands::ResolvedCommand`: `pub struct ResolvedCommand { pub label: Arc, pub icon: Option>, pub chord: Option, pub enabled: bool, pub checked: Option, pub marked: bool, pub hint: Option>, pub kind: CommandKind, pub instance: Option }`. A command as a surface shows and fires it. - `craft_ui::runtime::commands::fire`: `pub fn fire(ctx: &Context, command: impl Into, source: FireSource) -> bool`. Fires `command` from a surface that has no component of its own: a menu, the palette or automation. Scoped -- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into) -> ResolvedCommand`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state +- `craft_ui::runtime::commands::resolve`: `pub fn resolve(ctx: &Context, command: impl Into) -> Arc`. `command` as a surface with no component of its own shows it: the label, icon, chord, enabled and checked state - `craft_ui::runtime::commands::Binding`: re-export of `craft_keymap::Binding` (outside these crates). - `craft_ui::runtime::commands::ChromeCommand`: `pub enum ChromeCommand { TogglePanels, TogglePanelsKeepTools }`. The `window` commands that hide the panels of the window they run in. - `pub const ALL: [ChromeCommand; 2]`. Both commands. diff --git a/docs/glossary.md b/docs/glossary.md index f49a9d90a..317b2a858 100644 --- a/docs/glossary.md +++ b/docs/glossary.md @@ -49,7 +49,7 @@ One row per name in the author table (Overview) and per `pub` item a component a | `CommandGate` | The one gate that can disable commands (dialog open, workspace, recorder, pending operation) | `craft_ui::runtime::commands` | 11.3 | | `Commands` | The context trait on `Cx`, `BodyCx` and `ItemCx` for commands and the clipboard | `craft_ui::runtime::commands` | 11.3 | | `CommandSet` | A typed set of commands with one scope, written by `#[derive(CommandSet)]` and read with `take_command::()` | craft-keymap (trait), `craft_ui::runtime::commands` (board) | 11.2, 11.3 | -| `CommandState`, `CommandInput` | A command's state this frame, and the app-scope states in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 | +| `CommandState`, `CommandStates`, `CommandInput` | A command's state, the app-scope states an app holds in a `Tracked`, and the frame's command input in `FrameInput.commands` | `craft_ui::runtime::commands` | 11.3 | | `Common` | The props every component has, with no public fields | `craft_ui::contract` | 3.1 | | Component | Any type implementing the core trait | `craft_ui::contract` | 1.2 | | `ComponentStyle` | The trait every `type Style` implements, usually with `#[derive(ComponentStyle)]` | `craft_ui::style` | 4.3 |