diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs index 5052a1783..92276ae65 100644 --- a/crates/menu/tests/it/memo.rs +++ b/crates/menu/tests/it/memo.rs @@ -112,10 +112,12 @@ fn an_idle_bar_and_an_open_menu_build_no_labels() { fixture.key(Key::F, Modifiers::ALT); fixture.settle(); assert!(fixture.by_label("New").is_some(), "Alt+F opened File"); + fixture.key(Key::ArrowDown, Modifiers::NONE); + assert!(counted(&fixture).0 > 0, "a key in the open menu runs the bar"); + assert_eq!(label_builds(&fixture), 0, "and builds no labels"); for _ in 0..3 { fixture.frame(vec![]); - assert!(counted(&fixture).0 > 0, "the bar runs each pass while a menu is open"); - assert_eq!(label_builds(&fixture), 0, "and builds no labels"); + assert_eq!(label_builds(&fixture), 0, "an idle open menu builds no labels"); } } diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 0bf2e365b..fda2ccf1a 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -172,7 +172,12 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U }; let parent = overlay::drawing_parent(ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); - let spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting }; + let mut spec = LayerSpec { id: area, tier, at: placed.at, interactable: overlay.rank != Rank::Tooltip && !layer.exiting, root: None }; + // A popup's or a modal's layer, and any layer while it fades out, has a root node, made before its `Area` shows so + // egui hangs the layer's content below it. A sizing pass of the `Area` reports nothing. + if layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. }) { + spec.root = areas::content_rect(ctx, &spec).map(|rect| access::report_layer(ctx, layer.id, rect, overlay.rank.is_modal(), layer.exiting)); + } // The opener of the layer's scope is the stop focused when the layer first appears: egui's modal gate takes focus // from the widgets below a modal layer by the first pass that shows the layer. A dropdown that keeps its anchor's key // focus belongs to the component that opened it: a press moves the key focus onto that component only at the end of @@ -199,8 +204,8 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U // from the opener's inherited env with the layer-local fields fresh, and outside the opener's scopes. let installed = Env::install_for(ui, layer.env.capture().env()); let real = !ui.is_sizing_pass(); - if real && (layer.exiting || matches!(overlay.rank, Rank::Popup | Rank::Modal { .. })) { - access::report_layer(ctx, layer.id, ui.unique_id(), ui.max_rect(), overlay.rank.is_modal(), layer.exiting); + if spec.root.is_some() && layer.exiting { + access::hide_exiting_content(ctx, ui.unique_id()); } // Every layer is a focus scope, one without a policy (`FocusPolicy::NONE`) included: its stops are the layer's, // not those of the scope it was opened in, so a trap around it leaves them out (a menu's companion bar). @@ -237,6 +242,10 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U entry.absorbs = overlay.dismiss.outside == Outside::Absorb; overlay::record(ctx, entry); let dismissed = if layer.exiting { None } else { dismissal(ctx, layer, shown.rect, anchor, scope, &mut memory) }; + // The layer closes after its body ran: the run shows it open, so a record of the run is not replayed. + if dismissed.is_some() { + crate::runtime::replay::note_unsettled(ctx); + } if let Some(nudge) = &nudge { // `dismissal` above records the press beside the layer (`dismissal.rs`, `note_pressed_outside`), so the nudge // starts after it and moves the layer from the next pass on. diff --git a/crates/ui-contract/src/contract/steps/value.rs b/crates/ui-contract/src/contract/steps/value.rs index 0618346c3..e3e265fb8 100644 --- a/crates/ui-contract/src/contract/steps/value.rs +++ b/crates/ui-contract/src/contract/steps/value.rs @@ -10,12 +10,11 @@ use craft_behavior::{CancelReason, EditEvent, Gesture, Mixed, Value}; use egui::{Context, Id}; use std::sync::Arc; -/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the pass its value -/// step last ran in, the `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased +/// What a component showed last pass, in one shown slot under its id: the shown copy of its value, the +/// `(hovered, focus_visible)` that `PartsCx::hovered` and `focus_visible` read, and its eased /// hover, press and on. pub(crate) struct Shown { pub copy: Option>, - pub drawn: u64, pub state: ShownState, } @@ -38,13 +37,13 @@ impl ShownState { impl Clone for Shown { fn clone(&self) -> Self { - Shown { copy: self.copy.clone(), drawn: self.drawn, state: self.state.clone() } + Shown { copy: self.copy.clone(), state: self.state.clone() } } } impl Default for Shown { fn default() -> Self { - Shown { copy: None, drawn: 0, state: ShownState::default() } + Shown { copy: None, state: ShownState::default() } } } @@ -99,10 +98,9 @@ fn resolve_value(comp: &mut dyn ValueSource, stage: &mut MemoryStag let slot = gesture_key(id); let (serial, all_reason) = crate::runtime::edit::latest(stage.ctx()); let mut cancelled = None; - // A component not drawn for a pass loses its press at the end hook; its running gesture ends here, the first pass it is - // drawn again. - let pass_nr = crate::runtime::pointer::pass_of(stage.ctx()); - let removed = std::mem::replace(&mut stage.shown::>(id).drawn, pass_nr).saturating_add(1) < pass_nr; + // A component not shown for a pass, by a run or a replay of one, loses its press at the end hook; its running gesture + // ends here, the first pass it is shown again. + let removed = !crate::runtime::memory::shown_last_pass(stage.ctx(), id); if stage.shown::>(slot).is_running() { // `(given, value)` of a single-valued binding the app owns. let host = comp.binding().and_then(|bind| match bind.get() { diff --git a/crates/ui-contract/src/runtime/access.rs b/crates/ui-contract/src/runtime/access.rs index 1f80642c2..516bf849f 100644 --- a/crates/ui-contract/src/runtime/access.rs +++ b/crates/ui-contract/src/runtime/access.rs @@ -22,10 +22,12 @@ pub use crate::runtime::egui::access::bounds; #[doc(hidden)] pub use emit::SubDecl; #[doc(hidden)] +pub use emit::layer_root; +#[doc(hidden)] pub use emit::report_sub; #[doc(hidden)] pub use emit::sub_node_id; -pub(crate) use emit::{FaceFacts, Own, PopupShown, report, report_layer}; +pub(crate) use emit::{FaceFacts, Own, PopupShown, hide_exiting_content, report, report_layer}; pub use live::announce; pub(crate) use live::{begin_pass as begin_live_pass, end_pass as end_live_pass}; pub use scope::{FieldLabel, FieldLabelRole}; diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index 13560dd25..4dad0be30 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -52,7 +52,7 @@ pub(crate) struct Own<'a> { /// A popup an anchor shows this pass. #[derive(Clone, Copy, Debug)] pub(crate) struct PopupShown { - /// The popup's layer id: the id of its root node. + /// The popup's layer id (its root node is [`layer_root`]'s). pub id: Id, pub kind: PopupKind, pub open: bool, @@ -257,7 +257,7 @@ pub(crate) fn report(ctx: &Context, own: &Own<'_>) { let expanded = expanded_of(own.flags, access.expanded.or_else(|| popup.filter(|_| !own.popups_by_part).map(|popup| popup.open))); let mut relations = access.relations.clone(); relations.labelled_by.extend(name.labelled_by.iter().copied()); - relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| popup.id)); + relations.controls.extend(own.popups.iter().filter(|popup| popup.open).map(|popup| layer_root(popup.id))); let numeric = access.numeric.as_ref(); let mut spec = NodeSpec::new(own.role); spec.rect = Some(own.rect); @@ -419,19 +419,28 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { } } -/// The root node of an overlay layer: the layer's content attaches below it, and a modal layer's root is modal. An -/// exiting layer's root is hidden from the first pass it fades out, so nothing under it is reported while it still -/// paints; the ids stay the same if the layer reopens. -pub(crate) fn report_layer(ctx: &Context, id: Id, content: Id, rect: Rect, modal: bool, exiting: bool) { - adapter::register_layer_parent(ctx, content, id); +/// The id of the root node of the overlay layer `id`. The root has an id of its own: the layer's container component +/// takes the layer's id for its widget and node, inside the layer's content, which attaches below the root. +pub fn layer_root(id: Id) -> Id { + sub(id, "layer") +} + +/// Writes the root node of the overlay layer `id`, whose content takes `rect`, and returns its id. The layer's content +/// hangs below it, and a modal layer's root is modal. An exiting layer's root is hidden from the first pass it fades +/// out, so nothing under it is reported while it still paints; the ids stay the same if the layer reopens. Called +/// before the layer's `Area` shows, which egui hangs below the root. +pub(crate) fn report_layer(ctx: &Context, id: Id, rect: Rect, modal: bool, exiting: bool) -> Id { + let root = layer_root(id); let mut spec = NodeSpec::layer_root(); spec.rect = Some(rect); spec.modal = modal; spec.hidden = exiting; - write_node(ctx, id, &spec); - if exiting { - // The content `Ui` can attach to the viewport rather than to the root (a popup body that names its own - // parent), so it is hidden itself. - adapter::hide(ctx, content); - } + write_node(ctx, root, &spec); + root +} + +/// Hides the node of the content `Ui` of an exiting overlay layer: a popup body that names its own parent can hang +/// its content outside the layer's root. +pub(crate) fn hide_exiting_content(ctx: &Context, content: Id) { + adapter::hide(ctx, content); } diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index f6d4b3fb6..8e0a23986 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -211,14 +211,35 @@ pub(crate) fn register_parent(ctx: &Context, id: Id, parent: Id) { emit(ctx, id); } -/// `register_parent` for the content `Ui` of an overlay layer, which attaches to the layer's root node. The content is -/// neither a widget nor a node, so egui's records of the run hold no parent for it: a replay of the run registers it -/// again. A parent egui's records hold is never journaled: they hold its last value, which a replayed earlier call -/// would overwrite. -pub(crate) fn register_layer_parent(ctx: &Context, content: Id, root: Id) { - crate::runtime::replay::journal(ctx, || (content, root), |ctx, &(content, root)| register_layer_parent(ctx, content, root)); - ctx.register_accesskit_parent(content, root); - with_emitted(ctx, |emitted| emitted.emit(content)); +/// The trials' pass-end check that egui's AccessKit parents of the pass hold no cycle; panics naming the ids of the +/// first one found. egui places a node under the first ancestor that has a node by walking the parents, which a cycle +/// sends into endless recursion when no node of the cycle exists yet: a replay adds a run's nodes in the order they +/// were created, and a run only tolerates a cycle while some node of it already exists. +#[cfg(feature = "testing")] +pub(crate) fn check_parents_acyclic(ctx: &Context) { + let cycle = ctx.with_accesskit_parents(|parents| { + let mut acyclic = IdSet::default(); + for &start in parents.keys() { + let mut path: Vec = Vec::new(); + let mut on_path = IdSet::default(); + let mut at = Some(start); + while let Some(id) = at.filter(|id| !acyclic.contains(id)) { + if !on_path.insert(id) { + let from = path.iter().position(|on| *on == id).unwrap_or_default(); + return Some(path.split_off(from)); + } + path.push(id); + at = parents.get(&id).copied(); + } + acyclic.extend(path); + } + None + }); + let cycle = cycle.flatten(); + assert!( + cycle.is_none(), + "the AccessKit parents of the pass hold a cycle: {cycle:?}, each the parent of the one before and the first the parent of the last" + ); } /// Notes that the runtime emitted the node of `id`. diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index 56ec89afe..a27b7a8b1 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -212,6 +212,9 @@ pub(crate) struct LayerSpec { pub at: Pos2, /// Whether the layer takes input; a tooltip and the ghost layer never do. pub interactable: bool, + /// The accessibility node the layer's content hangs under, created before the layer shows: egui attaches the + /// layer's `Area`, and through it the content, below it. + pub root: Option, } /// What `show_layer` reports. @@ -226,17 +229,20 @@ pub(crate) struct LayerShown { /// service fades a layer in (`motion::layer_presence`), so egui's own fade-in of a new `Area` is off. pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut egui::Ui)) -> LayerShown { let mut sizing = false; - let shown = egui::Area::new(spec.id) + let mut area = egui::Area::new(spec.id) .fade_in(false) .order(spec.tier.order()) .pivot(egui::Align2::LEFT_TOP) .fixed_pos(spec.at) .constrain(false) - .interactable(spec.interactable) - .show(ctx, |ui| { - sizing = ui.is_sizing_pass(); - body(ui); - }); + .interactable(spec.interactable); + if let Some(root) = spec.root { + area = area.accessibility_parent(root); + } + let shown = area.show(ctx, |ui| { + sizing = ui.is_sizing_pass(); + body(ui); + }); register_area(ctx, shown.response.layer_id, sizing); // The `Area`'s own widget senses a click over the whole layer, beneath the layer's widgets: it stands for none of // the layer's components. @@ -244,6 +250,12 @@ pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut LayerShown { rect: shown.response.rect, layer: shown.response.layer_id } } +/// The rect the content of the layer `spec` shows takes in this pass, before the layer shows: its left-top and the size +/// egui keeps for its `Area`. `None` when the layer shows in an egui sizing pass, which paints and reports nothing. +pub(crate) fn content_rect(ctx: &Context, spec: &LayerSpec) -> Option { + egui::AreaState::load(ctx, spec.id).and_then(|state| state.size).map(|size| Rect::from_min_size(spec.at, size)) +} + /// What an overlay layer's `Area` keeps in egui's memory for a pass it shows in: its egui layer, its left-top in /// screen space, its size and whether it takes input. #[derive(Clone, Copy, Debug, PartialEq)] @@ -278,7 +290,7 @@ fn register_area(ctx: &Context, layer: LayerId, sizing: bool) { } fn show_again(ctx: &Context, area: &AreaRecord) { - crate::runtime::replay::journal(ctx, || *area, |ctx, area| show_again(ctx, area)); + crate::runtime::replay::journal(ctx, || *area, show_again); crate::runtime::replay::note_overlay(ctx, area.layer, Rect::from_min_size(area.at, area.size)); let became = egui::AreaState::load(ctx, area.layer.id).and_then(|state| state.last_became_visible_at); let state = egui::AreaState { diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index df63cb27a..072ab185f 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -745,6 +745,8 @@ pub(crate) fn end_pass(ui: &mut Ui) { for prune in prunes { prune(&ctx, &live); } + #[cfg(feature = "testing")] + crate::runtime::egui::access::check_parents_acyclic(&ctx); RUNNING.with(|running| { let mut running = running.borrow_mut(); if let Some(at) = running.iter().rposition(|pass| pass.ctx == ctx) { diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs index 06e41f4fd..a4d543eeb 100644 --- a/crates/ui-contract/src/runtime/inputs.rs +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -1,7 +1,7 @@ //! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, its presses, the -//! window's facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held, the events sent -//! to the focus, the requests to collections), each with a generation -//! that moves when its value changes. The accessor that reads one notes it into the records open around the running +//! window's facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the toast queues, the keys held, +//! the events sent to the focus, the requests to collections), each with a generation that moves when its value +//! changes. The accessor that reads one notes it into the records open around the running //! code (`replay::note_input`); a memoized view's replay is refused when an input its run read has another generation //! now (`runtime::lazy::settled`), so a change runs only the views that read it, and a view absent while it changed //! runs when it is shown again. @@ -43,6 +43,9 @@ pub(crate) enum Input { Sent, /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). Overlays, + /// The cards queued in the running viewport's toast queues (`toast::cards`): a post, a close or an expiry runs the + /// views that show them. + Toasts, /// The requests to collections from outside them (`items::request_rename`), read by the item step that takes /// them, so a pending request runs the view that takes it. Requests, @@ -51,7 +54,7 @@ pub(crate) enum Input { } impl Input { - pub(crate) const ALL: [Input; 13] = [ + pub(crate) const ALL: [Input; 14] = [ Input::Modifiers, Input::Pointer, Input::Press, @@ -63,6 +66,7 @@ impl Input { Input::Focus, Input::Sent, Input::Overlays, + Input::Toasts, Input::Requests, Input::Scroll, ]; @@ -130,9 +134,9 @@ pub(crate) fn observe(ctx: &Context, input }); } -/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers) are -/// observed here, and so are the events sent to the focus, which the key stage counts; the pointer, its presses and -/// the modifiers by the pointer's begin hook, the window facts and the layout where the frame's root env is built, the +/// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers, toast +/// queues) are observed here, and so are the events sent to the focus, which the key stage counts; the pointer, its +/// presses and the modifiers by the pointer's begin hook, the window facts and the layout where the frame's root env is built, the /// keymap by the command board, the requests by each request. pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { match input { @@ -141,6 +145,7 @@ pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { Input::Drag => observe(ctx, input, crate::runtime::drag::state(ctx)), Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)), Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)), + Input::Toasts => observe(ctx, input, crate::runtime::toast::queued(ctx)), Input::Keymap => return crate::runtime::commands::keymap_built(ctx), Input::Modifiers | Input::Pointer | Input::Press | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {} } diff --git a/crates/ui-contract/src/runtime/keys/claims.rs b/crates/ui-contract/src/runtime/keys/claims.rs index 13ec85cf2..874f05c6d 100644 --- a/crates/ui-contract/src/runtime/keys/claims.rs +++ b/crates/ui-contract/src/runtime/keys/claims.rs @@ -55,6 +55,8 @@ pub fn claim(ctx: &Context, owner: Id, chord: Chord) { #[doc(hidden)] pub fn capture(ctx: &Context, owner: Id, chord: Chord) { crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| capture(ctx, owner, chord)); + // The captured chord reaches `owner` wherever the focus is: a run that captures reads what is sent. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent); current(ctx, |stage| { if !stage.captures.contains(&(owner, chord)) { stage.captures.push((owner, chord)); diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index 27ed98177..a7667d012 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -203,6 +203,8 @@ struct OwnerRecord { viewport: ViewportId, pass: u64, at: f64, + /// The pass of the owner's registration before `pass`, in the same viewport. + before: Option, } /// One entry the runtime keeps for a component, and the owner that is tested for its eviction. @@ -270,11 +272,28 @@ pub(crate) fn register_owner(ctx: &Context, owner: Id) { crate::runtime::replay::note_owner(ctx, owner); let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { - reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now }); + let before = match reg.owners.get(&owner) { + Some(last) if last.viewport == facts.viewport && last.pass == facts.pass_nr => last.before, + Some(last) if last.viewport == facts.viewport => Some(last.pass), + _ => None, + }; + reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now, before }); reg.ended.remove(&owner); }); } +/// Whether `owner` was registered in the pass before the running one of its viewport, by a run or a replay: its +/// component was shown there. +pub(crate) fn shown_last_pass(ctx: &Context, owner: Id) -> bool { + let facts = frame::facts(ctx); + pass_state::with::(ctx, |reg| { + reg.owners.get(&owner).filter(|last| last.viewport == facts.viewport).is_some_and(|last| { + let shown = if last.pass == facts.pass_nr { last.before } else { Some(last.pass) }; + shown.is_some_and(|shown| shown + 1 >= facts.pass_nr) + }) + }) +} + /// The generation of ended shown lives now: a kept run stores it, and `ended_since` compares with it. pub(crate) fn ended_generation(ctx: &Context) -> u64 { pass_state::with::(ctx, |reg| reg.ended_generation) diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index 9f73466f1..f52cfa571 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -395,6 +395,9 @@ impl Driver<'_> { let sizing = self.stage.is_peek(); let now = frame::clock(ctx); let existing = if sizing { store::peek_clone::>(ctx, id) } else { store::take::>(ctx, id) }; + // A tween that moves in this pass (a new target, also one it jumps to, or a step, also its last one) leaves the + // slot in another state than the run found it in, which the next run reads (`layer_fading` among others). + let moved = existing.as_ref().is_some_and(|tween| tween.target() != target || !tween.is_settled()); let mut tween = match existing { Some(tween) => tween, None => { @@ -407,7 +410,7 @@ impl Driver<'_> { self.advance(&mut tween, target, spec, now); let shown = tween.shown(); if !sizing { - if !tween.is_settled() { + if moved || !tween.is_settled() { note_unsettled(ctx); } store::put(ctx, id, tween); diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index efa4b4df3..2ec9e5ccc 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -314,10 +314,11 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { facts.discards |= discard_requests(ctx) > open.discards; let focus = focus::transcript(ctx, open.focus); let widgets = egui.widgets().iter().map(|widget| widget.id).collect(); - // A run that ends holding focus reads what is sent to it: the next key, text, IME, clipboard or AccessKit event runs - // it, wherever the framework routes that event. + // A run that ends holding focus reads where the focus is and what is sent to it: a focus move, and the next key, + // text, IME, clipboard or AccessKit event wherever the framework routes it, run it. let held = Held::focused(ctx).within(&focus, &widgets); if held.any() { + facts.inputs.insert(Input::Focus); facts.inputs.insert(Input::Sent); } Record { focus, journal, widgets, held, egui, facts } diff --git a/crates/ui-contract/src/runtime/toast.rs b/crates/ui-contract/src/runtime/toast.rs index be51a8b36..4649ad0b9 100644 --- a/crates/ui-contract/src/runtime/toast.rs +++ b/crates/ui-contract/src/runtime/toast.rs @@ -285,14 +285,22 @@ pub fn keep(ctx: &Context, id: ToastId) { } } -/// The cards of the window `window` in the running viewport, oldest first. +/// The cards of the window `window` in the running viewport, oldest first. A tracked input (`Input::Toasts`). pub fn cards(ctx: &Context, window: &WindowKey) -> Vec { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Toasts); PerViewport::::with(ctx, pass::current_viewport(ctx), |queue| { let cards = queue.windows.iter().find(|(key, _)| key == window); cards.map_or_else(Vec::new, |(_, live)| live.iter().map(|live| live.card.clone()).collect()) }) } +/// The ids of the cards each window of the running viewport queues: what `Input::Toasts` observes. +pub(crate) fn queued(ctx: &Context) -> Vec<(WindowKey, Vec)> { + PerViewport::::with(ctx, pass::current_viewport(ctx), |queue| { + queue.windows.iter().map(|(key, live)| (key.clone(), live.iter().map(|live| live.card.id).collect())).collect() + }) +} + /// Every live viewport's cards with their windows, oldest first, for `ui.inspect`; `cards` is the running viewport's. pub fn snapshot(ctx: &Context) -> Vec<(WindowKey, Card)> { let mut cards = Vec::new(); diff --git a/crates/ui-contract/src/testing/access.rs b/crates/ui-contract/src/testing/access.rs index 2d05eb316..e6e343f64 100644 --- a/crates/ui-contract/src/testing/access.rs +++ b/crates/ui-contract/src/testing/access.rs @@ -3,6 +3,7 @@ use crate::runtime::access::{FieldLabel, scope}; use egui::{Context, Id}; +pub use crate::runtime::access::layer_root; pub use crate::runtime::egui::access::{AccessTree, Declared, NodeKey, prune_controls}; /// The AccessKit tree a finished pass of a viewport produced, taken out of its output; empty when it made none. diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 5a5d33116..48724fcfe 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -15,6 +15,7 @@ use craft_ui::runtime::env::{BodyMode, RevealEdge, ShellCx, WindowKey}; use craft_ui::runtime::focus::Initial; use craft_ui::runtime::memory::{SaveKey, set_saved_value}; use craft_ui::runtime::{frame, inspect}; +use craft_ui::testing::access::{NodeKey, layer_root}; use craft_ui::testing::in_audit_run; use craft_ui::testing::input::key_press; use craft_ui::testing::layout::{allocate, in_region, measured_block}; @@ -1272,6 +1273,13 @@ fn a_view_in_a_popover_fills_its_width_as_without_the_view() { const POPOVER_AT: Pos2 = Pos2::new(60.0, 60.0); const AWAY: Pos2 = Pos2::new(700.0, 500.0); +/// Frames with motion off: a layer opens and closes in one frame, with no fade that runs its view. +fn still_frames() -> Frames { + let mut frames = Frames::new(); + frames.root(craft_ui::runtime::env::RootEnv::default().motion(craft_behavior::MotionMode::Off)); + frames +} + /// A popover the view shows, holding a line of text and a button; the focus stays where it was, so nothing in it holds /// the focus. #[derive(MemoProps)] @@ -1304,12 +1312,12 @@ impl HintScene { ran.map(|(name, _, _)| short_name(name)).collect() } - fn settled(frames: &mut Frames) -> HintScene { - let mut scene = HintScene { open: true, row: None }; + /// An open popover after the frames that settle it. The scene stays where it is made: its binding's place is part + /// of the view's key. + fn settle(&mut self, frames: &mut Frames) { for _ in 0..SETTLE { - scene.frame(frames, vec![]); + self.frame(frames, vec![]); } - scene } } @@ -1321,8 +1329,9 @@ fn any_open(frames: &Frames) -> bool { /// runs, the layer stays open and on top under its row, and its AccessKit node keeps its id and parent. #[trial] fn an_open_popover_without_focus_replays_with_its_layer() { - let mut frames = Frames::new(); - let mut scene = HintScene::settled(&mut frames); + let mut frames = still_frames(); + let mut scene = HintScene { open: true, row: None }; + scene.settle(&mut frames); let row = scene.row.expect("the popover shows its row"); let layer = frames.ctx.layer_id_at(row.center()).expect("the popover's layer is under its row"); let dialog = |frames: &mut Frames| { @@ -1344,32 +1353,36 @@ fn an_open_popover_without_focus_replays_with_its_layer() { /// The pointer onto the popover's row runs the view in that frame. #[trial] fn the_pointer_over_a_replayed_popover_runs_its_view() { - let mut frames = Frames::new(); - let mut scene = HintScene::settled(&mut frames); + let mut frames = still_frames(); + let mut scene = HintScene { open: true, row: None }; + scene.settle(&mut frames); let row = scene.row.expect("the popover shows its row").center(); assert_eq!(scene.frame(&mut frames, vec![moved(row)]), ["Hint"], "the pointer onto the row runs the view"); } -/// An outside press closes a replaying popover in the press frame; the view runs at most once more and then replays +/// An outside press closes a replaying popover in the press frame; the view runs at most twice more and then replays /// with no layer open. #[trial] fn an_outside_press_closes_a_replaying_popover() { - let mut frames = Frames::new(); - let mut scene = HintScene::settled(&mut frames); + let mut frames = still_frames(); + let mut scene = HintScene { open: true, row: None }; + scene.settle(&mut frames); scene.frame(&mut frames, vec![moved(AWAY)]); assert!(scene.frame(&mut frames, vec![]).is_empty(), "the view replays with the pointer away"); assert_eq!(scene.frame(&mut frames, vec![press(AWAY), release(AWAY)]), ["Hint"], "the press runs the view"); assert!(!scene.open, "the outside press closed the popover in its frame"); - let after: Vec> = (0..WARM).map(|_| scene.frame(&mut frames, vec![])).collect(); - assert!(after.iter().skip(1).all(Vec::is_empty), "the view runs at most once after the close: {after:?}"); + // The first run after the close finds the layer's presence still open and settles it; the next one shows nothing. + let after: Vec> = (0..=WARM).map(|_| scene.frame(&mut frames, vec![])).collect(); + assert!(after.iter().skip(2).all(Vec::is_empty), "the view runs at most twice after the close: {after:?}"); assert!(!any_open(&frames), "no layer is open"); } /// A close of every popup from outside the view (a command's) closes a replaying popover in the next frame. #[trial] fn closing_the_popups_closes_a_replaying_popover() { - let mut frames = Frames::new(); - let mut scene = HintScene::settled(&mut frames); + let mut frames = still_frames(); + let mut scene = HintScene { open: true, row: None }; + scene.settle(&mut frames); craft_ui::runtime::overlay::close_popups(&frames.ctx); assert_eq!(scene.frame(&mut frames, vec![]), ["Hint"], "the queued close runs the view"); assert!(!scene.open, "the close reached the popover"); @@ -1378,8 +1391,9 @@ fn closing_the_popups_closes_a_replaying_popover() { /// A window resize runs a view that shows a popover once, and the popover stays inside the new window; then it replays. #[trial] fn a_window_resize_runs_a_popover_view_once() { - let mut frames = Frames::new(); - let mut scene = HintScene::settled(&mut frames); + let mut frames = still_frames(); + let mut scene = HintScene { open: true, row: None }; + scene.settle(&mut frames); frames.screen(Vec2::new(1000.0, 700.0)); let resized: Vec> = (0..WARM).map(|_| scene.frame(&mut frames, vec![])).collect(); assert_eq!(resized.iter().filter(|ran| !ran.is_empty()).count(), 1, "the resize runs the view once: {resized:?}"); @@ -1404,7 +1418,7 @@ fn typing(props: &mut Typing<'_>, ui: &mut Ui) { /// field in their frame, and an idle frame after each replays the view. #[trial] fn events_sent_to_a_replaying_focused_field_reach_it_in_their_frame() { - let mut frames = Frames::new(); + let mut frames = still_frames(); let mut text = String::new(); let frame = |frames: &mut Frames, events: Vec, text: &mut String| { frames.frame(events, |ui| { @@ -1432,6 +1446,91 @@ fn events_sent_to_a_replaying_focused_field_reach_it_in_their_frame() { } } +/// A popover the view shows, holding a line of text; returns the popover's id. +fn rooted(props: &mut Hint<'_>, ui: &mut Ui) -> Option { + let popover = Popover::new("Rooted", props.open.reborrowed()).at_point(POPOVER_AT).initial_focus(Initial::KeepAnchor); + let shown = popover.show(ui, |ui, _| Text::new("Rooted").show(ui)); + shown.output.open.then_some(shown.output.response.id) +} + +/// The nodes above `key` in `tree`, nearest first. +fn ancestors(tree: &craft_ui::testing::access::AccessTree, key: NodeKey) -> Vec { + let keys = tree.keys(); + let mut above = Vec::new(); + let mut at = key; + while let Some(parent) = keys.iter().copied().find(|parent| tree.children_of(*parent).contains(&at)) { + above.push(parent); + at = parent; + } + above +} + +/// A popover in a view hangs below its layer's root node, which has its own id, in the run and in each replay: the +/// pass's AccessKit parents hold no cycle (every trial's pass-end check), and a replay adds the nodes where the run did. +#[trial] +fn a_popover_in_a_view_hangs_below_its_layer_root() { + let mut frames = still_frames(); + let mut open = true; + let mut popover = None; + let mut frame = |frames: &mut Frames| { + frames.frame(vec![], |ui| popover = MemoView::new("rooted", Hint { open: Bind::bound(&mut open) }, rooted).show(ui).flatten()); + let ran = last_frame_memo_runs(&frames.ctx).into_iter().any(|(_, _, run)| run == MemoRun::Ran); + let id = popover.expect("the popover is open"); + let tree = frames.tree(); + (ran, ancestors(&tree, NodeKey::of(id)), NodeKey::of(layer_root(id))) + }; + let (ran, above, root) = frame(&mut frames); + assert!(ran, "the first frame runs the view"); + assert!(above.contains(&root), "the popover hangs below its layer's root: {above:?}, root {root:?}"); + for _ in 0..SETTLE { + frame(&mut frames); + } + let (ran, replayed, _) = frame(&mut frames); + assert!(!ran, "an idle frame replays the view"); + assert_eq!(replayed, above, "the replay adds the popover's node where the run did"); +} + +/// What the toast view shows: the main window's toasts, over the view's room. +#[derive(MemoProps)] +struct Notices { + corner: bool, +} + +fn notices(_: &mut Notices, ui: &mut Ui) { + let body = ui.max_rect(); + craft_ui::notices::ToastStack::show(ui, &WindowKey::main(), body); +} + +/// A toast posted to a view that shows the toasts runs the view in the next frame, which opens the toast layer; then +/// the view replays the layer, and the layer stack and egui's layer order hold. +#[trial] +fn a_toast_opening_runs_its_view_in_its_frame_then_replays() { + let mut frames = still_frames(); + let frame = |frames: &mut Frames| { + frames.frame(vec![], |ui| { + MemoView::new("notices", Notices { corner: true }, notices).show(ui); + }); + last_frame_memo_runs(&frames.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran).count() + }; + for _ in 0..SETTLE { + frame(&mut frames); + } + assert_eq!(frame(&mut frames), 0, "an idle frame with no toast replays the view"); + craft_ui::runtime::toast::post(&frames.ctx, &WindowKey::main(), craft_ui::runtime::toast::Toast::new("Saved").timeout(None)); + let runs: Vec = (0..=WARM).map(|_| frame(&mut frames)).collect(); + // The run that opens the toast asks for the discard pass that places the layer by its size, which runs it again. + assert!(runs[0] > 0, "the post runs the view in the next frame: {runs:?}"); + assert!(runs[1..].iter().all(|ran| *ran == 0), "then the view replays: {runs:?}"); + assert!(painted(&frames, "Saved"), "the replayed toast is painted"); + let stack = |frames: &Frames| (craft_ui::runtime::overlay::top(&frames.ctx), frames.ctx.memory(|memory| memory.layer_ids().collect::>())); + let held = stack(&frames); + assert!(held.0.is_some(), "the toast layer is open"); + for _ in 0..WARM { + assert_eq!(frame(&mut frames), 0, "an idle frame replays the view"); + assert_eq!(stack(&frames), held, "the layer stack and egui's layer order hold"); + } +} + #[derive(MemoProps)] struct Centred { label: String,