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 85673f2e0..d1a00b31c 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,24 @@ 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 was dead, 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]; + // A held instance that missed a pass is dead until it registers again: its return is seen too. + let seen = held.stamp + 1 < instance.stamp + || 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 +124,25 @@ 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 state keys that changed, with the `state_seq` of each change, since the oldest wake of a kept table. + state_log: Vec<(u64, StateKey)>, + /// 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. @@ -133,8 +159,8 @@ pub(crate) struct Board { before: HashMap, /// Where the commands of the running pass are judged from: the key focus and the modal layers. here: Vantage, - /// The chain of the last pass in which any component held key focus. - last_focused: Vec, + /// Each viewport's own vantage facts. + views: HashMap, matcher: Matcher, held: Vec, /// The top modal layer's root container of each viewport that has one. @@ -149,8 +175,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 +194,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 +208,275 @@ 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) { - 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)); +/// The generations of what resolutions read beside states and the gate, across the viewports. +#[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, the held-open + /// canvas). + shared: u64, + /// Read by a resolution that picks an instance: the instances around the focus in every viewport. + focus: u64, +} + +/// The generations of one viewport's own vantage facts. +#[derive(Clone, Copy, Default, PartialEq)] +struct ViewGens { + /// Read by every resolution in the viewport: a dialog owns the keys at its focus. + keys: u64, + /// Read by a resolution that picks an instance or reaches by focus: the chain last focused in the viewport and the + /// instances of its focus chain inside the top modal layer. + focus: u64, + /// Read by a resolution the focused stop answered: the edits that stop takes and those of them that do nothing now. + edits: u64, +} + +/// One viewport's vantage facts as its last `begin` set them, and their generations. A viewport's `begin` compares +/// with its own, so two windows never move each other's. +#[derive(Default)] +struct View { + /// The chain of the last pass in which any component of the viewport held key focus. + last_focused: Vec, + inside_modal: Vec, + dialog_keys: bool, + /// The focused stop's edits and those of them that do nothing now. The focus record changes only in an end hook, + /// so the value `begin` reads holds for the pass. + edits: Option<(EditSet, EditSet)>, + gens: ViewGens, +} + +/// 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, + /// The focused stop answered for the command, or was asked: it read that stop's edits. + edits: bool, +} + +/// The inputs a kept resolution was made from: it holds while each is unchanged. +#[derive(Clone, PartialEq)] +struct ResolveKey { + shared: u64, + /// The viewport's keys generation. + keys: u64, + /// The focus generations, across the viewports and the viewport's own, when the resolution read the focus. + focus: Option<(u64, u64)>, + /// 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 viewport's edits generation, when the resolution read the focused stop's edits. + edits: Option, + /// The vantage of a reader under a layer or inside a menu (`None` inside: no stop to return to). + vantage: Option>, + /// The command's number, which a resolution the focused stop answered is noted under. + number: u32, +} + +impl ResolveKey { + /// The key a region that showed the resolution read it under: the state's, else the focused stop's answer. + fn bind(&self) -> Option { + match (self.state, self.edits) { + (Some(((number, instance), _)), _) => Some(BindKey::Command(number, instance)), + (None, Some(_)) => Some(BindKey::FocusedEdit(self.number)), + (None, None) => None, + } + } +} + +/// 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, + view: ViewGens, + state_seq: u64, + gate: Option, +} + +/// A kept resolution and who it was kept for. +struct Entry { + reader: Reader, + kept: Kept, +} + +/// What each reader of a viewport was shown, with indexes from each input to the entries that read it, so a wake walks +/// only the entries whose inputs moved. +#[derive(Default)] +struct Shown { + entries: HashMap, + next: u64, + /// By reader and command number (a command's parameter variants share the number). + by_reader: HashMap>>, + /// By the state key read. + by_state: HashMap>, + /// The entries that read the focus generations. + by_focus: HashSet, + /// The entries that read the focused stop's edits. + by_edits: HashSet, + /// The entries of readers under a layer or inside a menu, whose vantage every wake reads again. + layered: HashSet, + /// The inputs at the last wake. + woke: Option, +} + +impl Shown { + fn index(&mut self, id: u64) { + let Some(entry) = self.entries.get(&id) else { return }; + let key = &entry.kept.key; + if let Some((state, _)) = key.state { + self.by_state.entry(state).or_default().insert(id); + } + if key.focus.is_some() { + self.by_focus.insert(id); + } + if key.edits.is_some() { + self.by_edits.insert(id); + } + if entry.reader.layer().is_some() { + self.layered.insert(id); + } + } + + fn unindex(&mut self, id: u64) { + let Some(entry) = self.entries.get(&id) else { return }; + if let Some((state, _)) = entry.kept.key.state + && let Some(ids) = self.by_state.get_mut(&state) + { + ids.remove(&id); + if ids.is_empty() { + self.by_state.remove(&state); + } + } + self.by_focus.remove(&id); + self.by_edits.remove(&id); + self.layered.remove(&id); + } + + /// The entry `reader` keeps for `command`. + fn find(&self, reader: &Reader, number: u32, command: &CommandRef) -> Option { + let ids = self.by_reader.get(reader)?.get(&number)?; + ids.iter().copied().find(|id| self.entries.get(id).is_some_and(|entry| entry.kept.resolved.command == *command)) + } + + /// Keeps `kept` for `reader`, in place of what it kept for the same command. + fn keep(&mut self, reader: Reader, number: u32, kept: Kept) { + match self.find(&reader, number, &kept.resolved.command) { + Some(id) => self.replace(id, kept), + None => { + let id = self.next; + self.next += 1; + self.by_reader.entry(reader.clone()).or_default().entry(number).or_default().push(id); + self.entries.insert(id, Entry { reader, kept }); + self.index(id); + } + } + } + + /// `kept` in place of entry `id`'s, indexed under its inputs. + fn replace(&mut self, id: u64, kept: Kept) { + self.unindex(id); + if let Some(entry) = self.entries.get_mut(&id) { + entry.kept = kept; + } + self.index(id); + } + + /// Drops the entries `drop` names. + fn drop_where(&mut self, mut drop: impl FnMut(&Entry) -> bool) { + let gone: Vec = self.entries.iter().filter(|(_, entry)| drop(entry)).map(|(id, _)| *id).collect(); + for id in gone { + self.unindex(id); + if let Some(entry) = self.entries.remove(&id) { + let number = entry.kept.key.number; + if let Some(by_number) = self.by_reader.get_mut(&entry.reader) { + if let Some(ids) = by_number.get_mut(&number) { + ids.retain(|at| *at != id); + if ids.is_empty() { + by_number.remove(&number); + } + } + if by_number.is_empty() { + self.by_reader.remove(&entry.reader); + } + } + } + } + } +} + +/// Whether `key` still holds under the board's `gens`, the viewport's `view` generations, `revisions`, the current +/// `gate` answer 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, + view: ViewGens, + revisions: &HashMap, + gate: Option<(u128, bool)>, + vantage: Option<&Option>, +) -> bool { + let same = key.shared == gens.shared + && key.keys == view.keys + && key.focus.is_none_or(|focus| focus == (gens.focus, view.focus)) + && key.edits.is_none_or(|edits| edits == view.edits) + && key.state.is_none_or(|(state, revision)| revisions.get(&state).copied().unwrap_or(0) == revision) + && key.vantage.as_ref() == vantage; + 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 a resolution under `key` (a state's, or the focused stop's +/// answer): 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, an instance or the stop's edits changed), and a change published after it in +/// the pass runs the pass again. +fn note_read(ctx: &Context, key: Option) { + let Some(key) = key else { return }; + reads::note(ctx, key, Id::NULL, measure::active(ctx), &[]); } /// 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 +499,64 @@ 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 key it was read under. + 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); + self.state_log.push((self.state_seq, key)); + } + + /// 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)) + } + + /// The generations of `viewport`'s own vantage facts. + fn view_gens(&self, viewport: ViewportId) -> ViewGens { + self.views.get(&viewport).map_or_else(ViewGens::default, |view| view.gens) + } + + /// What `reader` of `viewport` was shown of `command`, judged from `vantage` (a layered reader's). + fn lookup(&mut self, 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 view = self.view_gens(viewport); + let Some(shown) = self.shown.get_mut(&viewport) else { return Lookup::Missing }; + let Some(id) = shown.find(reader, number, command) else { return Lookup::Missing }; + let Some(entry) = shown.entries.get_mut(&id) else { return Lookup::Missing }; + if holds(&mut entry.kept.key, self.gens, view, &self.revisions, gate, vantage) { + Lookup::Fresh(Arc::clone(&entry.kept.resolved), entry.kept.key.bind()) + } 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 number = key.number; + self.shown.entry(viewport).or_default().keep(reader, number, Kept { resolved, key }); + } + fn live(&self, ctx: &Context, instance: &Instance) -> bool { instance.stamp + 1 >= pass::pass_nr(ctx, instance.viewport) } @@ -332,7 +654,8 @@ impl Board { fn pick(&self, ctx: &Context, scope: &str, from: &Vantage) -> Option { // The held-open canvas ranks below every instance around the focus. let focused: Vec = self.held_open.into_iter().chain(from.focused.iter().flat_map(|(_, chain)| chain.iter().copied())).collect(); - pick_instance(&self.live_instances(ctx, scope), &focused, &self.last_focused) + let last = self.views.get(&pass::current_viewport(ctx)).map_or(&[][..], |view| view.last_focused.as_slice()); + pick_instance(&self.live_instances(ctx, scope), &focused, last) } /// The non-app scopes around the focus, innermost first. An instance of a child scope also brings the scopes it @@ -370,7 +693,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 +702,13 @@ 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 = true; + 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 +723,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 +732,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 +744,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 +829,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 +989,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 +1005,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 +1063,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 +1130,11 @@ fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { crate::runtime::replay::journal(ctx, || (scope, id, layer), |ctx, &(scope, id, layer)| register_in(ctx, scope, id, layer)); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); - with(ctx, |board| 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 +1157,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 +1221,51 @@ 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 view = board.view_gens(pass::current_viewport(ctx)); + let key = ResolveKey { + shared: board.gens.shared, + keys: view.keys, + focus: reads.focus.then_some((board.gens.focus, view.focus)), + state: state.map(|state| (state, board.revisions.get(&state).copied().unwrap_or(0))), + gate, + edits: reads.edits.then_some(view.edits), + vantage: None, + number: board.numbers.get(command.id.as_str()).copied().unwrap_or(u32::MAX), + }; + (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 +1275,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,89 +1283,198 @@ 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(viewport, &reader, command, vantage.as_ref())); + let (resolved, bind) = match found { + Lookup::Fresh(resolved, bind) => (resolved, bind), + 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, bind) = (Arc::new(resolved), key.bind()); + with(ctx, |board| board.keep(viewport, reader, Arc::clone(&resolved), key)); + (resolved, bind) + } + }; + note_read(ctx, bind); 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 +/// `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 key each was read under when its 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 walks only the entries whose inputs +/// moved, through the table's indexes: every entry when a generation all of them read moved (the shared one, the +/// viewport's keys, the gate), else the readers of the focus, of the focused stop's edits and of each changed state, +/// and the readers under a layer or in a menu, whose vantage it reads again. 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 taken = with(ctx, |board| { + let now = + Woke { gens: board.gens, view: board.view_gens(viewport), state_seq: board.state_seq, gate: board.gate.as_ref().map(CommandGate::key) }; + let shown = board.shown.get(&viewport)?; + let woke = shown.woke; + if woke == Some(now) && shown.layered.is_empty() { + return None; + } + let all = woke.is_none_or(|woke| woke.gens.shared != now.gens.shared || woke.view.keys != now.view.keys || woke.gate != now.gate); + let mut walk: HashSet = if all { shown.entries.keys().copied().collect() } else { shown.layered.clone() }; + if let Some(woke) = woke.filter(|_| !all) { + if (woke.gens.focus, woke.view.focus) != (now.gens.focus, now.view.focus) { + walk.extend(&shown.by_focus); + } + if woke.view.edits != now.view.edits { + walk.extend(&shown.by_edits); + } + for (_, state) in board.state_log.iter().filter(|(seq, _)| *seq > woke.state_seq) { + walk.extend(shown.by_state.get(state).into_iter().flatten()); + } + } + Some((now, walk, board.shown.remove(&viewport)?)) + }); + let Some((now, walk, 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, + // A reader beneath a layer or inside a menu that is no longer shown is gone with it. + table.drop_where(|entry| entry.reader.layer().is_some_and(|layer| !overlay::is_open(ctx, layer))); + let mut vantages: HashMap>> = HashMap::new(); + for id in walk { + let Some(entry) = table.entries.get_mut(&id) else { continue }; + #[cfg(feature = "testing")] + measure::count_wake_walk(ctx); + let vantage = match entry.reader.layer() { + Some(layer) => vantages.entry(layer).or_insert_with(|| vantage_of(ctx, &entry.reader)).clone(), + None => None, + }; + let fresh = with(ctx, |board| { + let gate = board.gate_answer(&entry.kept.resolved.command); + holds(&mut entry.kept.key, board.gens, board.view_gens(viewport), &board.revisions, gate, vantage.as_ref()) }); - 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); - } + if fresh { + continue; } + #[cfg(feature = "testing")] + measure::count_resolve(ctx, Resolve::Again); + let (resolved, key) = resolve_as(ctx, &entry.reader, &entry.kept.resolved.command, vantage); + let was = entry.kept.key.bind(); + let resolved = if resolved == *entry.kept.resolved { + Arc::clone(&entry.kept.resolved) + } else { + changed.extend(was); + changed.extend(key.bind().filter(|bind| Some(*bind) != was)); + Arc::new(resolved) + }; + table.replace(id, Kept { resolved, key }); } - table.retain(|_, readers| !readers.is_empty()); + 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 (_, entry) in added.entries { + let number = entry.kept.key.number; + table.keep(entry.reader, number, entry.kept); } } - if !table.is_empty() { + if !table.entries.is_empty() { board.shown.insert(viewport, table); } }); - for (number, instance) in changed { - lazy::note_edit(ctx, BindKey::Command(number, instance)); + for key in changed { + lazy::note_edit(ctx, key); } } +/// Testing check, every 100th pass of a viewport: every kept resolution of `viewport` equals a full resolution from its +/// reader, and every kept gate answer equals the gate's answer asked again apart from the cache. 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.shown.remove(&viewport)) else { return }; + for entry in table.entries.values() { + if entry.reader.layer().is_some_and(|layer| !overlay::is_open(ctx, layer)) { + continue; + } + let command = &entry.kept.resolved.command; + measure::count_resolve(ctx, Resolve::Checked); + let (fresh, _) = resolve_as(ctx, &entry.reader, command, vantage_of(ctx, &entry.reader)); + assert!( + fresh == *entry.kept.resolved, + "the kept resolution of {} for a {} reader differs from a full resolve: kept {:?}, resolved {fresh:?}", + command, + entry.reader.kind(), + entry.kept.resolved, + ); + let (cached, gate) = with(ctx, |board| (board.gate_answers.get(command.key_text().as_ref()).copied(), board.gate.clone())); + if let (Some(cached), Some(gate)) = (cached, gate) { + assert!(cached == gate.allows(command), "the kept gate answer for {command} differs from the gate's"); + } + } + 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 +1504,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 +1542,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; } @@ -1099,11 +1582,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 { @@ -1165,7 +1651,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 } } @@ -1186,7 +1672,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,8 +1734,12 @@ pub(crate) fn begin(ctx: &Context) { // A shortcut pressed in a menu or on a menu bar matches where the focus returns to once the menus close. let returning = focused.filter(|_| !shortcuts.keys.is_empty()).and_then(|focused| Returning::of(ctx, focused)); let shell = frame::shell_root(ctx, viewport); + let edits = focused_edits(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)) @@ -1262,18 +1752,42 @@ pub(crate) fn begin(ctx: &Context) { (true, Some(root)) => vec![*root], _ => chain, }; - if !chain.is_empty() { - board.last_focused.clone_from(&chain); + let view = board.views.entry(viewport).or_default(); + if !chain.is_empty() && view.last_focused != chain { + view.last_focused.clone_from(&chain); + view.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; + } } - board.here.dialog_keys = shortcuts.dialog; - board.here.inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); + // The viewport's own facts move its own generations; `here` holds the running viewport's for the pass. + let inside_modal = Board::inside_modal_of(&chain, |id| board.is_modal_root(id)); + let view = board.views.entry(viewport).or_default(); + if view.dialog_keys != shortcuts.dialog { + view.dialog_keys = shortcuts.dialog; + view.gens.keys += 1; + } + if view.inside_modal != inside_modal { + view.inside_modal = inside_modal; + view.gens.focus += 1; + } + if view.edits != edits { + view.edits = edits; + view.gens.edits += 1; + } + board.here.dialog_keys = view.dialog_keys; + board.here.inside_modal.clone_from(&view.inside_modal); if shortcuts.keys.is_empty() { return None; } @@ -1289,6 +1803,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).is_multiple_of(100) { + check_kept(ctx, viewport); + } let Some((keys, mut matcher)) = taken else { return }; let mut fired = Vec::new(); for shortcut in &shortcuts.keys { @@ -1316,7 +1834,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; } @@ -1369,9 +1887,22 @@ pub(crate) fn begin(ctx: &Context) { /// The end hook: instances that stopped registering are gone, and so are the commands queued for them and the readers /// inside them. pub(crate) fn end(ctx: &Context) { + let viewport = pass::current_viewport(ctx); 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 of this viewport this pass did not register is dead from the viewport's next pass: resolutions + // see it. + let dies = board.instances.iter().zip(&alive).any(|(i, alive)| *alive && i.viewport == viewport && i.stamp < pass::pass_nr(ctx, viewport)); + let gone: HashSet = board.instances.iter().zip(&alive).filter(|(_, alive)| !**alive).map(|(i, _)| i.id).collect(); + // The revisions of a removed instance's states go in the same step as a shared move, which makes every entry + // that holds one stale first. + if !gone.is_empty() { + board.revisions.retain(|(_, instance), _| instance.is_none_or(|id| !gone.contains(&id))); + } + if dies || !gone.is_empty() { + board.gens.shared += 1; + } let mut keep = alive.iter(); board.instances.retain(|_| keep.next().copied().unwrap_or(false)); let instances = &board.instances; @@ -1380,16 +1911,20 @@ pub(crate) fn end(ctx: &Context) { board.held.retain(|held| held.target.is_none_or(ids)); board.chains.retain(|viewport, _| live.contains(viewport)); board.before.retain(|viewport, _| live.contains(viewport)); + board.views.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.drop_where(|entry| match &entry.reader { + Reader::Chain(chain) | Reader::InMenu(_, chain) => chain.innermost_any().is_some_and(|id| !ids(id)), + _ => false, }); - live.contains(viewport) && !table.is_empty() + live.contains(viewport) && !table.entries.is_empty() }); + // The state log keeps the changes no kept table has woken past. + let oldest = board.shown.values().map(|table| table.woke.map_or(0, |woke| woke.state_seq)).min(); + match oldest { + Some(oldest) => board.state_log.retain(|(seq, _)| *seq > oldest), + None => board.state_log.clear(), + } }); } diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 3c9592467..d18815467 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/egui/fixture.rs b/crates/ui-contract/src/runtime/egui/fixture.rs index c5f87706f..386f89f21 100644 --- a/crates/ui-contract/src/runtime/egui/fixture.rs +++ b/crates/ui-contract/src/runtime/egui/fixture.rs @@ -137,6 +137,45 @@ fn window_focus_facts(ctx: &Context, events: &[Event], native_pixels_per_point: #[derive(Default)] struct WindowFocus(Option); +/// The child windows of the root that are open: each opens with its first frame and stays listed in every frame's +/// viewports, as eframe lists every open viewport, until a test closes it ([`close_viewport`]) or the app sends it +/// `ViewportCommand::Close`. +#[derive(Default)] +struct OpenChildren(Vec); + +/// The open child windows, with `viewport` opened first when it is a child. +fn open_children(ctx: &Context, viewport: egui::ViewportId) -> Vec { + Service::::run(ctx, |open| { + if viewport != egui::ViewportId::ROOT && !open.0.contains(&viewport) { + open.0.push(viewport); + } + open.0.clone() + }) +} + +/// One run of `ui` on `input`; a root pass declares the open `children` after it, as an eframe app shows each of its +/// windows every frame: egui keeps a child viewport only while its parent's passes show it. Each child's content runs +/// in its own frames, so the declaration shows nothing. +fn run_ui(ctx: &Context, input: RawInput, children: &[egui::ViewportId], mut ui: impl FnMut(&mut Ui)) -> egui::FullOutput { + let root = input.viewport_id == egui::ViewportId::ROOT; + ctx.run_ui(input, |top| { + ui(top); + if root && !children.is_empty() { + let embedded = ctx.embed_viewports(); + ctx.set_embed_viewports(false); + for child in children { + ctx.show_viewport_deferred(*child, egui::ViewportBuilder::default(), |_, _| {}); + } + ctx.set_embed_viewports(embedded); + } + }) +} + +/// Closes the child window `viewport`: later frames no longer list it. +pub(crate) fn close_viewport(ctx: &Context, viewport: egui::ViewportId) { + Service::::run(ctx, |open| open.0.retain(|held| *held != viewport)); +} + /// The fixture's reset bridge, as egui-winit keeps one per window: the reset request it holds for each viewport, and /// the requests it dropped, which the next frame reports as `Event::ImeResetRetired`. #[derive(Default)] @@ -187,7 +226,8 @@ impl ImeResets { } /// Runs one pass of `viewport` at `time` seconds with `events` and `files`, on a window of `native_pixels_per_point` -/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live. +/// (egui's default when `None`). A viewport other than the root is a child window of the root, which stays live; the +/// child stays open in every later frame, the root's included, until it is closed. #[expect(clippy::too_many_arguments, reason = "the arguments are the facts of one frame, and every caller passes them all")] pub(crate) fn run_frame( ctx: &Context, @@ -204,9 +244,10 @@ pub(crate) fn run_frame( let dropped_files = files.dropped.iter().map(|name| Arc::new(DroppedPath(name.into())) as egui::DroppedFileHandle).collect(); Service::::run(ctx, |resets| resets.input(viewport, &mut events)); let mut viewports = window_focus_facts(ctx, &events, native_pixels_per_point); - if viewport != egui::ViewportId::ROOT { + let children = open_children(ctx, viewport); + for child in &children { viewports - .insert(viewport, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() }); + .insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), native_pixels_per_point, ..egui::ViewportInfo::default() }); } let input = RawInput { screen_rect: Some(screen), @@ -218,7 +259,7 @@ pub(crate) fn run_frame( viewports, ..RawInput::default() }; - let mut output = drive(|| ctx.run_ui(input, ui)); + let mut output = drive(|| run_ui(ctx, input, &children, ui)); Service::::run(ctx, |resets| resets.output(viewport, &output.platform_output)); let mut flat = Vec::new(); for clipped in &output.shapes { @@ -257,6 +298,15 @@ pub(crate) fn run_frame( }) .collect(); let closed = output.viewport_output.values().any(|viewport| viewport.commands.iter().any(|command| matches!(command, ViewportCommand::Close))); + let closing: Vec = output + .viewport_output + .iter() + .filter(|(id, out)| **id != egui::ViewportId::ROOT && out.commands.iter().any(|command| matches!(command, ViewportCommand::Close))) + .map(|(id, _)| *id) + .collect(); + for child in closing { + close_viewport(ctx, child); + } let repaint_delay = output.viewport_output.get(&egui::ViewportId::ROOT).map_or(std::time::Duration::MAX, |viewport| viewport.repaint_delay); let copied = output .platform_output @@ -366,8 +416,14 @@ pub(crate) fn reordered_fonts() -> egui::FontDefinitions { /// Runs one frame like `run_frame` and returns the shapes it painted, nested shapes flattened. pub(crate) fn run_frame_shapes(ctx: &Context, time: f64, screen: Vec2, ui: impl FnMut(&mut Ui)) -> Vec { let screen = Rect::from_min_size(Pos2::ZERO, screen); - let input = RawInput { screen_rect: Some(screen), time: Some(time), ..RawInput::default() }; - let mut output = drive(|| ctx.run_ui(input, ui)); + let children = open_children(ctx, egui::ViewportId::ROOT); + let mut viewports = egui::ViewportIdMap::default(); + viewports.insert(egui::ViewportId::ROOT, egui::ViewportInfo::default()); + for child in &children { + viewports.insert(*child, egui::ViewportInfo { parent: Some(egui::ViewportId::ROOT), ..egui::ViewportInfo::default() }); + } + let input = RawInput { screen_rect: Some(screen), time: Some(time), viewports, ..RawInput::default() }; + let mut output = drive(|| run_ui(ctx, input, &children, ui)); output.textures_delta.clear(); let mut flat = Vec::new(); for clipped in output.shapes { diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 71e2cf685..969020d63 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -297,6 +297,43 @@ 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 kept resolution a wake walked to compare its key. +#[cfg(feature = "testing")] +pub(crate) fn count_wake_walk(ctx: &Context) { + totals(ctx, |log| log.wake_walks += 1); +} + +/// The kept resolutions the wakes of the last pass walked. +#[cfg(feature = "testing")] +pub fn last_pass_wake_walks(ctx: &Context) -> u32 { + last_totals(ctx, |log| log.wake_walks, 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) { @@ -362,29 +399,49 @@ pub fn last_pass_settles(ctx: &Context) -> Vec<(Id, Settle)> { /// Bytes fed into memo keys in one pass, and the layouts, measure asks and chord texts of that pass. #[cfg(feature = "testing")] #[derive(Default)] -pub(crate) struct PassTotals { +pub(crate) struct Totals { pass: u64, key_bytes: usize, text_layouts: u32, chord_texts: u32, + resolves: [u32; 3], + wake_walks: u32, asks: Vec<(&'static str, u32)>, } +/// The totals of the running pass and of the one before it, which a pass's own counting does not overwrite: a pass +/// that counts in its begin hook keeps the last pass readable. #[cfg(feature = "testing")] -fn totals(ctx: &Context, f: impl FnOnce(&mut PassTotals) -> R) -> R { +#[derive(Default)] +pub(crate) struct PassTotals { + current: Totals, + previous: Totals, +} + +#[cfg(feature = "testing")] +fn totals(ctx: &Context, f: impl FnOnce(&mut Totals) -> R) -> R { let pass = ctx.cumulative_pass_nr(); pass_state::with::(ctx, |log| { - if log.pass != pass { - *log = PassTotals { pass, ..PassTotals::default() }; + if log.current.pass != pass { + let current = std::mem::replace(&mut log.current, Totals { pass, ..Totals::default() }); + log.previous = current; } - f(log) + f(&mut log.current) }) } #[cfg(feature = "testing")] -fn last_totals(ctx: &Context, f: impl FnOnce(&PassTotals) -> R, none: R) -> R { +fn last_totals(ctx: &Context, f: impl FnOnce(&Totals) -> R, none: R) -> R { let last = ctx.cumulative_pass_nr().saturating_sub(1); - pass_state::with::(ctx, |log| if log.pass == last { f(log) } else { none }) + pass_state::with::(ctx, |log| { + if log.current.pass == last { + f(&log.current) + } else if log.previous.pass == last { + f(&log.previous) + } else { + none + } + }) } /// Counts `bytes` fed into a memo key in this pass. Fed by `MemoKey`; until it exists, by `lazy::settled` (8 bytes diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index 4b3cf72e1..ca91aecb4 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -25,6 +25,8 @@ pub(crate) enum BindKey { Record(Id), /// A command's state on the board: the command's number and the instance whose state it is, `None` for the app's. Command(u32, Option), + /// A command the focused stop answers for (an edit it takes): the command's number. + FocusedEdit(u32), } /// One measure a reader made from the value it read: what it was offered and the size it took. 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/frames.rs b/crates/ui-contract/src/testing/frames.rs index 0b27e14fe..938170f56 100644 --- a/crates/ui-contract/src/testing/frames.rs +++ b/crates/ui-contract/src/testing/frames.rs @@ -186,9 +186,13 @@ impl Frames { } /// One frame of `viewport`, a child window of the root while the root stays live, with `events`; `ui` runs once - /// per pass. Returns the number of passes. + /// per pass. Returns the number of passes. The child opens with its first frame and stays open, listed in the root's + /// frames too, until [`close_viewport`](Self::close_viewport) or a `ViewportCommand::Close` for it. pub fn frame_in_viewport(&mut self, viewport: egui::ViewportId, events: Vec, mut ui: impl FnMut(&mut Ui)) -> usize { - set_input(&self.ctx, self.input()); + // The app's input is the root's, once per app frame: a child window's frame runs inside it. + if viewport == egui::ViewportId::ROOT { + set_input(&self.ctx, self.input()); + } let mut passes = 0; self.run(viewport, events, |root| { passes += 1; @@ -253,6 +257,11 @@ impl Frames { self.time += seconds; } + /// Closes the child window `viewport`, as its user would: later frames no longer list it. + pub fn close_viewport(&mut self, viewport: egui::ViewportId) { + fixture::close_viewport(&self.ctx, viewport); + } + /// `n` frames with no events. pub fn idle(&mut self, n: usize, mut ui: impl FnMut(&mut Ui)) { for _ in 0..n { 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..955bc8677 --- /dev/null +++ b/crates/ui-shell/tests/it/commands/resolve.rs @@ -0,0 +1,384 @@ +//! Command resolution runs only when an input of it changed: count trials over fifty shown commands. + +use super::kit::{AppCommand, DOCK, Dock, PANE, Pane, PaneCommand, Tap}; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Lazy, Trigger}; +use craft_ui::contract::{Props as _, Show as _, ShowContainer as _, Tracked}; +use craft_ui::dialog::Dialog; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::runtime::commands::{ + AppCatalog, Binding, CommandDef, CommandGate, CommandInput, CommandRef, CommandSet as _, CommandState, CommandStates, Commands as _, Scope, +}; +use craft_ui::runtime::commands::{EditCommands, declare_child, resolve, resolve_beneath}; +use craft_ui::runtime::focus::{FocusTarget, request}; +use craft_ui::runtime::measure::last_pass_wake_walks; +use craft_ui::runtime::measure::{Resolve, last_pass_resolves}; +use craft_ui::sections::{DialogRole, FooterButton}; +use craft_ui::testing::input::key_press; +use craft_ui::testing::pointer::moved; +use craft_ui::testing::pointer::{press, release}; +use craft_ui::testing::{Frames, trial}; +use craft_ui::text::TextField; +use egui::{Id, Pos2, Ui}; +use egui::{Key, Modifiers, ViewportId}; +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. With +/// `global`, a surface with no component of its own reads Zoom In after the panes, which picks an instance by the focus. +struct Scene { + zoom: Cell, + ids: RefCell>, + global: bool, + /// Pane `a` is left out of the next pass. + skip_a: Cell, + /// Salts the panes' ids, so two windows show panes of their own. + window: &'static str, +} + +impl Scene { + fn new() -> Self { + Scene { zoom: Cell::new(true), ids: RefCell::new(Vec::new()), global: false, skip_a: Cell::new(false), window: "" } + } + + fn show(&self, ui: &mut Ui) { + self.ids.borrow_mut().clear(); + let skip_a = self.skip_a.replace(false); + for (pane, salt) in PANES.iter().enumerate() { + if pane == 0 && skip_a { + continue; + } + Pane::new().id_salt((self.window, *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); + } + }); + } + if self.global { + resolve(ui.ctx(), PaneCommand::ZoomIn); + } + } +} + +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 (new, again, _) = frame_walks(frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + (new, again) +} + +/// One frame of `viewport` running `show`, and its new and repeated resolutions and the kept resolutions its wakes +/// walked, summed over every pass of the frame. +fn frame_walks(frames: &mut Frames, viewport: ViewportId, show: &mut dyn FnMut(&mut Ui)) -> (u32, u32, u32) { + let ctx = frames.ctx.clone(); + let (mut new, mut again, mut walks, mut pass) = (0, 0, 0, 0); + let mut add = |ctx: &egui::Context| { + let (n, a) = counts(ctx); + (new, again, walks) = (new + n, again + a, walks + last_pass_wake_walks(ctx)); + }; + frames.frame_in_viewport(viewport, vec![], |ui| { + if pass > 0 { + add(&ctx); + } + pass += 1; + show(ui); + }); + add(&ctx); + (new, again, walks) +} + +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"); +} + +/// Two windows with frames alternating between them, idle: each frame resolves nothing and walks nothing, as the +/// child stays open across the root's frames and the root's across the child's. +#[trial] +fn idle_frames_alternating_between_two_windows_resolve_nothing() { + let root = Scene::new(); + let other = Scene { window: "child", ..Scene::new() }; + let child = ViewportId::from_hash_of("second window"); + let mut frames = Frames::new(); + let states = Tracked::new(CommandStates::new()); + frames.commands(gated(&states, false)); + for _ in 0..3 { + frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui)); + frame_walks(&mut frames, child, &mut |ui| other.show(ui)); + } + for round in 0..4 { + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| root.show(ui)), (0, 0, 0), "root frame {round}"); + assert_eq!(frame_walks(&mut frames, child, &mut |ui| other.show(ui)), (0, 0, 0), "child frame {round}"); + } +} + +/// 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_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), + (0, SAVE_READERS, SAVE_READERS), + "the wake walks and resolves again only Save's readers" + ); + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "the next frame walks 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); + // The publish runs before its reader, which resolves again as it reads; a wake walks only that reader. + let (new, again, first) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + let (_, _, second) = frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)); + assert_eq!((new, again), (0, 1), "only pane a's Zoom In reader resolves again"); + assert_eq!(first + second, 1, "the wakes walk only the reader of the published key"); + assert_eq!(frame_walks(&mut frames, ViewportId::ROOT, &mut |ui| scene.show(ui)), (0, 0, 0), "publishing the same state again walks 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"); + } + } +} + +/// An instance that misses exactly one pass and registers again is live again for every kept resolution in the +/// frame it comes back in: its return moves the inputs every resolution reads. +#[trial] +fn an_instance_back_after_one_missed_pass_is_live_again() { + let shown = Cell::new(true); + let enabled = Cell::new(false); + let mut show = |ui: &mut Ui| { + if shown.get() { + Pane::new().id_salt("b").show(ui, |ui, _| { + Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui); + }); + } + enabled.set(resolve(ui.ctx(), PaneCommand::ZoomIn).enabled); + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + assert!(enabled.get(), "Zoom In reaches the pane"); + shown.set(false); + assert_eq!(frames.frame(vec![], &mut show), 1, "the pane misses one pass"); + shown.set(true); + frames.frame(vec![], &mut show); + assert!(enabled.get(), "the pane is live again in the frame it comes back in"); + frames.frame(vec![], &mut show); + assert!(enabled.get(), "and stays so"); +} + +/// A settled region that shows a command the focused stop answers for (Cut, which a text field takes) runs when that +/// stop's answer changes: with the focus moving from the field to a tap, which takes no edits, Cut no longer waits for a +/// selection. +#[trial] +fn a_settled_region_runs_when_the_focused_stops_answer_changes() { + let text = RefCell::new("hello".to_owned()); + let (field, tap, cut) = (Cell::new(Id::NULL), Cell::new(Id::NULL), Cell::new(Id::NULL)); + let runs = Cell::new(0); + let mut show = |ui: &mut Ui| { + field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id); + tap.set(Tap::new().id_salt("plain").show(ui).id); + Lazy::new("edits", 0.0).settles(true).show(ui, |ui| { + runs.set(runs.get() + 1); + cut.set(Button::command(EditCommands::Cut).show(ui).id); + }); + }; + let mut frames = Frames::new(); + frames.idle(2, &mut show); + request(&frames.ctx, FocusTarget::Id(field.get())); + frames.idle(30, &mut show); + assert!(frames.tree().is_disabled(cut.get()), "Cut does nothing with no text selected"); + runs.set(0); + frames.idle(2, &mut show); + assert_eq!(runs.get(), 0, "the region is settled"); + request(&frames.ctx, FocusTarget::Id(tap.get())); + frames.idle(2, &mut show); + assert_eq!(runs.get(), 1, "the new answer for Cut runs the region once"); + assert!(!frames.tree().is_disabled(cut.get()), "which shows Cut enabled"); +} + +/// The testing check every 100th pass compares every kept resolution with a full one, and every kept gate answer with +/// the gate's. The script changes, a few passes before each check, every kind of input a resolution reads: app and +/// published states, the gate, the keymap, the focus and the focused stop's edits, a menu and a modal layer with readers +/// inside (a palette's reader under the layer), an instance that misses one pass and a scope's parent. +#[trial] +fn the_hundredth_pass_check_finds_every_kept_resolution_current() { + let scene = Scene { global: true, ..Scene::new() }; + let text = RefCell::new("hello".to_owned()); + let (field, opener) = (Cell::new(Id::NULL), Cell::new(Pos2::ZERO)); + let modal = Cell::new(false); + let mut show = |ui: &mut Ui| { + scene.show(ui); + field.set(TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui).response.id); + Tap::new().id_salt("cut").command(EditCommands::Cut).show(ui); + Dock::new().id_salt("dock").show(ui, |ui, _| { + Tap::new().id_salt("zoom").command(PaneCommand::ZoomIn).show(ui); + }); + let open = Tap::new().id_salt("opener").show(ui); + opener.set(open.rect.center()); + Menu::new("Menu").opened_by(&open, Trigger::Click).show(ui, |ui, _| { + MenuItem::command(AppCommand::Save).show(ui); + MenuItem::command(EditCommands::Cut).show(ui); + }); + let mut open = modal.get(); + Dialog::new("Options").opened(Bind::bound(&mut open)).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, cx| { + cx.publish(EditCommands::Undo, CommandState::new()); + resolve_beneath(ui.ctx(), AppCommand::Save); + Tap::new().id_salt("in dialog").command(EditCommands::Undo).show(ui); + }); + modal.set(open); + }; + 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.is_multiple_of(2) { "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)); + // Each step at the pass it names, relative to a check at 100 and 200. + let script: Vec<(usize, &str)> = [100, 200] + .into_iter() + .flat_map(|check| { + let steps: &[(usize, &str)] = if check == 100 { + &[(14, "focus field"), (12, "select all"), (10, "press opener"), (9, "release opener"), (6, "parent"), (3, "skip a"), (1, "state")] + } else { + &[(14, "focus field"), (12, "collapse"), (10, "modal"), (8, "keymap"), (6, "gate"), (3, "skip a"), (1, "publish")] + }; + steps.iter().map(move |(before, step)| (check - before, *step)).collect::>() + }) + .chain([(103, "escape"), (203, "close modal")]) + .collect(); + let mut script = script.into_iter().peekable(); + let (mut passes, mut checked) = (0, Vec::new()); + while passes < 260 { + let mut events = Vec::new(); + if let Some((_, step)) = script.next_if(|(at, _)| passes + 1 >= *at) { + match step { + "focus field" => { + request(&frames.ctx, FocusTarget::Id(field.get())); + } + "select all" => events.push(key_press(Key::A, Modifiers::COMMAND)), + "collapse" => events.push(key_press(Key::ArrowRight, Modifiers::NONE)), + "press opener" => events.push(press(opener.get())), + "release opener" => events.push(release(opener.get())), + "escape" => events.push(key_press(Key::Escape, Modifiers::NONE)), + "skip a" => scene.skip_a.set(true), + "parent" => declare_child(&frames.ctx, DOCK, PANE), + "state" => states.set(AppCommand::Go, CommandState::new().checked(true)), + "gate" => refuses = !refuses, + "keymap" => generation += 1, + "publish" => scene.zoom.set(!scene.zoom.get()), + "modal" => modal.set(true), + _ => modal.set(false), + } + } + frames.commands(input(&states, refuses, generation)); + passes += frames.frame(events, &mut show); + let compared = last_pass_resolves(&frames.ctx, Resolve::Checked); + if compared > 0 { + checked.push(compared); + } + } + assert_eq!(script.next().map(|(_, step)| step), None, "every step ran"); + assert_eq!(checked.len(), 2, "two checks ran: {checked:?}"); + assert!(checked.iter().all(|compared| *compared > KEPT), "each compared the panes' readers and the script's: {checked:?}"); +} 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/design/layers/craft-ui-contract/contract.toml b/design/layers/craft-ui-contract/contract.toml index b39d88b37..6206cbe3c 100644 --- a/design/layers/craft-ui-contract/contract.toml +++ b/design/layers/craft-ui-contract/contract.toml @@ -3,3 +3,8 @@ config_version = 1 [[module]] path = "contract" layer = 4 + +# memo depends only on std and runtime::env, so it sits with the runtime modules that use it. +[[module]] +path = "contract::memo" +layer = 2 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 |