diff --git a/crates/menu/tests/it/memo.rs b/crates/menu/tests/it/memo.rs index 614a6d891..5052a1783 100644 --- a/crates/menu/tests/it/memo.rs +++ b/crates/menu/tests/it/memo.rs @@ -1,5 +1,5 @@ //! The in-window bar is a memoized view: idle frames replay it, a title rename or Alt runs it once, and an open menu -//! runs it while it is open. +//! replays with it while nothing reaches the menu. use std::cell::RefCell; use std::rc::Rc; @@ -67,18 +67,26 @@ fn alt_runs_the_menu_bar_once_each_way() { assert_eq!(counted(&fixture).0, 1, "Alt up runs the bar once"); } -/// A menu the bar opens is an overlay inside its run, which keeps the run from being replayed while it is open. The -/// run in which the menu's fade ends is the last that shows it, so the replays after it match a real run (the audit). +/// A menu the bar opens is an overlay of its run: with the focus on the menu's first row, an idle frame replays the bar +/// and the open menu, and a key the menu takes runs the bar in its frame. #[trial] -fn an_open_menu_runs_the_bar_and_closing_it_replays_it() { +fn an_idle_open_menu_replays_and_a_key_in_it_runs_the_bar() { let bar = Rc::new(RefCell::new(model("File"))); let mut fixture = fixture(&bar); audit_replays(fixture.ctx(), true); fixture.key(Key::F, Modifiers::ALT); fixture.settle(); assert!(fixture.by_label("New").is_some(), "Alt+F opened File"); + for _ in 0..3 { + fixture.frame(vec![]); + assert_eq!(counted(&fixture), (0, 1), "an idle frame replays the bar and its open menu"); + assert!(fixture.by_label("New").is_some(), "the replayed menu keeps its rows' nodes"); + } + fixture.key(Key::ArrowDown, Modifiers::NONE); + assert!(counted(&fixture).0 > 0, "a key in the open menu runs the bar in its frame"); + fixture.settle(); fixture.frame(vec![]); - assert!(counted(&fixture).0 > 0, "the bar runs while a menu is open"); + assert_eq!(counted(&fixture), (0, 1), "then the bar replays again"); // The first Escape closes the menu; the bar keeps the keyboard until the second one hands it back. fixture.key(Key::Escape, Modifiers::NONE); fixture.settle(); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index fffb18b1d..705634221 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -15,15 +15,22 @@ use std::sync::Arc; /// it adds that run again (paint, widgets, accessibility nodes, focus stops and the other per-pass /// registrations) and returns what that run returned. It runs in a pass where its key differs, or where any of these /// holds: -/// - the pointer is over it or was in its last run, a press started on it, or one of its widgets is dragged or holds -/// focus, or did; +/// - the pointer is over it or an overlay layer it shows, or was in its last run, a press started on either, or one of +/// its widgets is dragged, or was; +/// - the focus moved into, out of or within it, or, while the focus is in it, a key, text, IME, clipboard or AccessKit +/// event came; /// - an intent of the pass is routed to a component in it (an AccessKit request on one of its nodes); /// - an animation in it is not at its end, a texture it shows is still loading, something in it asked for a repaint /// (`frame::request_repaint`), or a wake time it asked for came; /// - a bound value, inspection record or command state it read changed; /// - its place differs from its last run (see below), or the shown life of a component it showed ended; -/// - its last run asked for a discard pass or did something a replay cannot repeat (an overlay, paint on another -/// layer). +/// - it shows an overlay layer and a press came anywhere, a close waits for the layer, or the layers or the window's +/// safe rect changed; +/// - its last run asked for a discard pass or did something a replay cannot repeat (paint on a layer that is neither +/// its own nor an overlay it shows, a window of another viewport). +/// +/// An overlay it shows is part of its run: a replay shows the layer again, with its paint, widgets, nodes, focus scope +/// and layer stack entry, at the place of the run. A view that shows one replays only at the room and clip it ran in. /// /// Input elsewhere in the window and repaint requests outside it do not run it: what they change in the data it shows /// reaches it through its props. diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index eb8b2635c..54fee68fb 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -337,6 +337,8 @@ impl Host for ViewportHost { return; } let ctx = parent.ctx().clone(); + // The window's content runs in its own viewport's pass, which no record of this one holds. + crate::runtime::replay::block(&ctx); let focus = self.overlay.focus; let mut window_rules = self.overlay.clone(); window_rules.dismiss.outside = Outside::Keep; diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index b6790cd12..2b1ae4b38 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -75,8 +75,7 @@ pub(super) fn dismissal( /// Whether a primary press landed outside the layer, its anchor and the layers opened from inside it. fn press_outside(ctx: &Context, layer: &Layer<'_>, rect: Rect, anchor: Rect) -> bool { - let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) - else { + let Some(press) = pointer::primary_press(ctx) else { return false; }; let inside_family = overlay::family(ctx, layer.id).iter().filter_map(|id| overlay::entry(ctx, *id)).any(|entry| entry.rect.contains(press)); @@ -104,6 +103,8 @@ fn escape(ctx: &Context, layer: &Layer<'_>, scope: Option, inside: if inside != Some(true) && !(owns_loose && focus_in_no_layer(ctx)) { return None; } + // The focus may be in no record of the layer's host: the Escape is read from the events of the frame. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Sent); let step = keys::scope_escape(ctx, policy.cancel, pointer::press_captured(ctx), false)?; matches!(step, craft_behavior::focus::EscapeStep::CloseScope).then_some(CloseReason::Escape) } diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index 9c2ab20fc..0bf2e365b 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -342,6 +342,8 @@ impl Nudge { /// The layer-stack side of an OS-window mount: records the window as an entry of its viewport's stack (rank, key /// class, scope; no egui layer) and decides its dismissal after the body ran. `rect` is the window's inner rect. pub(crate) fn host_window(ctx: &Context, layer: &Layer<'_>, rect: Rect) -> LayerOut { + // The entry stands for a window of another viewport, whose pass no record of this one holds. + crate::runtime::replay::block(ctx); let overlay = layer.overlay; let mut memory = recall(layer, ctx); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); diff --git a/crates/ui-contract/src/runtime/access/emit.rs b/crates/ui-contract/src/runtime/access/emit.rs index 1631aefad..13560dd25 100644 --- a/crates/ui-contract/src/runtime/access/emit.rs +++ b/crates/ui-contract/src/runtime/access/emit.rs @@ -423,7 +423,7 @@ pub fn report_sub(ctx: &Context, decl: &SubDecl<'_>) { /// 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_parent(ctx, content, id); + adapter::register_layer_parent(ctx, content, id); let mut spec = NodeSpec::layer_root(); spec.rect = Some(rect); spec.modal = modal; diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index be6d1ac13..f6d4b3fb6 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -167,8 +167,10 @@ pub(crate) fn pass_through(ctx: &Context, id: Id) { }); } -/// Reports `id` as the focused node of this pass. +/// Reports `id` as the focused node of this pass. A replay of the run that reported it reports it again: a view that +/// holds focus replays while nothing reaches it. pub(crate) fn set_focus(ctx: &Context, id: Id) { + crate::runtime::replay::journal(ctx, || id, |ctx, &id| set_focus(ctx, id)); with_emitted(ctx, |emitted| emitted.focus_set = true); ctx.set_accesskit_focus(id); } @@ -209,6 +211,16 @@ 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)); +} + /// Notes that the runtime emitted the node of `id`. fn emit(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| emitted.emit(id)); diff --git a/crates/ui-contract/src/runtime/egui/areas.rs b/crates/ui-contract/src/runtime/egui/areas.rs index bf7c2d9be..56ec89afe 100644 --- a/crates/ui-contract/src/runtime/egui/areas.rs +++ b/crates/ui-contract/src/runtime/egui/areas.rs @@ -1,5 +1,6 @@ //! `Area` with its left-top pivot, `Order`, sublayers, transform layers and `set_layer_order`. +use crate::runtime::shift::Shift; #[cfg(feature = "testing")] use egui::Ui; use egui::emath::TSTransform; @@ -224,6 +225,7 @@ pub(crate) struct LayerShown { /// Shows an overlay layer: an `Area` with its left-top pivot at `spec.at`, never egui's default pivot. The motion /// 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) .fade_in(false) .order(spec.tier.order()) @@ -231,13 +233,64 @@ pub(crate) fn show_layer(ctx: &Context, spec: &LayerSpec, body: impl FnOnce(&mut .fixed_pos(spec.at) .constrain(false) .interactable(spec.interactable) - .show(ctx, body); + .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. crate::runtime::pointer::record_layer_widget(ctx, shown.response.id); LayerShown { rect: shown.response.rect, layer: shown.response.layer_id } } +/// 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)] +struct AreaRecord { + layer: LayerId, + at: Pos2, + size: Vec2, + interactable: bool, +} + +/// A replay moves the left-top; the size stays. +impl Shift for AreaRecord { + fn shifted(&self, by: &egui::RecordShift) -> Self { + AreaRecord { at: self.at.shifted(by), ..*self } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + AreaRecord { at: self.at.snapped(&to.at, within), ..*self } + } +} + +/// Registers the `Area` of `layer` that was shown now (an egui sizing pass of it when `sizing`) as an overlay of the +/// records open around it, which journal the registration: a replay shows the area again in egui's memory, as shown +/// this pass with the place, size and input it had, so egui finds the layer and orders it. A sizing pass paints +/// nothing and asks for the next pass, so the run that made it runs again. +fn register_area(ctx: &Context, layer: LayerId, sizing: bool) { + let Some(state) = egui::AreaState::load(ctx, layer.id) else { return }; + if sizing { + crate::runtime::replay::note_unsettled(ctx); + } + show_again(ctx, &AreaRecord { layer, at: state.left_top_pos(), size: state.size.unwrap_or_default(), interactable: state.interactable }); +} + +fn show_again(ctx: &Context, area: &AreaRecord) { + crate::runtime::replay::journal(ctx, || *area, |ctx, area| show_again(ctx, area)); + 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 { + pivot_pos: Some(area.at), + pivot: egui::Align2::LEFT_TOP, + size: Some(area.size), + interactable: area.interactable, + last_became_visible_at: became, + }; + ctx.memory_mut(|memory| memory.areas_mut().set_state(area.layer, state)); +} + /// What [`show_cover_layer`] shows: the layer's id and tier, the `screen` it covers, its `scrim`, the `through` canvas /// left open, and whether it `absorbs` pointer hits. pub(crate) struct CoverLayer { @@ -263,6 +316,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { Some(clear) => bands(screen, clear).into_iter().filter(|band| band.is_positive()).collect(), None => vec![screen], }; + let mut sizing = false; egui::Area::new(id) .fade_in(false) .order(tier.order()) @@ -272,6 +326,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { .interactable(absorbs) .sense(Sense::hover()) .show(ctx, |ui| { + sizing = ui.is_sizing_pass(); for rect in covered { ui.painter().rect_filled(rect, 0.0, scrim); let absorber = ui.allocate_rect(rect, Sense::click_and_drag()); @@ -279,6 +334,7 @@ pub(crate) fn show_cover_layer(ctx: &Context, cover: CoverLayer) { crate::runtime::egui::access::hide(ui.ctx(), absorber.id); } }); + register_area(ctx, layer_of(tier, id), sizing); } /// The four rects of `screen` around `hole`: above, below, left of and right of it. @@ -297,8 +353,15 @@ pub(crate) fn layer_rect(ctx: &Context, id: Id) -> Option { } /// The viewport's safe rect: the room overlays must stay inside, the part of the content rect the user can see on -/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. +/// the monitor and above its taskbar. Without a known monitor size it is the whole content rect. A tracked input +/// (`Input::Shell`), which the frame's root env observes. pub(crate) fn safe_rect(ctx: &Context) -> Rect { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Shell); + safe_rect_raw(ctx) +} + +/// `safe_rect` without noting the read: for the root env, which moves `Input::Shell` by it. +pub(crate) fn safe_rect_raw(ctx: &Context) -> Rect { let content = ctx.content_rect(); ctx.input(|input| { let viewport = input.viewport(); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 00c95d128..c0f132239 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -514,8 +514,9 @@ impl Env { let shell = Arc::new(windows::shell_of(ctx, pass::current_viewport(ctx))); let active = shell.window.active; let keyboard = Arc::new(crate::runtime::keys::layout_of(ctx)); - // The window facts and the layout are tracked inputs: a view that read them runs when they change. - crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, (*shell).clone()); + // The window facts, the safe rect and the layout are tracked inputs: a view that read them runs when they change. + let safe = crate::runtime::egui::areas::safe_rect_raw(ctx); + crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Shell, ((*shell).clone(), safe)); crate::runtime::inputs::observe(ctx, crate::runtime::inputs::Input::Keyboard, (*keyboard).clone()); let words = host_words(ctx, host.as_ref()); let key = EnvKey::new(tokens.key(), root.direction, scale, os, active, root.values.style_hash()) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index ac9e6f5ab..1adf515be 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -386,7 +386,8 @@ pub(crate) fn replay(ctx: &Context, transcript: &Transcript) { with(ctx, |state| { let placed = transcript.placed(state.open.last().map(|(id, _)| *id)); for (id, mut scope) in placed.scopes { - // No replayed scope has a noted opener: an overlay, which notes one, blocks its record. + // A replayed scope keeps the opener the last pass held: an overlay's scope, the one kind that notes an opener, + // took it in the pass that first showed the layer, which ran. scope.opener = opener(state, id, None, focused); if scope.entering.is_none() { state.seen.insert(id, frame); diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index b6804a2b8..df63cb27a 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -633,7 +633,9 @@ pub(crate) fn input_hook(ctx: &Context, input: &mut RawInput) { // H0: one press per pass. let frame = pass::frame_nr(ctx, viewport); let held_back = PerViewport::::with(ctx, viewport, |record| raw_input::hold_back_presses(&mut events, frame, &mut record.held)); - // H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. + // H3: the key stage strips what the runtime owns; egui decides on a repaint from the events left. The events sent + // to the focus are counted first, before the IME and key stages take theirs. + keys::count_sent(ctx, viewport, &events); ime::input_hook(ctx, &mut events, viewport); let (stripped, later) = keys::input_hook(ctx, input, &mut events); if !later.is_empty() { diff --git a/crates/ui-contract/src/runtime/ime.rs b/crates/ui-contract/src/runtime/ime.rs index 0e19f1a6d..48705289b 100644 --- a/crates/ui-contract/src/runtime/ime.rs +++ b/crates/ui-contract/src/runtime/ime.rs @@ -373,8 +373,14 @@ pub(crate) fn composing(ctx: &Context, owner: Id) -> bool { current(ctx, |engine| engine.owner == Some(owner) && engine.composing) } -/// Records the caret rect for the OS candidate window. +/// Records the caret rect for the OS candidate window. A replay of the run that recorded it records it again, so the +/// pass writes the IME output and the OS keeps the IME open for a focused field that replays. pub(crate) fn note_caret(ctx: &Context, owner: Id, field: Rect, caret: Rect, password: bool) { + crate::runtime::replay::journal( + ctx, + || (owner, field, caret, password), + |ctx, &(owner, field, caret, password)| note_caret(ctx, owner, field, caret, password), + ); current(ctx, |engine| engine.caret = Some((owner, field, caret, password))); } diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs index 27f75e78a..06e41f4fd 100644 --- a/crates/ui-contract/src/runtime/inputs.rs +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -1,6 +1,6 @@ -//! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, the window's -//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held, the requests to -//! collections), each with a generation +//! 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 //! 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 @@ -21,9 +21,14 @@ pub(crate) enum Input { Modifiers, /// The pointer's frame (`pointer::frame`, `pointer::with_pass_pointer`). Pointer, + /// The pointer's presses and releases, an outside press the layer stack absorbed included (`pointer::primary_press`, + /// `overlay::absorbed_press`): a layer's dismissal reads them, so a press anywhere runs the views that show layers, + /// and a pointer move does not. + Press, /// The keys held, Caps Lock and whether a key arrived (`keys::input::down`, `keyed`, `lock_keys::caps_lock`). Keys, - /// The platform and window facts (`EnvView::shell`). + /// The platform and window facts (`EnvView::shell`) and the viewport's safe rect (`areas::safe_rect`): its + /// content rect and the visible part of its monitor. Shell, /// The keyboard layout (`EnvView::keyboard_layout`). Keyboard, @@ -33,6 +38,9 @@ pub(crate) enum Input { Drag, /// Where key focus is (`focus::focused_rec`, `focus_in_scope`, `commands::focus_within`). Focus, + /// The key, text, IME, clipboard and AccessKit action events of the frame: a run that ends holding focus reads them + /// (`replay::close`), so any such event runs the views the focus is in, and an idle frame replays them. + Sent, /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). Overlays, /// The requests to collections from outside them (`items::request_rename`), read by the item step that takes @@ -43,15 +51,17 @@ pub(crate) enum Input { } impl Input { - pub(crate) const ALL: [Input; 11] = [ + pub(crate) const ALL: [Input; 13] = [ Input::Modifiers, Input::Pointer, + Input::Press, Input::Keys, Input::Shell, Input::Keyboard, Input::Keymap, Input::Drag, Input::Focus, + Input::Sent, Input::Overlays, Input::Requests, Input::Scroll, @@ -121,16 +131,18 @@ 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; the pointer 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. +/// 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 { Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(ctx)), + Input::Sent => observe(ctx, input, crate::runtime::keys::sent(ctx)), 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::Keymap => return crate::runtime::commands::keymap_built(ctx), - Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {} + Input::Modifiers | Input::Pointer | Input::Press | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {} } with(ctx, |generations| generations.gens[input as usize]) } diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index f8d80f3f1..b4a350730 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -27,7 +27,7 @@ pub use claims::take_claimed; pub(crate) use claims::take_first_claimed; /// The types `Intents` reads and returns, for an app that reads the window's intents (`with_window_intents`). pub use craft_behavior::{AccessRequest, Intent, MoveMods, NavMove, PartRef}; -pub(crate) use input::{claims_press, input_hook, keys_state, queue_nav, take_menu_keys, take_nav}; +pub(crate) use input::{claims_press, count_sent, input_hook, keys_state, queue_nav, sent, take_menu_keys, take_nav}; #[doc(hidden)] pub use input::{down, keyed}; pub use intents::Intents; @@ -242,6 +242,8 @@ pub(crate) struct Stage { down: Vec, /// The input hook read a key press, typed text or a clipboard event in this pass, withheld ones included. keyed: bool, + /// How many inputs of the viewport held an event sent to the focus (`count_sent`). + sent: u64, /// The keys whose press the strip took and whose release it is still to drop. consumed: Vec, shortcuts: Shortcuts, diff --git a/crates/ui-contract/src/runtime/keys/claims.rs b/crates/ui-contract/src/runtime/keys/claims.rs index 587c00366..13ec85cf2 100644 --- a/crates/ui-contract/src/runtime/keys/claims.rs +++ b/crates/ui-contract/src/runtime/keys/claims.rs @@ -2,6 +2,8 @@ use super::current; use craft_keymap::Chord; + +crate::stays!(Chord); use egui::{Context, Id}; /// Reads the claimed chord: whether it arrived this pass for `id`, consuming it. Also true for a chord @@ -32,8 +34,10 @@ pub(crate) fn take_first_claimed(ctx: &Context, id: Id, chords: &[Chord]) -> Opt }) } -/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component. +/// Records that `owner` has an open edit run: the next Escape cancels the run and stays with the component. Like the +/// claims below, a replay of the run that recorded it records it again: a focused view replays while nothing reaches it. pub(crate) fn hold_escape(ctx: &Context, owner: Id) { + crate::runtime::replay::journal(ctx, || owner, |ctx, &owner| hold_escape(ctx, owner)); current(ctx, |stage| stage.open_edits.push(owner)); } @@ -41,6 +45,7 @@ pub(crate) fn hold_escape(ctx: &Context, owner: Id) { /// component. #[doc(hidden)] pub fn claim(ctx: &Context, owner: Id, chord: Chord) { + crate::runtime::replay::journal(ctx, || (owner, chord), |ctx, &(owner, chord)| claim(ctx, owner, chord)); current(ctx, |stage| stage.claims.push((owner, chord))); } @@ -49,6 +54,7 @@ pub fn claim(ctx: &Context, owner: Id, chord: Chord) { /// keys, Enter and Escape (the window move and size modes, 16.3); the claim lapses when it is not renewed. #[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)); current(ctx, |stage| { if !stage.captures.contains(&(owner, chord)) { stage.captures.push((owner, chord)); diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index 78074d5fb..d508086ee 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -593,6 +593,33 @@ pub(crate) fn keys_state(ctx: &Context) -> (Vec, bool, bool) { (down, keyed, crate::runtime::lock_keys::caps_on(ctx)) } +/// Counts an input of `viewport` whose `events` hold one sent to the focus: a key, text, IME, clipboard or AccessKit +/// action event (`Input::Sent`). Read before any stage takes events, so the IME's and the ones a shortcut takes count. +pub(crate) fn count_sent(ctx: &Context, viewport: ViewportId, events: &[Arrived]) { + let sent = events.iter().any(|arrived| { + matches!( + arrived.event, + egui::Event::Key { .. } + | egui::Event::Text(_) + | egui::Event::Ime(_) + | egui::Event::Copy + | egui::Event::Cut + | egui::Event::Paste(_) + | egui::Event::PasteImage(_) + | egui::Event::MiddleClickPaste { .. } + | egui::Event::AccessKitActionRequest(_) + ) + }); + if sent { + with(ctx, viewport, |stage| stage.sent += 1); + } +} + +/// How many inputs of the running viewport held an event sent to the focus: its value moves with each one. +pub(crate) fn sent(ctx: &Context) -> u64 { + current(ctx, |stage| stage.sent) +} + /// Whether the running viewport's input hook read a key press, typed text or a clipboard event in this pass, the ones /// the key stage took from egui's input included: an app that redraws state after input asks this, not egui's events. pub fn keyed(ctx: &Context) -> bool { diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index a2fba430f..01d898b5e 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -15,7 +15,7 @@ //! framework tracks has changed for it since (`settled`). Its entry outlives a few frames of absence. use crate::runtime::egui::areas::Layer; -use crate::runtime::egui::{focus as focus_state, input as input_state, pass}; +use crate::runtime::egui::{input as input_state, pass}; use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame::{self, PerViewport}; use crate::runtime::inputs::{self, Input}; @@ -193,9 +193,10 @@ struct Moved { impl Place { /// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its - /// size, the layer, layout, scale, font atlas and environment are the ones the run had. The record moves by the - /// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there - /// gives) and, for a move, the record holds nothing a move cannot place (`movable`: no paint callback) on an + /// size, the layer, layout, scale, font atlas and environment are the ones the run had. A record that shows an + /// overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the room's move + /// when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and, + /// for a move, the record holds nothing a move cannot place (`Record::movable`: no paint callback) on an /// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow /// the clip when either: /// - the clip moved with the room (`with_clip`): every rect and clip moves exactly, whatever the clip cut; @@ -204,7 +205,7 @@ impl Place { /// so the run's clip becomes the clip now and inner clips move (`RecordShift::clip`). /// /// Otherwise it runs: a run cut by its clip lacks what was culled. - fn shift_to(&self, rect: Rect, now: Place, movable: bool, transformed: bool) -> Option { + fn shift_to(&self, rect: Rect, now: Place, record: &Record, transformed: bool) -> Option { let offset = now.room.min - self.room.min; let same = now.room.size() == self.room.size() && now.layer == self.layer @@ -212,7 +213,11 @@ impl Place { && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas && now.env == self.env; - let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed); + let placeable = if record.pinned() { + offset == Vec2::ZERO && now.clip == self.clip + } else { + offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && record.movable() && !transformed) + }; if !same || !placeable { return None; } @@ -454,9 +459,11 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then: /// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no texture it shows still /// loading, no wake time reached; -/// - the pointer is not over it, no press started on it and none of its widgets is dragged or holds egui focus, and -/// none of that held in its last run; -/// - none of its stops holds focus or is the target of a focus request, now or in its last run; +/// - the pointer is not over it or an overlay layer it shows, no press started on either and none of its widgets is +/// dragged, and none of that held in its last run; +/// - the focus is where its run left it (`replay::Held`: the same stop and egui widget of it, or none), and while the +/// focus is in it no key, text, IME, clipboard or AccessKit event came (`Input::Sent`, which such a run reads); +/// - none of its stops is the target of a focus request, now or in its last run; /// - no intent of this pass is routed to a component in it (an AccessKit request on one of its nodes); /// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or, /// replaying a run of this frame, after that run started; @@ -467,8 +474,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is /// gone; /// - no framework input its run read outside its props has moved (`runtime::inputs`), the scroll view a nested `Lazy` -/// child of it decided by is the same (moved with it, `moved`), and no command waits for a command scope instance of -/// it. +/// child of it decided by is the same (moved with it, `moved`), no command waits for a command scope instance of +/// it, and no close waits for a layer it shows. pub(crate) fn settled( ctx: &Context, owner: Option, @@ -478,10 +485,11 @@ pub(crate) fn settled( view: Option, key: Key, ) -> Option<(Vec2, Rect, RecordShift)> { - let targets = focus::targets(ctx); + let revealed = focus::targets(ctx)[1]; let routed = crate::runtime::keys::routed_to(ctx); let now = frame::clock(ctx); - let held = (input_state::dragged(ctx), focus_state::focused(ctx)); + let dragged = input_state::dragged(ctx); + let focused = replay::Held::focused(ctx); let transformed = place.is_some_and(|place| ctx.layer_transform_to_global(place.layer).is_some()); let settled = write(ctx, id, |store, pass_nr, frame| { let changes = &store.changes; @@ -501,9 +509,10 @@ pub(crate) fn settled( && !facts.blocked && !facts.discards && facts.quiet(now, edited.as_ref()) - && !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop)) || routed.contains(&stop)) + && !settled.record.focus.stop_ids().any(|stop| revealed == Some(stop) || routed.contains(&stop)) && !routed.iter().any(|id| settled.record.widgets.contains(id)) - && ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget)) + && !dragged.is_some_and(|widget| settled.record.widgets.contains(&widget)) + && focused.within(&settled.record.focus, &settled.record.widgets) == settled.record.held }); entry.replays = Some((pass_nr, replays)); replays @@ -511,7 +520,7 @@ pub(crate) fn settled( }; // A measuring run cannot tell the place: it replays where the run was. let moved = |settled: &Settled| match place { - Some(place) => settled.place.shift_to(settled.rect, place, settled.record.movable(), transformed), + Some(place) => settled.place.shift_to(settled.rect, place, &settled.record, transformed), None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }), }; let settled = entry.settled.clone().filter(|_| replays).and_then(|settled| Some((moved(&settled)?, settled))); @@ -534,7 +543,7 @@ pub(crate) fn settled( // The scroll view a nested child decided by: the run's, moved with the record, while the clip moved with it; a run // that lay wholly in its clip ran every nested child, which holds at any view. let view = place.and_then(|_| with_clip.then(|| (settled.view.map(|ran| ran.moved(shift.offset)), view))); - if engaged(ctx, settled.place.layer, rect.intersect(shift.clip)) + if engaged(ctx, settled.place.layer, rect.intersect(shift.clip), &settled.record.facts.overlays) || crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives) || moved(ctx, &settled, view) { @@ -551,20 +560,26 @@ pub(crate) fn settled( /// Whether something a memoized view's run read outside its props moved since: a framework input it read has another /// generation, the scroll view a nested `Lazy` child decided by is another than the one it needs (`view`: the view it /// needs and the view now, in a real run whose record replays only in that view; a measuring run lays the content out -/// from offset zero, so its view is not the one the real run decided by), or a command waits for one of its instances. +/// from offset zero, so its view is not the one the real run decided by), a command waits for one of its instances, +/// or a close waits for a layer it shows. fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option)>) -> bool { let facts = &settled.record.facts; inputs::moved(ctx, facts.inputs, &settled.seen) || (facts.inputs.contains(Input::Scroll) && view.is_some_and(|(needs, now)| needs != now)) || crate::runtime::commands::queued_for(ctx, &facts.instances) + || crate::runtime::overlay::close_queued(ctx, &facts.layers) } -/// Whether the pointer is over `rect` (shown) on `layer`, or a press that is held started there. Both halves ask -/// whether `layer` is the top layer at the point, so a pointer or a press on an overlay above the view leaves it alone. -fn engaged(ctx: &Context, layer: Layer, rect: Rect) -> bool { - let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); - ctx.rect_contains_pointer(layer, rect) - || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) +/// Whether the pointer is over `rect` (shown) on `layer` or over one of the overlay layers `overlays` shown, or a +/// press that is held started there. Both halves ask whether the layer is the top layer at the point, so a pointer or +/// a press on an overlay above the view leaves it alone. +fn engaged(ctx: &Context, layer: Layer, rect: Rect, overlays: &[replay::ShownLayer]) -> bool { + let over = |layer: Layer, rect: Rect| { + let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); + ctx.rect_contains_pointer(layer, rect) + || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) + }; + over(layer, rect) || overlays.iter().any(|shown| over(shown.layer, shown.rect)) } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` @@ -630,11 +645,11 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec if ctx.will_discard() { return; } - let targets = focus::targets(ctx); - let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))); + let revealed = focus::targets(ctx)[1]; + let engaged_now = record.focus.stop_ids().any(|stop| revealed == Some(stop)); let lives = crate::runtime::memory::ended_generation(ctx); let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, key, pass: 0, edits, output, lives, seen, view }; - settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip)); + settled.engaged |= engaged(ctx, place.layer, rect.intersect(place.clip), &settled.record.facts.overlays); with(ctx, |store, pass_nr, frame| { settled.frame = frame; settled.pass = pass_nr; diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index d43456fd0..be4d8185a 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -9,6 +9,7 @@ use crate::runtime::egui::pass; use crate::runtime::frame::{PassStep, PerViewport, Stamped}; use crate::runtime::pass_state; use crate::runtime::pointer; +use crate::runtime::shift::Shift; use craft_behavior::OwnerClass; use craft_behavior::overlay::Side; use egui::emath::TSTransform; @@ -120,7 +121,7 @@ pub enum OpenFilter { } /// One shown egui layer. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[doc(hidden)] pub struct OpenEntry { /// The layer's id. @@ -160,6 +161,29 @@ pub struct OpenEntry { dialog: Option, } +/// A replay moves the entry's screen rects with its record; the rest stays. +impl Shift for OpenEntry { + fn shifted(&self, by: &egui::RecordShift) -> Self { + OpenEntry { + anchor: self.anchor.shifted(by), + peers: self.peers.shifted(by), + rect: self.rect.shifted(by), + region: self.region.shifted(by), + ..self.clone() + } + } + + fn snapped(&self, to: &Self, within: f32) -> Self { + OpenEntry { + anchor: self.anchor.snapped(&to.anchor, within), + peers: self.peers.snapped(&to.peers, within), + rect: self.rect.snapped(&to.rect, within), + region: self.region.snapped(&to.region, within), + ..self.clone() + } + } +} + impl OpenEntry { /// An entry for the layer `id` of `rank`. pub(crate) fn new(id: Id, rank: Rank, keys: OwnerClass, rect: Rect, layer: Layer) -> Self { @@ -479,7 +503,8 @@ pub(crate) fn appears(ctx: &Context, id: Id, exiting: bool) -> bool { /// Marks the layer `id`'s body as running, so layers opened from inside it become its children, with the `side` of /// its anchor it was placed on. A layer shown again while it fades out opens anew: it appears in this frame and pass. pub(crate) fn begin_layer(ctx: &Context, id: Id, tier: Tier, exiting: bool, side: Option) { - crate::runtime::replay::block(ctx); + // Which layers a press opened reads the presses and releases. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); let reopened = reopened(ctx, id, exiting); with_pass(ctx, |pass| { pass.drawing.push((id, tier)); @@ -617,13 +642,27 @@ pub(crate) fn absorb_presses(ctx: &Context, input: &mut crate::runtime::egui::in input.events.len() != before } -/// The outside press the input hook removed for the running pass. +/// The outside press the input hook removed for the running pass. A tracked input (`Input::Press`). pub(crate) fn absorbed_press(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Press); + absorbed_press_raw(ctx) +} + +/// `absorbed_press` without noting the read: for the pointer's begin hook, which moves `Input::Press` by it. +pub(crate) fn absorbed_press_raw(ctx: &Context) -> Option { with_persist(ctx, pass::current_viewport(ctx), |persist| persist.outside_press) } -/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass. +/// Whether a close is queued for one of the layers `ids`: only a run of the layer's owner takes it, so a memoized view +/// that showed one of them runs while it waits. +pub(crate) fn close_queued(ctx: &Context, ids: &[Id]) -> bool { + !ids.is_empty() && pass_state::with::(ctx, |closes| closes.0.iter().any(|(closed, ..)| ids.contains(closed))) +} + +/// Records the toggling parts that sit beside the anchor of the layer `id` shown in this pass. A replay of the run +/// that showed the layer records them again. pub(crate) fn note_peers(ctx: &Context, id: Id, peers: Vec) { + crate::runtime::replay::journal(ctx, || (id, peers.clone()), |ctx, (id, peers)| note_peers(ctx, *id, peers.clone())); with_pass(ctx, |pass| { if let Some(entry) = pass.current.iter_mut().find(|entry| entry.id == id) { entry.peers = peers; @@ -665,12 +704,16 @@ pub fn end_stack_dialog(ctx: &Context, dialog: Id) { /// Records the layer shown in this pass, parent first: a layer is recorded once its body ran, after the layers opened /// from inside it, so it goes in front of them, and every layer then stacks above the layer it was opened from. A -/// layer shown again in a discarded pass replaces its entry. +/// layer shown again in a discarded pass replaces its entry. A replay of the run that showed the layer records the +/// entry again, its stack place and dialog filled, and the records open around it note the layer as one they show. pub(crate) fn record(ctx: &Context, mut entry: OpenEntry) { - crate::runtime::replay::block(ctx); with_pass(ctx, |pass| { entry.place = entry.place.or(pass.place); entry.dialog = entry.dialog.or(pass.dialog); + }); + crate::runtime::replay::note_layer(ctx, entry.id); + crate::runtime::replay::journal(ctx, || entry.clone(), |ctx, entry| record(ctx, entry.clone())); + with_pass(ctx, |pass| { if let Some(at) = pass.current.iter().position(|recorded| recorded.id == entry.id) { pass.current[at] = entry; return; diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index d32f5b886..7e99402fb 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -237,6 +237,10 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { if events { inputs::bump(ctx, Input::Pointer); } + // A press or release, or an outside press the layer stack's input hook took before egui saw it. + if frame.press.is_some() || frame.release.is_some() || crate::runtime::overlay::absorbed_press_raw(ctx).is_some() { + inputs::bump(ctx, Input::Press); + } } PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer)); PerViewport::::with(ctx, viewport, |shapes| { @@ -325,6 +329,13 @@ pub fn mods(ctx: &Context) -> Mods { with_pass_raw(ctx, |pointer| pointer.frame.as_ref().map_or(Mods::NONE, |frame| frame.mods)) } +/// Where the primary press of the running pass started. A tracked input (`Input::Press`): a layer's dismissal decides by +/// it, so a memoized view that shows a layer runs on a press anywhere, and a pointer move leaves it alone. +pub(crate) fn primary_press(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, Input::Press); + frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) +} + /// `frame` without noting the read: for the steps of the component under the pointer and the pass machinery. pub(crate) fn frame_raw(ctx: &Context) -> PointerFrame { with_pass_raw(ctx, |pointer| pointer.frame.clone()).unwrap_or_else(|| PointerFrame { @@ -444,6 +455,7 @@ pub(crate) fn record_text_widget(ctx: &Context, widget: Id, owner: Id) { /// it the press where no widget on the layer is, and the press and hover there go to the layer's shapes as if egui /// had named no target. pub(crate) fn record_layer_widget(ctx: &Context, widget: Id) { + crate::runtime::replay::journal(ctx, || widget, |ctx, &widget| record_layer_widget(ctx, widget)); PerViewport::::with(ctx, pass::current_viewport(ctx), |record| { record.this_grounds.insert(widget); }); diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index bde005d12..910ff06a3 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -9,8 +9,11 @@ //! //! The record also holds the facts the settled test reads (`runtime::lazy`): the values the run read, whether //! something in it still moves (an animation that is not at its end, a repaint request) and the earliest time it asked -//! to be shown again, and whether it did something a replay cannot repeat (an overlay it shows, paint on another -//! layer, a label scope open around it). Such a record is never replayed: the view runs. +//! to be shown again, the overlay layers it shows and where the focus was in it, and whether it did something a replay +//! cannot repeat (paint on a layer that is neither its own nor an overlay it shows, such as a raw egui popup or a +//! transformed body; a window of another viewport; a label scope open around it). Such a record is never replayed: +//! the view runs. An overlay it shows is journaled as every other registration is (its `Area`, its layer stack +//! entry), so its record replays only where it ran (`Record::pinned`). use crate::runtime::egui::areas::Layer; use crate::runtime::focus::{self, Transcript}; @@ -19,7 +22,7 @@ use crate::runtime::inputs::{Input, Inputs}; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; use crate::runtime::shift::Shift; -use egui::{Context, IdSet, RecordShift}; +use egui::{Context, IdSet, RecordShift, Rect}; use std::any::Any; use std::collections::HashSet; use std::fmt; @@ -164,6 +167,43 @@ pub(crate) struct Facts { /// The command scope instances that registered in the run (`commands::register_instance`): a command queued for one /// is taken only by a run, so a replay waits until the queue holds none. pub(crate) instances: Vec, + /// The overlay layers the run showed (`note_overlay`): their paint and widgets are the record's, and the pointer over + /// one of them engages the record. + pub(crate) overlays: Vec, + /// The layer stack entries the run recorded (`note_layer`): a close queued for one is taken only by a run. + pub(crate) layers: Vec, +} + +/// An overlay layer a run showed: its egui layer and its rect in screen space. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct ShownLayer { + pub(crate) layer: Layer, + pub(crate) rect: Rect, +} + +/// Where the focus was in a run: the component of the focused stop when the run registered it, and the egui widget +/// that held egui focus when the run made it. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Held { + pub(crate) stop: Option, + pub(crate) widget: Option, +} + +impl Held { + /// Where the focus is now: the component of the focused stop and the egui widget that holds egui focus. + pub(crate) fn focused(ctx: &Context) -> Held { + Held { stop: focus::focused_stop(ctx).map(|key| key.0), widget: crate::runtime::egui::focus::focused(ctx) } + } + + /// The part of the focus `self` that is among the stops of `focus` and the egui widgets `widgets`. + pub(crate) fn within(self, focus: &Transcript, widgets: &IdSet) -> Held { + Held { stop: self.stop.filter(|stop| focus.stop_ids().any(|id| id == *stop)), widget: self.widget.filter(|widget| widgets.contains(widget)) } + } + + /// Whether the focus is in the run at all. + pub(crate) fn any(self) -> bool { + self.stop.is_some() || self.widget.is_some() + } } /// What one real run of a region added to its pass. @@ -173,14 +213,22 @@ pub(crate) struct Record { egui: egui::PassRecords, /// The egui widgets of the run. pub(crate) widgets: IdSet, + /// Where the focus was in the run when it ended. + pub(crate) held: Held, pub(crate) facts: Facts, } impl Record { /// Whether a replay can add the record at another place: egui's records hold no paint callback - /// (`PassRecords::paints_callback`). + /// (`PassRecords::paints_callback`) and the record is not pinned. pub(crate) fn movable(&self) -> bool { - !self.egui.paints_callback() + !self.egui.paints_callback() && !self.pinned() + } + + /// Whether the record replays only where it ran, at the offset and clip of its run: it shows an overlay, which a + /// host places in screen space by its anchor, so a move of the record is no move of the layer. + pub(crate) fn pinned(&self) -> bool { + !self.facts.overlays.is_empty() } } @@ -242,6 +290,8 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.reads.extend(open.facts.reads.iter().copied().filter(|key| !kept || !matches!(key, BindKey::Place(..)))); outer.facts.inputs.extend(open.facts.inputs); outer.facts.instances.extend(open.facts.instances.iter().copied()); + outer.facts.overlays.extend(open.facts.overlays.iter().copied()); + outer.facts.layers.extend(open.facts.layers.iter().copied()); } else { recorder.journal.clear(); } @@ -254,13 +304,22 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { facts.layout_keeps.dedup(); facts.derived_keeps.sort_unstable_by_key(|id| id.value()); facts.derived_keeps.dedup(); - // A paint callback's output depends on what its closure holds, which neither a view's key nor a comparison sees: - // its run is never replayed. - facts.blocked |= egui.layers().any(|on| on != layer) || egui.paints_callback(); + // Paint on a layer that is neither the run's own nor an overlay it showed (a raw egui popup, a transformed body) + // comes from code that registers nothing to replay it with. A paint callback's output depends on what its closure + // holds, which neither a view's key nor a comparison sees. Either run is never replayed. + facts.blocked |= egui.layers().any(|on| on != layer && !facts.overlays.iter().any(|shown| shown.layer == on)) || egui.paints_callback(); // Every discard request reaches egui's output (`sizing::request_discard` and egui's own); layout memory's waits // for the end of the pass and notes itself (`note_discard`). facts.discards |= discard_requests(ctx) > open.discards; - Record { focus: focus::transcript(ctx, open.focus), journal, widgets: egui.widgets().iter().map(|widget| widget.id).collect(), egui, facts } + 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. + let held = Held::focused(ctx).within(&focus, &widgets); + if held.any() { + facts.inputs.insert(Input::Sent); + } + Record { focus, journal, widgets, held, egui, facts } } #[cfg(feature = "testing")] @@ -471,6 +530,17 @@ pub(crate) fn note_wake(ctx: &Context, at: f64) { with_open(ctx, |facts| facts.wake = min_wake(facts.wake, Some(at))); } +/// Notes that the running code showed the overlay layer `layer` at the screen rect `rect`. Called by the journaled +/// registration of the layer's `Area`, so a record that replays it notes it again in the records open around it. +pub(crate) fn note_overlay(ctx: &Context, layer: Layer, rect: Rect) { + with_open(ctx, |facts| facts.overlays.push(ShownLayer { layer, rect })); +} + +/// Notes that the running code recorded the layer stack entry `id`, by a run or a replay. +pub(crate) fn note_layer(ctx: &Context, id: egui::Id) { + with_open(ctx, |facts| facts.layers.push(id)); +} + /// Notes that the running code did something a replay cannot repeat. pub(crate) fn block(ctx: &Context) { with_open(ctx, |facts| facts.blocked = true); diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 349e2f42f..5a5d33116 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -12,6 +12,7 @@ use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::{List, ListRow}; use craft_ui::popover::Popover; 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::in_audit_run; @@ -22,6 +23,7 @@ use craft_ui::testing::{ Frames, MemoRun, last_frame_memo_runs, last_pass_measuring_runs, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, measuring_run, trial, }; +use craft_ui::text::TextField; use egui::{Id, Key, Modifiers, Pos2, Rect, Ui, Vec2}; use std::cell::Cell; @@ -1161,8 +1163,7 @@ impl InPopover { let button = &mut self.button; frames.frame(events, |ui| { Popover::new("Presets", Bind::given(true)).at_point(Pos2::new(80.0, 80.0)).show(ui, |ui, _| { - // The popover's first stop, outside the view, takes the focus on open: a view that holds the focus - // runs in every pass. + // The popover's first stop, outside the view, takes the focus on open. Button::new("Search").show(ui); *button = MemoView::new("presets", Title { title: "Inside".to_owned() }, title).show(ui); }); @@ -1267,6 +1268,170 @@ fn a_view_in_a_popover_fills_its_width_as_without_the_view() { assert!(plain > 0.0 && (memo - plain).abs() <= 0.5, "the popover is as wide with the view: {memo} against {plain}"); } +/// Where the popovers of the overlay trials open, and a point outside them. +const POPOVER_AT: Pos2 = Pos2::new(60.0, 60.0); +const AWAY: Pos2 = Pos2::new(700.0, 500.0); + +/// 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)] +struct Hint<'a> { + open: Bind<'a, bool>, +} + +/// Returns where the button in the popover was shown. +fn hint(props: &mut Hint<'_>, ui: &mut Ui) -> Option { + let mut row = None; + Popover::new("Hint", props.open.reborrowed()).at_point(POPOVER_AT).initial_focus(Initial::KeepAnchor).show(ui, |ui, _| { + Text::new("A hint").show(ui); + row = Some(Button::new("Row").show(ui).response.rect); + }); + row +} + +/// The hint view, with whether its popover is open and where its row was shown. +struct HintScene { + open: bool, + row: Option, +} + +impl HintScene { + /// One frame with `events`; returns the views that ran in any of its passes, by props type name. + fn frame(&mut self, frames: &mut Frames, events: Vec) -> Vec<&'static str> { + let (open, row) = (&mut self.open, &mut self.row); + frames.frame(events, |ui| *row = MemoView::new("hint", Hint { open: Bind::bound(open) }, hint).show(ui).flatten()); + let ran = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran); + ran.map(|(name, _, _)| short_name(name)).collect() + } + + fn settled(frames: &mut Frames) -> HintScene { + let mut scene = HintScene { open: true, row: None }; + for _ in 0..SETTLE { + scene.frame(frames, vec![]); + } + scene + } +} + +fn any_open(frames: &Frames) -> bool { + craft_ui::runtime::overlay::any_open(&frames.ctx, craft_ui::runtime::overlay::OpenFilter::Any) +} + +/// A view that shows an open popover with no focus in it replays the popover while nothing reaches it: no component +/// 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 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| { + let tree = frames.tree(); + let node = *tree.with_role(craft_ui::contract::Role::DIALOG).first().expect("the popover reports its node"); + (node, tree.parent_of_key(node)) + }; + let ran_with = dialog(&mut frames); + for _ in 0..WARM { + assert!(scene.frame(&mut frames, vec![]).is_empty(), "an idle frame replays the view"); + assert!(last_pass_runs(&frames.ctx).is_empty(), "no component runs: {:?}", last_pass_runs(&frames.ctx)); + assert!(any_open(&frames), "the replayed popover stays open"); + assert_eq!(frames.ctx.layer_id_at(row.center()), Some(layer), "the popover's layer is still on top under its row"); + assert_eq!(dialog(&mut frames), ran_with, "the popover's node keeps its id and parent"); + } + assert!(painted(&frames, "A hint"), "the replayed popover is painted"); +} + +/// 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 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 +/// 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); + 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:?}"); + 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); + 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"); +} + +/// 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); + 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:?}"); + assert!(resized[0] == ["Hint"], "it runs in the resize frame: {resized:?}"); + let row = scene.row.expect("the popover shows its row"); + assert!(frames.ctx.content_rect().contains_rect(row), "the popover stays inside the window"); +} + +/// A popover the view shows with a text field in it, which takes the focus when it opens. +#[derive(MemoProps)] +struct Typing<'a> { + text: Bind<'a, String>, +} + +fn typing(props: &mut Typing<'_>, ui: &mut Ui) { + Popover::new("Typing", Bind::given(true)).at_point(POPOVER_AT).show(ui, |ui, _| { + TextField::new("Name", props.text.reborrowed()).id_salt("typing").show(ui); + }); +} + +/// With the focus in a replaying popover's text field, a typed character, a paste and an IME commit each reach the +/// 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 text = String::new(); + let frame = |frames: &mut Frames, events: Vec, text: &mut String| { + frames.frame(events, |ui| { + MemoView::new("typing", Typing { text: Bind::bound(text) }, typing).show(ui); + }); + let ran = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran); + ran.map(|(name, _, _)| short_name(name)).collect::>() + }; + for _ in 0..SETTLE { + frame(&mut frames, vec![], &mut text); + } + assert!(frame(&mut frames, vec![], &mut text).is_empty(), "an idle frame replays the view with the focus in its field"); + assert!(last_pass_runs(&frames.ctx).is_empty(), "no component runs: {:?}", last_pass_runs(&frames.ctx)); + let sent = [ + (craft_ui::testing::input::text("a"), "a"), + (egui::Event::Paste("b".to_owned()), "ab"), + (egui::Event::Ime(egui::ImeEvent::Commit("c".to_owned())), "abc"), + ]; + for (event, after) in sent { + let ran = frame(&mut frames, vec![event], &mut text); + assert_eq!(text, after, "the event reached the field in its frame"); + assert!(ran.contains(&"Typing"), "the event ran the view: {ran:?}"); + frame(&mut frames, vec![], &mut text); + assert!(frame(&mut frames, vec![], &mut text).is_empty(), "an idle frame after it replays the view"); + } +} + #[derive(MemoProps)] struct Centred { label: String,