diff --git a/crates/draw/tests/it/transform_box.rs b/crates/draw/tests/it/transform_box.rs index 4f4b10608..4712c9ff8 100644 --- a/crates/draw/tests/it/transform_box.rs +++ b/crates/draw/tests/it/transform_box.rs @@ -55,6 +55,8 @@ struct Config { line: Option, /// Snap targets beside the guides at [`SNAP_XS`]. targets: Vec, + /// egui runs each frame twice and gives the frame's input to its first pass only. + twice: bool, } /// What the host keeps of the box and what the passes reported. @@ -99,6 +101,7 @@ fn defaults() -> Config { centre_mark: false, line: None, targets: Vec::new(), + twice: false, } } @@ -183,6 +186,9 @@ fn harness(state: BoxState, setup: impl FnOnce(&mut Config)) -> Harness { } (control.show_at(ui, body.rect), guide_edits) }); + if config.twice && ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("the frame runs twice"); + } if let Some((output, guide_edits)) = canvas.inner { let mut host = shown_host.borrow_mut(); host.guide_events += guide_edits; @@ -441,6 +447,27 @@ fn a_text_frame_fed_back_through_an_f32_host_follows_every_move_to_the_commit() assert!((h.state().quad[2].y - 280.0).abs() < 0.01 && events.last() == Some(&Seen::Commit), "the commit holds the last move"); } +/// A frame egui runs twice reports each move of a drag once: its second pass proposes the box the first did, and an +/// equal proposal reports no `Update` again, so a host that applies each `Update` (a text layer's box) applies it once +/// per move. +#[trial] +fn a_frame_run_twice_reports_each_move_of_a_drag_once() { + let mut h = harness(BoxState::from_rect(RECT), |config| config.text_frame = true); + let (start, mid, end) = (h.screen(Point::new(200.0, 220.0)), h.screen(Point::new(200.0, 250.0)), h.screen(Point::new(200.0, 280.0))); + frame(&mut h, vec![pointer::moved(start)]); + frame(&mut h, vec![pointer::press(start)]); + h.config.borrow_mut().twice = true; + h.host.borrow_mut().events.clear(); + frame(&mut h, vec![pointer::moved(mid)]); + assert_eq!(h.fixture.passes(), 2, "the frame ran twice"); + frame(&mut h, vec![pointer::moved(end)]); + frame(&mut h, Vec::new()); + let events = h.host.borrow().events.clone(); + let updates = events.iter().filter(|seen| **seen == Seen::Update).count(); + assert_eq!(updates, 2, "two moves report two updates, a held frame none: {events:?}"); + assert!((h.state().quad[2].y - 280.0).abs() < 0.01, "the last move reached the host"); +} + #[trial] fn a_scale_drag_reads_its_size_in_the_ruler_unit_and_percent_only_in_percent_rulers() { // A corner drag from 200 x 140 to 300 x 210 document units; the box follows the pointer. diff --git a/crates/keymap/src/command.rs b/crates/keymap/src/command.rs index 92ef66207..ae0095f7e 100644 --- a/crates/keymap/src/command.rs +++ b/crates/keymap/src/command.rs @@ -1,5 +1,6 @@ //! Commands with parameters and their binding keys. +use std::borrow::Cow; use std::fmt; use serde::{Deserialize, Serialize}; @@ -33,15 +34,21 @@ impl CommandRef { /// The binding key: the id, or `id {json}` with object keys sorted and no spaces. `Null` and /// an empty object give the bare id. pub fn key(&self) -> String { + self.key_text().into_owned() + } + + /// [`key`](Self::key), borrowing the id when it is the whole key: a lookup by key of a command without parameters + /// allocates nothing. + pub fn key_text(&self) -> Cow<'_, str> { match &self.params { - Value::Null => self.id.clone(), - Value::Object(m) if m.is_empty() => self.id.clone(), + Value::Null => Cow::Borrowed(&self.id), + Value::Object(m) if m.is_empty() => Cow::Borrowed(&self.id), p => { let mut out = String::with_capacity(self.id.len() + 16); out.push_str(&self.id); out.push(' '); write_canonical(p, &mut out); - out + Cow::Owned(out) } } } diff --git a/crates/keymap/src/keymap.rs b/crates/keymap/src/keymap.rs index 7bcb8f0d9..47ef3320c 100644 --- a/crates/keymap/src/keymap.rs +++ b/crates/keymap/src/keymap.rs @@ -44,6 +44,13 @@ pub enum Lookup { Cycle(Vec), } +/// What a press runs, by catalog position. +enum Winners { + None, + Run(usize), + Cycle(Vec), +} + /// What to do with other commands that hold a chord being assigned. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] @@ -235,6 +242,11 @@ pub struct Keymap { current: Vec>, /// Effective trigger → (command, position in its `current` list), kept in step with `current`. by_trigger: HashMap>, + /// Each command's [`shown_chord`](Keymap::shown_chord), kept in step with `current`. A change to one command's + /// bindings can shadow or free another's chord, so every change rebuilds the whole table. + shown: Vec>, + /// How many times `shown` was built ([`Keymap::shown_builds`]). + shown_builds: u64, /// The overrides entry each command reads, when it has one. stored: Vec>, /// Whether the overrides hold a hand-written variant of a command's key @@ -262,6 +274,8 @@ impl Keymap { defaults: Vec::new(), current: Vec::new(), by_trigger: HashMap::new(), + shown: Vec::new(), + shown_builds: 0, stored: Vec::new(), variants: false, catalog_scopes: HashSet::new(), @@ -376,9 +390,18 @@ impl Keymap { /// [`lookup`](Self::lookup) with the panels around the focused one in `outer` ([`Scopes::rank_nested`]). pub fn lookup_nested(&self, chord: &Chord, double: bool, active: &Active, outer: &[&str]) -> Lookup { - let want = Trigger { chord: chord.effective(self.platform), double }; + let command = |i: usize| self.catalog[i].command.clone(); + match self.winners(Trigger { chord: chord.effective(self.platform), double }, active, outer) { + Winners::None => Lookup::None, + Winners::Run(i) => Lookup::Run(command(i)), + Winners::Cycle(cycle) => Lookup::Cycle(cycle.into_iter().map(command).collect()), + } + } + + /// The commands, by catalog position, that a press of the effective trigger `want` runs with `active` focus. + fn winners(&self, want: Trigger, active: &Active, outer: &[&str]) -> Winners { let held = active.typing && !self.typing.fires(&want.chord, self.platform); - let Some(holders) = self.by_trigger.get(&want) else { return Lookup::None }; + let Some(holders) = self.by_trigger.get(&want) else { return Winners::None }; // Each command's nearest rank; `holders` is in catalog order. let mut ranks: Vec<(usize, u8)> = Vec::new(); for &(i, k) in holders { @@ -392,16 +415,16 @@ impl Keymap { _ => ranks.push((i, r)), } } - let Some(best) = ranks.iter().map(|(_, r)| *r).min() else { return Lookup::None }; + let Some(best) = ranks.iter().map(|(_, r)| *r).min() else { return Winners::None }; let winners: Vec = ranks.iter().filter(|(_, r)| *r == best).map(|(i, _)| *i).collect(); match winners.as_slice() { - [] => Lookup::None, - [i] => Lookup::Run(self.catalog[*i].command.clone()), + [] => Winners::None, + [i] => Winners::Run(*i), [first, rest @ ..] => { if rest.iter().all(|j| self.same_group(*first, *j)) { - Lookup::Cycle(winners.iter().map(|i| self.catalog[*i].command.clone()).collect()) + Winners::Cycle(winners) } else { - Lookup::Run(self.catalog[*first].command.clone()) + Winners::Run(*first) } } } @@ -411,9 +434,20 @@ impl Keymap { /// home scope first, that runs it. A binding runs the command when the lookup of its chord, where the binding /// applies (an application binding with no panel focused, a panel binding with its panel focused, a context /// binding with its context active), gives the command or a cycle that holds it. `None` when every binding is - /// shadowed or the command has none. + /// shadowed or the command has none. Read from a table the keymap builds when its bindings change. pub fn shown_chord(&self, command: &CommandRef) -> Option { - let i = self.find(command)?; + self.find(command).and_then(|i| self.shown[i]) + } + + /// How many times the keymap worked out the chords it shows ([`shown_chord`](Self::shown_chord)): once when it is + /// built and once per change to its bindings, never per call. + #[doc(hidden)] + pub fn shown_builds(&self) -> u64 { + self.shown_builds + } + + /// [`shown_chord`](Self::shown_chord) of the command at catalog position `i`, from the bindings. + fn shown_of(&self, i: usize) -> Option { let home = &self.catalog[i].scope; let single = || self.current[i].iter().filter(|(trigger, _)| !trigger.double); let runs = |(trigger, scope): &&Bound| { @@ -423,45 +457,19 @@ impl Keymap { ScopeKind::Panel => Active::panel(name[0]), ScopeKind::Context => Active { panel: None, contexts: &name, typing: false }, }; - self.press_runs(&trigger.chord, &active, i) + match self.winners(Trigger { chord: trigger.chord.effective(self.platform), double: false }, &active, &[]) { + Winners::None => false, + Winners::Run(j) => j == i, + Winners::Cycle(cycle) => cycle.contains(&i), + } }; single().filter(|(_, scope)| scope == home).chain(single().filter(|(_, scope)| scope != home)).find(runs).map(|(trigger, _)| trigger.chord) } - /// Whether a single press of `chord` with `active` focus runs catalog entry `i`, alone or in a cycle: what - /// [`lookup`](Self::lookup) answers, decided on catalog positions without building the answer's commands. - /// [`shown_chord`](Self::shown_chord) asks it for each binding of every command a frame shows. - fn press_runs(&self, chord: &Chord, active: &Active, i: usize) -> bool { - let want = Trigger { chord: chord.effective(self.platform), double: false }; - let held = active.typing && !self.typing.fires(&want.chord, self.platform); - let Some(holders) = self.by_trigger.get(&want) else { return false }; - // Each command's nearest rank, as `lookup_nested` ranks them: `holders` is in catalog order, so a command's - // bindings are consecutive. - let ranked = || { - let mut out: Vec<(usize, u8)> = Vec::new(); - for &(j, k) in holders { - let Some(r) = self.at(j, k).and_then(|(_, s)| self.scopes.rank_nested(s, active, &[])) else { continue }; - if held && r != 0 { - continue; - } - match out.last_mut() { - Some((last, best)) if *last == j => *best = (*best).min(r), - _ => out.push((j, r)), - } - } - out - }; - let ranks = ranked(); - let Some(best) = ranks.iter().map(|(_, r)| *r).min() else { return false }; - let mut winners = ranks.iter().filter(|(_, r)| *r == best).map(|(j, _)| *j); - let Some(first) = winners.next() else { return false }; - let rest: Vec = winners.collect(); - if rest.is_empty() || !rest.iter().all(|j| self.same_group(first, *j)) { - // One winner, or several of different groups: the first runs. - return first == i; - } - // A cycle of the winners. - first == i || rest.contains(&i) + /// Rebuilds the table of shown chords from the current bindings. + pub(crate) fn index_shown(&mut self) { + self.shown = (0..self.current.len()).map(|i| self.shown_of(i)).collect(); + self.shown_builds += 1; } /// The command that holds `chord` for a surface that takes the key whatever has focus (a system menu item): the @@ -636,13 +644,9 @@ impl Keymap { } fn find(&self, command: &CommandRef) -> Option { - // A command without parameters is keyed by its id (`CommandRef::key`): look it up without building the key. - // Menu rows, tooltips and buttons ask for their chords on every frame. - match &command.params { - serde_json::Value::Null => self.index.get(command.id.as_str()).copied(), - serde_json::Value::Object(params) if params.is_empty() => self.index.get(command.id.as_str()).copied(), - _ => self.index.get(&command.key()).copied(), - } + // Menu rows, tooltips and buttons ask for their chords on every frame: a command without parameters is looked + // up without building its key. + self.index.get(command.key_text().as_ref()).copied() } fn resolve_key(&self, key: &str) -> Option { @@ -906,6 +910,7 @@ impl Keymap { *c = list; } self.index_command(i); + self.index_shown(); } fn index_command(&mut self, i: usize) { @@ -933,6 +938,7 @@ impl Keymap { for i in 0..self.current.len() { self.index_command(i); } + self.index_shown(); } /// Recomputes every command's bindings from the defaults and the overrides. diff --git a/crates/keymap/src/parity.rs b/crates/keymap/src/parity.rs index 37316cbee..aa901d1cf 100644 --- a/crates/keymap/src/parity.rs +++ b/crates/keymap/src/parity.rs @@ -62,6 +62,7 @@ impl Keymap { // new: gap 85; PhotoCraft's `bindings()` table lets tools share keys. pub fn with_shared_tool_keys(mut self, on: bool) -> Keymap { self.shared_tool_keys = on; + self.index_shown(); self } diff --git a/crates/keymap/tests/keymap.rs b/crates/keymap/tests/keymap.rs index 22b1b7cb5..7766e2830 100644 --- a/crates/keymap/tests/keymap.rs +++ b/crates/keymap/tests/keymap.rs @@ -2,7 +2,7 @@ use craft_keymap::{ Active, Binding, Chord, CommandDef, CommandRef, DropReason, Key, KeyInput, Keymap, Layout, Lookup, MAX_COMMANDS, Matcher, Mods, Overrides, - Platform, Press, Problem, Scope, Scopes, + Platform, Policy, Press, Problem, Scope, Scopes, }; use serde_json::json; @@ -97,6 +97,28 @@ fn a_command_shows_only_the_chords_the_lookup_runs_it_for() { assert_eq!(alone.shown_chord(&cmd("edit.settings")), None, "every key shadowed"); } +/// The shown chords are worked out when the bindings change, not per call, and follow every change: a key freed by one +/// command shows on the command it no longer shadows, and a stolen key leaves the command it was taken from. +#[test] +fn shown_chords_follow_binding_changes_and_reads_work_out_nothing() { + let catalog = vec![app("layer.hide", &["Cmd+,"]), app("edit.settings", &["Cmd+,", "Cmd+Alt+,"]), app("view.extras", &["Cmd+H"])]; + let mut km = Keymap::new(catalog, Scopes::new(), Platform::Mac); + let built = km.shown_builds(); + for _ in 0..100 { + assert_eq!(km.shown_chord(&cmd("edit.settings")), Some(chord("Cmd+Alt+,"))); + } + assert_eq!(km.shown_builds(), built, "reads work out no chord"); + + assert!(km.clear(&cmd("layer.hide"))); + assert_eq!(km.shown_chord(&cmd("edit.settings")), Some(chord("Cmd+,")), "the freed key shows on the command it no longer shadows"); + km.assign(&cmd("view.extras"), b("Cmd+,"), Policy::Steal).expect("steal"); + assert_eq!(km.shown_chord(&cmd("view.extras")), Some(chord("Cmd+H"))); + assert_eq!(km.shown_chord(&cmd("edit.settings")), Some(chord("Cmd+Alt+,")), "a stolen key leaves the command it was taken from"); + km.reset_all(); + assert_eq!(km.shown_chord(&cmd("layer.hide")), Some(chord("Cmd+,"))); + assert_eq!(km.shown_chord(&cmd("edit.settings")), Some(chord("Cmd+Alt+,"))); +} + #[test] fn overrides_write_the_map_form_unless_a_command_has_several_keys() { let mut o = Overrides::new(); diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index aecb29e2f..3907b35de 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -141,7 +141,7 @@ impl<'a> MenuBarUi<'a> { let entries = move || entries_of(bar_model, english); let mut bar = Bar::new(env.words::().label.clone(), titles).keyboard(self.keyboard.unwrap_or(target != Target::Mac)); if let Some(menu) = help { - bar = bar.help(MenuHelp::built(menu, &entries)); + bar = bar.help(MenuHelp::new(menu, &entries)); } MenuBarOutput { titles: bar.show(ui).titles } } diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 2d859408f..bc6ffb266 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -92,6 +92,25 @@ impl Lazy { /// Runs `add` in a child `Ui` placed in flow in `ui`, or takes the remembered extent there; `None` when it did not /// run. pub fn show(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option { + self.run(ui, |ui, _| add(ui)) + } + + /// [`show`](Self::show) for a child that may leave its room to other content: `add` runs first and settles; when + /// it returns `None`, `otherwise` runs in the same child `Ui` and the run is not kept, so a settling child runs + /// again in the next pass rather than replay it. A dock group's host view is one: where the host leaves the group + /// to the dock, the dock's group shows in its place and settles by its own rules. `None` when the child did not + /// run: it replayed a run of `add`, or was out of view. + pub fn show_or(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> Option, otherwise: impl FnOnce(&mut Ui) -> U) -> Option> { + self.run(ui, |ui, run| match add(ui) { + Some(shown) => Ok(shown), + None => { + run.unkept(ui.ctx()); + Err(otherwise(ui)) + } + }) + } + + fn run(self, ui: &mut Ui, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Option { let ctx = ui.ctx().clone(); let view = Env::of(ui).view().lazy_view(); let id = match view { @@ -149,17 +168,20 @@ impl Lazy { return None; } let mark = focus::mark(&ctx); - let records = self.settles && real; - if records { + let mut run = Run { recording: self.settles && real, kept: true, layer: place.layer }; + if run.recording { replay::open(&ctx); } let mut child = alloc::child(ui, UiBuilder::new().max_rect(available).layout(layout).scope_id(id)); // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. - let out = layout_memory::boundary(&ctx, false, || add(&mut child)); + let out = layout_memory::boundary(&ctx, false, || add(&mut child, &mut run)); let rect = child.min_rect(); // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); - let record = records.then(|| replay::close(&ctx, place.layer)); + let record = run.recording.then(|| replay::close(&ctx, place.layer)); + if !run.kept { + lazy::forget(&ctx, id); + } if real { layout_memory::backstop(&ctx, id, rect.size()); } @@ -179,3 +201,22 @@ impl Lazy { Some(out) } } + +/// The run of a child: whether it records what it adds for a replay, and whether it is kept. +struct Run { + recording: bool, + kept: bool, + layer: egui::LayerId, +} + +impl Run { + /// Ends the run's record here and keeps it from settling: what the child adds from here on is not what it settles + /// on. + fn unkept(&mut self, ctx: &egui::Context) { + if self.recording { + replay::close(ctx, self.layer); + self.recording = false; + } + self.kept = false; + } +} diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 9844a352b..0c3d7f8a7 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -70,6 +70,9 @@ 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. + gate_answers: HashMap, /// Command ids by number, so a state lookup allocates nothing. numbers: HashMap, this: HashMap, @@ -614,6 +617,7 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { board.last = std::mem::replace(&mut board.this, states); board.modal_published_last = std::mem::take(&mut board.modal_published); 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 @@ -798,12 +802,25 @@ fn resolve_in( // 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)); - (resolved, first_unknown, board.gate.clone()) + // 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) }); 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); } - if gate.is_some_and(|gate| !gate.allows(command)) { + 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) diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index e7f5ca7af..1570c4ae1 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -329,7 +329,8 @@ impl CommandInput { self } - /// The one gate over commands. + /// 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. #[must_use] pub fn gate(mut self, gate: CommandGate) -> Self { self.gate = Some(gate); diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 9df7a798c..8cefd9fb5 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -389,6 +389,15 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec }); } +/// Drops the kept run of the settling child `id`: its last run is not one it settles on, so it runs again. +pub(crate) fn forget(ctx: &Context, id: Id) { + with(ctx, |store, _, _| { + if let Some(entry) = store.entries.get_mut(&id) { + entry.settled = None; + } + }); +} + /// Whether the measure-only child `id` takes the size its last measuring run at `place` found, in place of measuring /// again, and that size. It does when that run was in this pass, or in an earlier frame and since then none of the /// settled rules a measure reads has broken (`settled`): nothing in it moves or asked to be shown again, no value it diff --git a/crates/ui-panels/src/docking/panels.rs b/crates/ui-panels/src/docking/panels.rs index bb1d9b206..a988978d6 100644 --- a/crates/ui-panels/src/docking/panels.rs +++ b/crates/ui-panels/src/docking/panels.rs @@ -39,7 +39,9 @@ pub trait DockPanels

{ /// The version of the app data `panel`'s body shows that the framework does not track (a document's revision, a /// job's progress). With one, the body settles (`Lazy::settles` with `Lazy::content`): it runs only when its /// version, its room or something the framework tracks in it changed, the pointer is over it or focus is in it, and - /// otherwise repaints its last run. `None` (the default) runs the body every pass. + /// otherwise repaints its last run. A [`group_view`](Self::group_view) settles the same way under the version of + /// the group's shown panel, its panels and its shown tab: the version covers what the view shows, and whether the + /// host takes the group depends only on its panels. `None` (the default) runs the body, and the view, every pass. fn content(&self, _panel: &P) -> Option { None } @@ -59,7 +61,8 @@ pub trait DockPanels

{ /// `GroupAt::Show(rect)` it shows its view in `ui`, which the dock holds to `rect` and clips to it; at /// `GroupAt::Measure(width)` it measures that view at `width` the way it shows it. It returns the height the view /// takes (at `Show`, the rect's). `None` (the default) leaves the group to the dock, at both. A canvas group uses - /// the panels to tell which document it holds and draws it in the room `ui` has. + /// the panels to tell which document it holds and draws it in the room `ui` has. At `Show` the view settles when + /// the shown panel has a [`content`](Self::content) version: a settled view repaints its last run instead of running. fn group_view(&mut self, _panels: &[P], _active: usize, _ui: &mut Ui, _at: GroupAt, _cx: &mut BodyCx<'_>) -> Option { None } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index b7759451b..902dda70e 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -891,25 +891,24 @@ impl Pass<'_, P> { let scene = self.scene; let anchor = members.first()?; let active = active.min(members.len() - 1); - let viewed = match at { - // The view draws in a child `Ui` held to the group's rect and clipped to it: it lays out in the group's - // room, never in the room the area has left. - GroupAt::Show(rect) => { - ui.scope_builder(UiBuilder::new().max_rect(rect), |ui| { - ui.shrink_clip_rect(rect); - self.panels.group_view(members, active, ui, at, body) - }) - .inner - } - GroupAt::Measure(_) => self.panels.group_view(members, active, ui, at, body), - }; - if let Some(height) = viewed { - return matches!(at, GroupAt::Measure(_)).then_some(height); + if let GroupAt::Measure(_) = at + && let Some(height) = self.panels.group_view(members, active, ui, at, body) + { + return Some(height); } let shown = &members[active]; + let content = self.panels.content(shown); + // A host view settles as a panel body does, under the shown panel's content version (`DockPanels::content`): + // it runs again when that version, the group's panels or the shown tab change. + let view_version = content.map(|content| { + use std::hash::Hasher; + let mut hasher = std::collections::hash_map::DefaultHasher::new(); + (content, members, active).hash(&mut hasher); + hasher.finish() + }); // The group settles when the host versions its specs and the shown body: it runs again when the pass's chrome // key, the body's version or how the group shows changes. - let version = scene.chrome.zip(self.panels.content(shown)).map(|(chrome, content)| { + let version = scene.chrome.zip(content).map(|(chrome, content)| { use std::hash::Hasher; let mut hasher = std::collections::hash_map::DefaultHasher::new(); (chrome, content, members, active, look.minimized, look.section, look.in_window).hash(&mut hasher); @@ -967,25 +966,49 @@ impl Pass<'_, P> { GroupAt::Show(rect) => rect, }; // One child `Ui` held to the group's rect, whether the group settles or not. It takes the parent's next id, as - // the group did before it settled, so a change of the group's first tab keeps every id inside; the Lazy is - // keyed by that id, unique among the groups of a dock in a scroll area too. + // the group did before it settled, so a change of the group's first tab keeps every id inside; each Lazy is + // keyed by its `Ui`'s id, unique among the groups of a dock in a scroll area too. The host view runs first and + // settles; where the host leaves the group to the dock, the group shows in its place and settles under its own + // version. let output = ui .scope_builder(UiBuilder::new().max_rect(rect), |ui| { - let lazy = Lazy::new(ui.unique_id(), 0.0).settles(version.is_some()); - let lazy = match version { - Some(version) => lazy.content(version), - None => lazy, + let view = Lazy::new(ui.unique_id(), 0.0).settles(view_version.is_some()); + let view = match view_version { + Some(version) => view.content(version), + None => view, }; - lazy.show(ui, |ui| { - let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output; - // `show_at` takes no room in flow; the run covers the group, so the pointer over it runs it again. - ui.expand_to_include_rect(rect); - output - }) + view.show_or( + ui, + |ui| { + // The view draws held to the group's rect and clipped to it: it lays out in the group's room, + // never in the room the area has left. + let taken = ui + .scope_builder(UiBuilder::new().max_rect(rect), |ui| { + ui.shrink_clip_rect(rect); + panels.borrow_mut().group_view(members, active, ui, at, body) + }) + .inner; + // The run covers the group, so the pointer over it runs the view again. + taken.map(|_| ui.expand_to_include_rect(rect)) + }, + |ui| { + let lazy = Lazy::new(ui.unique_id(), 0.0).settles(version.is_some()); + let lazy = match version { + Some(version) => lazy.content(version), + None => lazy, + }; + lazy.show(ui, |ui| { + let output = make(active, look.minimized).show_at(ui, rect, |ui, body| panel_body(&panels, shown, ui, body)).output; + // `show_at` takes no room in flow; the run covers the group, so the pointer over it runs it again. + ui.expand_to_include_rect(rect); + output + }) + }, + ) }) .inner; - // A settled group replayed its last run: nothing reached it. - let output = output?; + // A host view took the group, or a settled view or group replayed its last run: nothing reached it. + let output = output.and_then(Result::err).flatten()?; // The size `panel` floats at out of this group: the group's width, and the height the group measures at with // `panel` shown in a floating window's room, so content that fills the body takes that room. let fitted = |ui: &Ui, panel: &P| { diff --git a/crates/ui-patterns/tests/it/docking/runs.rs b/crates/ui-patterns/tests/it/docking/runs.rs index 376ef899c..158de715b 100644 --- a/crates/ui-patterns/tests/it/docking/runs.rs +++ b/crates/ui-patterns/tests/it/docking/runs.rs @@ -6,7 +6,7 @@ use craft_behavior::Axis; use craft_behavior::dock::{Action, Floating, Layout, Node, Permissions, SplitSize, Workspace}; use craft_ui::contract::{Bind, BodyCx, Role}; -use craft_ui::docking::{DockConfig, DockPanels, PanelDrag, PanelSpec}; +use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelDrag, PanelSpec}; use craft_ui::menu::PanelRow; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; @@ -121,6 +121,69 @@ fn a_panel_body_with_a_content_version_runs_only_when_its_version_changes() { assert_eq!(frame()[0], 0, "and it settles at it"); } +/// Panel 0's group is the host's view and panel 1's the dock's; both panels give the content version `version`. The +/// view counts its runs where it shows, the bodies theirs. +struct Hosted { + views: Rc>, + bodies: Rc>, + version: Rc>, +} + +impl DockPanels for Hosted { + fn spec(&self, panel: &usize) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } + + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) { + self.bodies.set(self.bodies.get() + 1); + } + + fn content(&self, _: &usize) -> Option { + Some(self.version.get()) + } + + fn group_view(&mut self, panels: &[usize], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + if !panels.contains(&0) { + return None; + } + match at { + GroupAt::Measure(_) => Some(0.0), + GroupAt::Show(rect) => { + self.views.set(self.views.get() + 1); + Some(rect.height()) + } + } + } +} + +/// A host view settles as a panel body does: it runs in the frame its panel's version changes or the pointer comes +/// over it, and not in a settled frame. The group the host leaves to the dock keeps showing beside it. +#[trial] +fn a_host_view_with_a_content_version_runs_only_when_its_version_changes() { + let (views, bodies, version) = (Rc::new(Cell::new(0)), Rc::new(Cell::new(0)), Rc::new(Cell::new(1))); + let root = Node::split(Axis::X, SplitSize::Ratio(0.5), Node::tabs(vec![0], 0), Node::tabs(vec![1], 0)); + let mut workspace = Workspace::new(Layout::new(Some(root), Vec::new())); + let mut panels = Hosted { views: Rc::clone(&views), bodies: Rc::clone(&bodies), version: Rc::clone(&version) }; + let mut fixture = Fixture::new(move |ui| { + DockArea::new("Dock", Bind::bound(&mut workspace), &mut panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(1200.0, 600.0)).settle(); + let mut frame = |events: Vec| { + views.set(0); + bodies.set(0); + fixture.frame(events); + (views.get(), bodies.get()) + }; + assert_eq!(frame(Vec::new()), (0, 0), "a settled frame runs neither the view nor the versioned body"); + assert_eq!(frame(Vec::new()), (0, 0), "nor the next one"); + version.set(2); + let (viewed, bodied) = frame(Vec::new()); + assert!(viewed > 0 && bodied > 0, "a new version runs the view and the body: {viewed}, {bodied}"); + assert_eq!(frame(Vec::new()), (0, 0), "both settle at it"); + assert!(frame(vec![moved(Pos2::new(300.0, 300.0))]).0 > 0, "the pointer over the view runs it"); + assert!(fixture.by_label("Panel 1").is_some(), "the dock's group shows beside the view"); +} + /// Panels whose specs and bodies all have versions, so the dock's chrome settles; `plain` is a panel whose body has /// none. struct Settling { diff --git a/crates/ui-shell/tests/it/commands/board.rs b/crates/ui-shell/tests/it/commands/board.rs index daf673588..63dfc001e 100644 --- a/crates/ui-shell/tests/it/commands/board.rs +++ b/crates/ui-shell/tests/it/commands/board.rs @@ -103,6 +103,36 @@ fn the_gate_may_resolve_commands() { 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-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index 26000173b..c8cdac79d 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -177,46 +177,21 @@ impl<'a> MenuTitle<'a> { #[non_exhaustive] pub struct MenuHelp<'a> { menu: usize, - entries: HelpEntries<'a>, -} - -/// Where the help search's commands come from: a list the caller built, or a builder the bar runs only while the -/// Help menu is open. -#[derive(Clone, Copy)] -enum HelpEntries<'a> { - Listed(&'a [HelpEntry]), - Built(&'a dyn Fn() -> Vec), + entries: &'a dyn Fn() -> Vec, } impl std::fmt::Debug for MenuHelp<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let entries = match self.entries { - HelpEntries::Listed(entries) => format!("{} listed", entries.len()), - HelpEntries::Built(_) => "built when opened".to_string(), - }; - f.debug_struct("MenuHelp").field("menu", &self.menu).field("entries", &entries).finish() + f.debug_struct("MenuHelp").field("menu", &self.menu).finish_non_exhaustive() } } impl<'a> MenuHelp<'a> { - /// A search field at the top of the menu `menu` (its position among the titles) over `entries`. - pub fn new(menu: usize, entries: &'a [HelpEntry]) -> Self { - MenuHelp { menu, entries: HelpEntries::Listed(entries) } - } - - /// A search field at the top of the menu `menu` over the commands `entries` builds. The bar runs it only in a pass - /// that shows the Help menu, so an app whose command list is costly to collect (every row of its menus) pays - /// nothing while the menu is closed. - pub fn built(menu: usize, entries: &'a dyn Fn() -> Vec) -> Self { - MenuHelp { menu, entries: HelpEntries::Built(entries) } - } - - /// The commands, built now for a builder. - fn entries(&self) -> std::borrow::Cow<'a, [HelpEntry]> { - match self.entries { - HelpEntries::Listed(entries) => std::borrow::Cow::Borrowed(entries), - HelpEntries::Built(build) => std::borrow::Cow::Owned(build()), - } + /// A search field at the top of the menu `menu` (its position among the titles) over the commands `entries` + /// lists. The bar runs it only in a pass that shows the Help menu, so an app whose command list is costly to + /// collect (every row of its menus) pays nothing while the menu is closed. + pub fn new(menu: usize, entries: &'a dyn Fn() -> Vec) -> Self { + MenuHelp { menu, entries } } } @@ -557,8 +532,8 @@ impl Component for MenuBar<'_> { let folder = cx.env.folder(); let texts = self.texts(&cx.env); let help = self.help; - // Only a pass that shows the Help menu needs its commands; a builder runs here and nowhere else. - let help_entries = help.filter(|help| opened == Some(Open::Title(help.menu))).map(|help| help.entries()); + // Only a pass that shows the Help menu needs its commands: the entries function runs here and nowhere else. + let help_entries = help.filter(|help| opened == Some(Open::Title(help.menu))).map(|help| (help.entries)()); let help_rows = help_entries.as_deref().map(|entries| Self::help_texts(entries, &cx.env, cx.env.words::().path_separator.as_str())); // The search starts empty each time the Help menu opens. diff --git a/crates/ui-widgets/src/menu/bar/stories.rs b/crates/ui-widgets/src/menu/bar/stories.rs index 0a44d16c8..849c39045 100644 --- a/crates/ui-widgets/src/menu/bar/stories.rs +++ b/crates/ui-widgets/src/menu/bar/stories.rs @@ -70,8 +70,9 @@ fn titles() -> Vec> { fn menu_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let size = *data.choice("size", ControlSize::Md, &[("Sm", ControlSize::Sm), ("Md", ControlSize::Md)]); let search = *data.value("search", true); + let entries = || HELP.clone(); let bar = MenuBar::new("Main menu", titles()).size(size); - let bar = if search { bar.help(MenuHelp::new(5, HELP.as_slice())) } else { bar }; + let bar = if search { bar.help(MenuHelp::new(5, &entries)) } else { bar }; bar.show(ui).into() } @@ -88,7 +89,8 @@ fn menu_bar_open(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { #[story(MenuBar<'static>, covers = [], drive = Drive::Never)] fn menu_bar_with_help_search(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { - MenuBar::new("Main menu", titles()).help(MenuHelp::new(5, HELP.as_slice())).show(ui).into() + let entries = || HELP.clone(); + MenuBar::new("Main menu", titles()).help(MenuHelp::new(5, &entries)).show(ui).into() } #[story(EditMenu, covers = [Default], drive = Drive::Never)] diff --git a/crates/ui-widgets/tests/it/menu/bar.rs b/crates/ui-widgets/tests/it/menu/bar.rs index 0dea99d4f..67bfe501f 100644 --- a/crates/ui-widgets/tests/it/menu/bar.rs +++ b/crates/ui-widgets/tests/it/menu/bar.rs @@ -38,8 +38,7 @@ fn rig(direction: Direction) -> Rig { MenuItem::new("&About").show(ui); }), ]; - let help = entries(); - MenuBar::new("Main menu", titles).help(MenuHelp::new(2, &help)).show(ui); + MenuBar::new("Main menu", titles).help(MenuHelp::new(2, &entries)).show(ui); }); // The in-window menu bar and its Alt, F10 and letter keys are PC behaviour: a Mac app's menu bar is native. fixture.os(Os::Linux); @@ -174,7 +173,7 @@ fn built_help_entries_are_collected_only_while_the_help_menu_shows() { counted.set(counted.get() + 1); entries() }; - MenuBar::new("Main menu", titles).help(MenuHelp::built(1, &build)).show(ui); + MenuBar::new("Main menu", titles).help(MenuHelp::new(1, &build)).show(ui); }); fixture.os(Os::Linux); fixture.settle(); diff --git a/crates/ui-widgets/tests/it/menu/pick_focus.rs b/crates/ui-widgets/tests/it/menu/pick_focus.rs index d3204ff14..f3a79134b 100644 --- a/crates/ui-widgets/tests/it/menu/pick_focus.rs +++ b/crates/ui-widgets/tests/it/menu/pick_focus.rs @@ -41,7 +41,7 @@ fn rig() -> Rig { MenuItem::new("&About").show(ui); }), ]; - let help = vec![HelpEntry::new(EditCommands::Undo, "Undo").with_path(["Edit"])]; + let help = || vec![HelpEntry::new(EditCommands::Undo, "Undo").with_path(["Edit"])]; MenuBar::new("Main menu", titles).help(MenuHelp::new(1, &help)).show(ui); let mut held = text.borrow_mut(); field.set(Some(TextField::new("Name", Bind::bound(&mut *held)).show(ui).response.id)); @@ -212,7 +212,7 @@ fn scoped_rig() -> ScopedRig { let titles = vec![MenuTitle::new("&Help", |ui| { MenuItem::new("&About").show(ui); })]; - let help = vec![HelpEntry::new(BarKeysCommand::Toggle, "Toggle")]; + let help = || vec![HelpEntry::new(BarKeysCommand::Toggle, "Toggle")]; MenuBar::new("Main menu", titles).help(MenuHelp::new(0, &help)).show(ui); craft_ui::layout_components::Stack::new().command_scope(::SCOPE).show(ui, |ui, cx| { while cx.take_command::().is_some() { diff --git a/migration/api-map/menus.toml b/migration/api-map/menus.toml index c909cf558..aef8c4049 100644 --- a/migration/api-map/menus.toml +++ b/migration/api-map/menus.toml @@ -220,7 +220,7 @@ new = "" [[setter]] type = "MenuBar" old = "help_search(usize)" -new = "help(MenuHelp::new(usize, &[HelpEntry]))" +new = "help(MenuHelp::new(usize, &dyn Fn() -> Vec))" [[setter]] type = "MenuBar"