diff --git a/crates/timeline/src/ui/mod.rs b/crates/timeline/src/ui/mod.rs index 1162ed909..bbc2981bb 100644 --- a/crates/timeline/src/ui/mod.rs +++ b/crates/timeline/src/ui/mod.rs @@ -92,7 +92,7 @@ impl DragEvent { /// The colours of the sixteen labels ([`MarkerColor`](crate::MarkerColor) indices), the app's Label preferences. The /// root value is Premiere's (FilmCraft `crates/project/src/label.rs:64`); an app sets its own through its app values. -#[derive(Clone, Debug, PartialEq, EnvValue)] +#[derive(Clone, Debug, PartialEq, EnvValue, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct LabelPalette(pub [egui::Color32; 16]); diff --git a/crates/timeline/src/ui/view.rs b/crates/timeline/src/ui/view.rs index d3420d63d..eb74987e2 100644 --- a/crates/timeline/src/ui/view.rs +++ b/crates/timeline/src/ui/view.rs @@ -130,6 +130,13 @@ impl TimeAxis { #[derive(Clone, Copy, Debug, PartialEq)] struct InTimeline(Option); +/// The axis the timeline rebuilds each pass from its view: a view under it runs in every pass. +impl craft_ui::contract::MemoProps for InTimeline { + fn key(&self, key: &mut craft_ui::contract::MemoKey) { + key.changes_every_pass(); + } +} + impl EnvValue for InTimeline { fn root() -> Self { InTimeline(None) diff --git a/crates/ui-canvas/src/canvas/readout.rs b/crates/ui-canvas/src/canvas/readout.rs index 103aa4274..ec36f1e0c 100644 --- a/crates/ui-canvas/src/canvas/readout.rs +++ b/crates/ui-canvas/src/canvas/readout.rs @@ -6,7 +6,7 @@ use egui::{Context, Pos2}; /// The one Show Transformation Values gate: while it holds `false` in the root env, [`readout`] and the tool host's /// paint of a tool's readout rows paint nothing. [`hud`] is never gated. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, crate::contract::MemoProps)] pub struct ShowReadouts(pub bool); impl EnvValue for ShowReadouts { diff --git a/crates/ui-canvas/src/canvas/snap.rs b/crates/ui-canvas/src/canvas/snap.rs index d1a88c3b9..69ddbb6d7 100644 --- a/crates/ui-canvas/src/canvas/snap.rs +++ b/crates/ui-canvas/src/canvas/snap.rs @@ -162,6 +162,13 @@ pub fn snap_tolerance(view: &CanvasView, mods: Mods, os: Platform, tool_reads_co #[derive(Clone, PartialEq)] struct InCanvasSnap(Option); +/// A context the canvas rebuilds each pass: a view under it runs in every pass. +impl crate::contract::MemoProps for InCanvasSnap { + fn key(&self, key: &mut crate::contract::MemoKey) { + key.changes_every_pass(); + } +} + impl EnvValue for InCanvasSnap { fn root() -> Self { InCanvasSnap(None) diff --git a/crates/ui-canvas/src/canvas/space.rs b/crates/ui-canvas/src/canvas/space.rs index fbf32a377..b1412701c 100644 --- a/crates/ui-canvas/src/canvas/space.rs +++ b/crates/ui-canvas/src/canvas/space.rs @@ -350,6 +350,13 @@ pub(crate) fn context_menu(cx: &mut Cx<'_, C>, part: impl Into); +/// A context the canvas rebuilds each pass: a view under it runs in every pass. +impl crate::contract::MemoProps for InCanvas { + fn key(&self, key: &mut crate::contract::MemoKey) { + key.changes_every_pass(); + } +} + impl EnvValue for InCanvas { fn root() -> Self { InCanvas(None) diff --git a/crates/ui-canvas/src/canvas/tool_host.rs b/crates/ui-canvas/src/canvas/tool_host.rs index 573c1f353..1591d94c8 100644 --- a/crates/ui-canvas/src/canvas/tool_host.rs +++ b/crates/ui-canvas/src/canvas/tool_host.rs @@ -391,6 +391,13 @@ fn keys_down(ctx: &Context, holds: &[Key]) -> Vec { #[derive(Clone, PartialEq)] struct InToolPass(Option); +/// A context the canvas rebuilds each pass: a view under it runs in every pass. +impl crate::contract::MemoProps for InToolPass { + fn key(&self, key: &mut crate::contract::MemoKey) { + key.changes_every_pass(); + } +} + impl EnvValue for InToolPass { fn root() -> Self { InToolPass(None) diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index c996143d6..8d660f9ea 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -686,7 +686,7 @@ pub enum Gap { /// Set by a menu for its body: a horizontal divider takes `space.gap.inline` above and below its line, since the rows /// of a menu touch. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[doc(hidden)] pub struct InMenu(pub bool); diff --git a/crates/ui-contract/src/contract/ghost.rs b/crates/ui-contract/src/contract/ghost.rs index 829d418fb..ad2de1c80 100644 --- a/crates/ui-contract/src/contract/ghost.rs +++ b/crates/ui-contract/src/contract/ghost.rs @@ -102,7 +102,7 @@ fn paint_pointer(ctx: &Context, env: &Env, painter: &egui::Painter) { use craft_behavior::{Cursor, PaintedCursor}; let Some(at) = areas::pointer_pos(ctx) else { return }; let Some(Cursor::Painted(cursor)) = cursor::current(ctx) else { return }; - let closed = pointer::frame(ctx).buttons.contains(craft_behavior::Buttons::PRIMARY); + let closed = pointer::frame_raw(ctx).buttons.contains(craft_behavior::Buttons::PRIMARY); let target = cursor::image_target(ctx).filter(|_| !matches!(cursor, PaintedCursor::Badged { .. })); if let Some(target) = target { if cursor::show_image(ctx, &pointer_art(env, &cursor, closed, false), target) { @@ -183,7 +183,7 @@ fn paint_drag(ctx: &Context, env: &Env, painter: &egui::Painter, session: &drag: } let record = RefCell::new(PaintRecord::default()); let draw = &Draw::new(painter, &record, DrawEnv { tokens: &env.tokens, direction: env.direction, ink: Ink::OnPanel }); - let Some(at) = pointer::frame(ctx).pos else { return }; + let Some(at) = pointer::frame_raw(ctx).pos else { return }; match &session.preview { DragPreview::Badge(label) => { let label = env.view().resolve(label); diff --git a/crates/ui-contract/src/contract/group.rs b/crates/ui-contract/src/contract/group.rs index c82f4be8a..5b1deebd1 100644 --- a/crates/ui-contract/src/contract/group.rs +++ b/crates/ui-contract/src/contract/group.rs @@ -53,6 +53,14 @@ impl PartialEq for GroupHandle { } } +/// A handle to group state its members write during the pass: a key cannot follow it, so a view under a group runs in +/// every pass. +impl crate::contract::MemoProps for GroupHandle { + fn key(&self, key: &mut crate::contract::MemoKey) { + key.changes_every_pass(); + } +} + impl EnvValue for GroupHandle { fn root() -> Self { GroupHandle { state: None, kind: PhantomData } diff --git a/crates/ui-contract/src/contract/items/drag.rs b/crates/ui-contract/src/contract/items/drag.rs index 9a34cf375..ac971d6cf 100644 --- a/crates/ui-contract/src/contract/items/drag.rs +++ b/crates/ui-contract/src/contract/items/drag.rs @@ -378,7 +378,7 @@ impl ItemsHooks<'_, '_, C> { /// does nothing and starts no sweep. pub(super) fn begin_toggle(&mut self, cx: &mut Cx<'_, C>, at: usize, (column, toggle, cell): (ColumnKey, ToggleColumn, Rect)) { if toggle.sweepable { - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; self.drags.sweep = Some(Sweep { column: column.clone(), on: false, mods, crossed: vec![at], span: cell.x_range(), open: Vec::new() }); } match self.flip_toggle(cx, at, column, toggle) { @@ -398,7 +398,7 @@ impl ItemsHooks<'_, '_, C> { return None; } let on = !self.source.toggled(at, &column); - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; self.emit_toggle(cx, at, &column, on, mods); if toggle.exclusive && on { for other in (0..self.source.len()).filter(|&other| other != at && self.source.toggled(other, &column)) { diff --git a/crates/ui-contract/src/contract/items/edge.rs b/crates/ui-contract/src/contract/items/edge.rs index baf704692..b3c6da9be 100644 --- a/crates/ui-contract/src/contract/items/edge.rs +++ b/crates/ui-contract/src/contract/items/edge.rs @@ -16,7 +16,7 @@ impl ItemsHooks<'_, '_, C> { pub(super) fn edge_parts(&mut self, comp: &C, pcx: &mut PartsCx<'_, C>) { self.edge = None; let Some(rule) = comp.edge_press() else { return }; - let frame = crate::runtime::pointer::frame(pcx.measure.ui.ctx()); + let frame = crate::runtime::pointer::frame_raw(pcx.measure.ui.ctx()); let (Some(pos), true) = (frame.pos, frame.mods == rule.mods()) else { return }; let Some(layout) = self.layout.clone() else { return }; let view = self.below_header(pcx.content_rect); @@ -59,7 +59,7 @@ impl ItemsHooks<'_, '_, C> { pub(super) fn edge_step(&mut self, cx: &mut Cx<'_, C>) { let Some((above, below)) = self.edge.clone() else { return }; if cx.part_activated(EDGE).is_some() { - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; self.events.push(CollectionEvent::EdgePressed { above, below, mods }); } } diff --git a/crates/ui-contract/src/contract/items/header.rs b/crates/ui-contract/src/contract/items/header.rs index 455a33725..c0109baa9 100644 --- a/crates/ui-contract/src/contract/items/header.rs +++ b/crates/ui-contract/src/contract/items/header.rs @@ -560,7 +560,7 @@ impl Header { if sortable && ((phase.is_click() && primary) || (keyed && active == Some(at))) { self.sort(&key); } - if cx.part(HEADER.at(hash)).hovered && crate::runtime::pointer::frame(&ctx).release == Some(PointerButton::Secondary) { + if cx.part(HEADER.at(hash)).hovered && crate::runtime::pointer::frame_raw(&ctx).release == Some(PointerButton::Secondary) { self.ask_menu(&ctx, Some(key.clone()), ctx.pointer_latest_pos().unwrap_or(rect.left_bottom())); } if movable && primary && matches!(phase, PressPhase::DragStart { .. }) { @@ -606,7 +606,7 @@ impl Header { } if let Some(room) = self.room && cx.part(ROOM).hovered - && crate::runtime::pointer::frame(&ctx).release == Some(PointerButton::Secondary) + && crate::runtime::pointer::frame_raw(&ctx).release == Some(PointerButton::Secondary) { self.ask_menu(&ctx, None, ctx.pointer_latest_pos().unwrap_or(room.left_bottom())); } diff --git a/crates/ui-contract/src/contract/items/lead.rs b/crates/ui-contract/src/contract/items/lead.rs index d78d489ef..88e069872 100644 --- a/crates/ui-contract/src/contract/items/lead.rs +++ b/crates/ui-contract/src/contract/items/lead.rs @@ -115,7 +115,7 @@ impl ItemsHooks<'_, '_, C> { /// The pointer's position, in screen space, while it is over the collection. fn hovered_pos(cx: &Cx<'_, C>) -> Option { - crate::runtime::pointer::frame(&cx.core.ctx).pos.filter(|_| cx.core.response.hovered()) + crate::runtime::pointer::frame_raw(&cx.core.ctx).pos.filter(|_| cx.core.response.hovered()) } /// The row under `pos` (screen space) in the rows' placement `at`: the pointer-to-row mapping of `hover_lead`, @@ -139,9 +139,8 @@ impl ItemsHooks<'_, '_, C> { /// arrow keys. A pass moves the pointer when it holds a move event: the pointer entering over a row moves the lead /// with no movement to measure, and a modifier change under a resting pointer leaves the lead where the keys put it. pub(super) fn hover_lead(&mut self, comp: &C, cx: &Cx<'_, C>, layout: &C::ItemLayout, at: Placement) { - let moved = crate::runtime::pointer::with_pass_pointer(&cx.core.ctx, |pass| { - pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. })) - }); + let moved = + crate::runtime::pointer::with_pass_raw(&cx.core.ctx, |pass| pass.events.iter().any(|event| matches!(event, PointerEvent::Moved { .. }))); if !moved { return; } @@ -177,7 +176,7 @@ impl ItemsHooks<'_, '_, C> { { return; } - let Some(row) = crate::runtime::pointer::frame(ctx).pos.and_then(|pos| self.row_under(layout, at, pos)) else { return }; + let Some(row) = crate::runtime::pointer::frame_raw(ctx).pos.and_then(|pos| self.row_under(layout, at, pos)) else { return }; if self.holds(row) { return; } diff --git a/crates/ui-contract/src/contract/items/marquee.rs b/crates/ui-contract/src/contract/items/marquee.rs index ab7139dcb..02342ac3b 100644 --- a/crates/ui-contract/src/contract/items/marquee.rs +++ b/crates/ui-contract/src/contract/items/marquee.rs @@ -47,7 +47,7 @@ impl ItemsHooks<'_, '_, C> { let local = Self::logical(layout, rect, rtl, origin); if rect.contains(origin) && layout.hit(local, seen).is_none() { let selected: Vec = self.selected_keys(&self.selection_at_read); - let mods = crate::runtime::pointer::frame(&cx.core.ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&cx.core.ctx).mods; let select = MarqueeSelect::begin(content_point(local, seen), mods, selected.clone()); self.drags.marquee = Some(MarqueeDrag { select, last: selected, live: false }); } diff --git a/crates/ui-contract/src/contract/items/press.rs b/crates/ui-contract/src/contract/items/press.rs index 88860d64c..212884a5a 100644 --- a/crates/ui-contract/src/contract/items/press.rs +++ b/crates/ui-contract/src/contract/items/press.rs @@ -56,11 +56,11 @@ impl ItemsHooks<'_, '_, C> { let at = xf.map_or(at, |map| map.to_layer(at)) - rect.min.to_vec2(); if layout.mirrors() && rtl { flow.to_physical(Rect::from_min_size(at, Vec2::ZERO)).min } else { at } }; - let mods_now = crate::runtime::pointer::frame(&ctx).mods; + let mods_now = crate::runtime::pointer::frame_raw(&ctx).mods; // A click on a row the collection does not take (a caption, a disabled row) is no pick: the layers around the // collection (a dropdown's list) stay open. if cx.core.activation.as_ref().is_some_and(|activation| !activation.by_key) - && let Some(pos) = crate::runtime::pointer::frame(&ctx).pos + && let Some(pos) = crate::runtime::pointer::frame_raw(&ctx).pos && local(pos).y >= 0.0 && layout .hit(local(pos), offset) @@ -100,7 +100,7 @@ impl ItemsHooks<'_, '_, C> { self.drags.command = Some(self.source.key(at)); self.move_lead(at, LeadSource::Pointer); } else if !secondary_on_toggle { - let mods = crate::runtime::pointer::frame(&ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&ctx).mods; let key = self.source.key(at); let column = if Self::selects_cells(comp) { layout.column_at(local(start.origin), offset) } else { None }; // A plain press on a selected row of a multiple selection leaves the selection whole, so a drag @@ -206,7 +206,7 @@ impl ItemsHooks<'_, '_, C> { && let Some(at) = layout.hit(local(start.origin), offset).filter(|&at| self.source.enabled(at) && layout.shown(at)) { // A modified click is a command on the thumbnail (load as selection, and so on), not a pick. - let mods = crate::runtime::pointer::frame(&ctx).mods; + let mods = crate::runtime::pointer::frame_raw(&ctx).mods; if !(mods.shift || mods.cmd || mods.alt) { if !self.keeps_pick(at, start.clicks) { self.pick(comp, at, false, false); @@ -277,7 +277,7 @@ impl ItemsHooks<'_, '_, C> { // Something over the collection, or a part of a row or of the collection that takes presses and is under the // pointer, keeps the request away; a part that picks its item (a thumbnail) is the row's, and the request names // it. - let released = crate::runtime::pointer::frame(&ctx); + let released = crate::runtime::pointer::frame_raw(&ctx); let hover = crate::primitives::sensing::read_outcome(&ctx, ArenaId::new(cx.core.id)).hover; let menu_at = if released.release == Some(craft_behavior::PointerButton::Secondary) && cx.core.response.hovered() diff --git a/crates/ui-contract/src/contract/label/props.rs b/crates/ui-contract/src/contract/label/props.rs index 5f80ba2a3..e1b357c84 100644 --- a/crates/ui-contract/src/contract/label/props.rs +++ b/crates/ui-contract/src/contract/label/props.rs @@ -72,7 +72,7 @@ impl GlyphLabel { /// How the labelled rows under a container show their labels: set once on the container (`ContainerProps::labels`), /// read by every label step under it until another container sets its own. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[non_exhaustive] pub enum LabelScheme { /// A dialog or a form: a beside label sits against its control and ends with a colon; the control keeps its own diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index d5ea3cc8f..47b72393d 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -154,6 +154,8 @@ impl Lazy { // A run around this one that is replayed later keeps the child's entry. replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); if let Some(view) = view { + // A run around this child decides it by the scroll view: it replays only while the view is the same. + replay::note_input(&ctx, crate::runtime::inputs::Input::Scroll); let at = |size: Vec2| { let x = if rtl { available.max.x - size.x } else { available.min.x }; Rect::from_min_size(Pos2::new(x, available.min.y), size) @@ -187,7 +189,7 @@ impl Lazy { crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass"); } if self.settles - && let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place), key) + && let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place), view, key) { let (took, _) = take_in_flow(ui, size); let memo = matches!(key, Key::Memo(_)); @@ -208,6 +210,7 @@ impl Lazy { let mark = focus::mark(&ctx); let mut run = Run { recording: self.settles && real, kept: true, layer: place.layer, output: None }; let edits = if run.recording { lazy::edits(&ctx) } else { 0 }; + let seen = if run.recording && matches!(key, Key::Memo(_)) { crate::runtime::inputs::seen(&ctx) } else { Default::default() }; if run.recording { replay::open(&ctx); } @@ -237,7 +240,7 @@ impl Lazy { if let Some(record) = record { // The key from before the run: a run that wrote through its props moved the key, so the view runs once more, // from the written value, before it replays. - lazy::ran(&ctx, id, record, place, rect, lazy::Ran { key, edits, output: run.output.take() }); + lazy::ran(&ctx, id, record, place, rect, lazy::Ran { key, edits, seen, view, output: run.output.take() }); } #[cfg(feature = "testing")] if real && self.settles { diff --git a/crates/ui-contract/src/contract/memo.rs b/crates/ui-contract/src/contract/memo.rs index 5d92f1ee7..162c8a970 100644 --- a/crates/ui-contract/src/contract/memo.rs +++ b/crates/ui-contract/src/contract/memo.rs @@ -299,6 +299,11 @@ impl MemoKey { MemoKey { context: Some(ctx.clone()), ..MemoKey::default() } } + /// An empty key of the same view as this one. + pub(crate) fn child(&self) -> MemoKey { + MemoKey { context: self.context.clone(), ..MemoKey::default() } + } + /// The context of the view that takes the key; `None` for a key taken outside a view (`MemoKey::of`). pub(crate) fn context(&self) -> Option<&egui::Context> { self.context.as_ref() @@ -311,6 +316,16 @@ impl MemoKey { key.finish() } + /// Feeds an input whose value a key cannot follow (a handle to state shared and written elsewhere, a context a + /// container rebuilds each pass): a view whose key holds it runs in every pass. Outside a view's key it feeds + /// nothing. + pub fn changes_every_pass(&mut self) { + if let Some(ctx) = &self.context { + let pass = ctx.cumulative_pass_nr(); + self.write(&pass.to_le_bytes()); + } + } + /// Feeds `bytes`. pub fn write(&mut self, bytes: &[u8]) { self.hasher.write(bytes); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index ae11407e4..5b31be194 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -3,6 +3,7 @@ use super::lazy::{Lazy, Shown}; use super::memo::{MemoKey, MemoProps}; +use crate::runtime::env::{Env, Scoped}; use egui::Ui; use std::hash::Hash; use std::sync::Arc; @@ -25,6 +26,21 @@ use std::sync::Arc; /// view runs once more, reads the written value, and replays from then on. A write costs one more run, never a stale /// replay. /// +/// Its other inputs are the framework's, and each reaches the key or the settled test: +/// - its place: the room it is given, the clip, the layer, the layout, the scale and the scope's style inputs (tokens, +/// theme, density, direction, language, window active), compared for every view; +/// - what the scope around it hands down beyond those (enabled, read-only, size, ink, the command chain, motion, every +/// app value, and the rest of `Scoped::scope_key`), in the key; +/// - the framework inputs it reads outside its props (`runtime::inputs`: the modifiers, the pointer, the keys held, the +/// window facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the scroll view of a nested +/// `Lazy`): a change of one runs only the views that read it; +/// - the clock, read through `frame::stepped_clock`: the view runs at the next step; +/// - commands sent to a command scope instance inside it: it runs while one waits. +/// +/// Its content is a layout room of its own, as a pane's is: the flow of the body around it (a row's shrink, a column's +/// sweep, a grid's cursor) does not reach in, so the room it is given reaches it only through its place. To the body +/// around it the view is one unit, sized by its content's measure. +/// /// What `show` returns holds layout facts only (a size, which part took the room). A replay returns the kept value /// again, so an event returned through it would arrive once per pass. Events leave a view through its bindings, its /// `Tracked` writes or commands. A measuring pass that takes the kept extent returns the kept value of the real run. @@ -72,9 +88,13 @@ impl MemoView pub fn show(self, ui: &mut Ui) -> Option { let MemoView { lazy, mut props, show } = self; let ctx = ui.ctx().clone(); - let key = Self::key(&ctx, &props, show); + let env = Env::of(ui); + let key = Self::key(&ctx, &env, &props, show); let shown = lazy.run_keyed(ui, std::any::type_name::

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { + // The content is a layout room of its own: the flow of the body around it does not reach in. + let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); let out = show(&mut props, ui); + Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); out }); @@ -85,12 +105,14 @@ impl MemoView } } - /// The key of `props` shown through `show`: the props type, the `fn`'s address and the props' inputs. Two `fn`s - /// the compiler merged into one address differ in their props type or show the same. - fn key(ctx: &egui::Context, props: &P, show: fn(&mut P, &mut Ui) -> R) -> u128 { + /// The key of `props` shown through `show` in the scope `env`: the props type, the `fn`'s address, the props' inputs + /// and what the scope hands down beyond its style inputs (`Scoped::scope_key`). Two `fn`s the compiler merged into + /// one address differ in their props type or show the same. + fn key(ctx: &egui::Context, env: &Env, props: &P, show: fn(&mut P, &mut Ui) -> R) -> u128 { let mut key = MemoKey::of_view(ctx); key.feed_hash(&P::identity()); key.write(&(show as usize).to_le_bytes()); + key.write(&env.scope_key().to_le_bytes()); props.key(&mut key); #[cfg(feature = "testing")] crate::runtime::measure::count_memo_key_bytes(ctx, key.bytes()); diff --git a/crates/ui-contract/src/contract/overlay/dismissal.rs b/crates/ui-contract/src/contract/overlay/dismissal.rs index 918738b59..eda60ea08 100644 --- a/crates/ui-contract/src/contract/overlay/dismissal.rs +++ b/crates/ui-contract/src/contract/overlay/dismissal.rs @@ -75,7 +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(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) + let Some(press) = pointer::frame_raw(ctx).press.filter(|press| press.button == craft_behavior::PointerButton::Primary).map(|press| press.origin) else { return false; }; @@ -118,8 +118,9 @@ impl Cx<'_, C> { self.core.injected = Some(source); } - /// The modifiers held this frame, Alt alone included. + /// The modifiers held this frame, Alt alone included. A tracked input: a memoized view that reads them runs when + /// they change. pub fn modifiers(&self) -> Mods { - pointer::frame(&self.core.ctx).mods + pointer::mods(&self.core.ctx) } } diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index ffec66732..eddf596da 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -68,7 +68,7 @@ impl Opener { // arena member alike: whether the open press is on it and whether a click released on it. let pressed_on = response::is_pressed(anchor); let request = keys::context_request(&anchor.ctx, anchor.id); - let (fired, opening, pressed, clicked) = pointer::with_pass_pointer(&anchor.ctx, |pass| { + let (fired, opening, pressed, clicked) = pointer::with_pass_raw(&anchor.ctx, |pass| { let Some(frame) = pass.frame.as_ref() else { return (false, Opening::Plain, false, false) }; let inside = frame .pos @@ -128,7 +128,7 @@ impl Opener { /// Whether a secondary-button release lands inside `response`'s rect in this pass: the secondary click a /// `Trigger::Press` opener opens on. pub(super) fn secondary_release_in(response: &Response) -> bool { - pointer::with_pass_pointer(&response.ctx, |pass| { + pointer::with_pass_raw(&response.ctx, |pass| { pass.frame.as_ref().is_some_and(|frame| { frame.release == Some(PointerButton::Secondary) && frame.pos.is_some_and(|pos| { @@ -169,7 +169,7 @@ pub(crate) fn anchor_floor(overlay: &Overlay) -> f32 { /// The least width of the layer the content runs in ([`anchor_floor`]), which a layer's container gives its regions: /// a content-sized collection in the layer is at least this wide, so its rows fill the layer. 0 outside a layer. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] pub(crate) struct LayerFloor(pub(crate) f32); impl crate::runtime::env::EnvValue for LayerFloor { diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 5a550a592..064321fc2 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -50,7 +50,7 @@ fn stored_opening(ctx: &Context, id: Id) -> Option { /// The screen rect the popups opened in an env are contained in, and the popups opened from those: the menus of a menu /// bar stay below the bar ([`OverlayUi::contain_popups_below`](super::OverlayUi::contain_popups_below)). `None`, the /// root's, lets popups take the whole safe rect. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] #[non_exhaustive] pub struct PopupRegion(pub Option); diff --git a/crates/ui-contract/src/contract/steps/label.rs b/crates/ui-contract/src/contract/steps/label.rs index 3c9741ce1..33d4c55d3 100644 --- a/crates/ui-contract/src/contract/steps/label.rs +++ b/crates/ui-contract/src/contract/steps/label.rs @@ -52,7 +52,7 @@ fn scrub_warp(cx: &mut Cx<'_, C>, drag: &ValueDrag, pos: Pos2) -> if warp.pending() { return shift; } - let Some(screen) = crate::runtime::pointer::frame(&ctx).pos else { return shift }; + let Some(screen) = crate::runtime::pointer::frame_raw(&ctx).pos else { return shift }; let hosts = WindowHost::of(&ctx); if let (Some(by), Some(desktop)) = (drag.warp_by(screen, ctx.content_rect()), hosts.desktop_pointer()) && hosts.warp_pointer(desktop + by) diff --git a/crates/ui-contract/src/contract/steps/paint.rs b/crates/ui-contract/src/contract/steps/paint.rs index 2328d5aa6..f7a494cb7 100644 --- a/crates/ui-contract/src/contract/steps/paint.rs +++ b/crates/ui-contract/src/contract/steps/paint.rs @@ -30,6 +30,12 @@ pub(crate) struct Fade { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(crate) struct UnderVeil(pub Option); +impl crate::contract::MemoProps for UnderVeil { + fn key(&self, key: &mut crate::contract::MemoKey) { + key.feed_hash(&self.0); + } +} + impl EnvValue for UnderVeil { fn root() -> Self { UnderVeil(None) diff --git a/crates/ui-contract/src/contract/steps/update.rs b/crates/ui-contract/src/contract/steps/update.rs index 9d4db0705..e853d9816 100644 --- a/crates/ui-contract/src/contract/steps/update.rs +++ b/crates/ui-contract/src/contract/steps/update.rs @@ -18,7 +18,7 @@ pub(crate) fn takes_activation(resolved: &Resolved<'_>) -> bool { /// `Intent::Activate` carries them, and the pass's pointer frame reads them from the same input a pointer activation's /// modifiers come from (Alt+Enter adds the way Alt+click does). pub(crate) fn key_activation(ctx: &egui::Context) -> crate::contract::Activation { - crate::contract::Activation { by_key: true, mods: crate::runtime::pointer::frame(ctx).mods } + crate::contract::Activation { by_key: true, mods: crate::runtime::pointer::frame_raw(ctx).mods } } /// Step 9, update, the part the library writes: the keyboard activation. @@ -95,7 +95,7 @@ fn double_click(core: &CxCore<'_>) -> Option> { /// Whether this pass releases the secondary button over the component, its text part included (a widget of its own /// over it): a right click on it. pub(crate) fn secondary_click(core: &CxCore<'_>) -> bool { - crate::runtime::pointer::frame(&core.ctx).release == Some(craft_behavior::PointerButton::Secondary) + crate::runtime::pointer::frame_raw(&core.ctx).release == Some(craft_behavior::PointerButton::Secondary) && (core.response.hovered() || core.texts.as_ref().is_some_and(|(key, _)| { core.ctx.read_response(crate::primitives::text_adapter::text_id(core.id, *key)).is_some_and(|text| text.hovered()) diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 5e118532a..8660c3d8a 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -480,7 +480,7 @@ pub(crate) fn run( } if decl.options.holds_drafts { // A window deactivation leaves the draft for the next Enter or a press elsewhere (L-52). - if state.end == Some(End::Blur) && crate::runtime::pointer::with_pass_pointer(&ctx, |pointer| pointer.focus_lost) { + if state.end == Some(End::Blur) && crate::runtime::pointer::with_pass_raw(&ctx, |pointer| pointer.focus_lost) { state.end = None; } // A press the focus service held for this part keeps focus; the draft shows as its value would. diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 3217d7577..00e3a12ec 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -428,7 +428,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut }; // A secondary press inside the selection keeps the selection for the edit menu it opens, as native fields do; // egui's widget moves the caret to any press, so the selection from before the press is put back. - let secondary = crate::runtime::pointer::frame(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary); + let secondary = crate::runtime::pointer::frame_raw(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary); let kept = selection(ctx, widget).filter(|(caret, anchor)| secondary && caret != anchor); let shown = text_edit::show(input.ui, edit); crate::runtime::pointer::record_text_widget(ctx, widget, input.id); diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 05853c05a..2900121f2 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -69,6 +69,8 @@ pub(crate) struct Board { /// The commands the app defines at run time, from this frame's input. app: Option, keymap: Option, + /// How many keymaps the board built: the keymap's generation (`runtime::inputs::Input::Keymap`). + keymaps: u64, gate: Option, /// The gate's answers in this frame, by command key (`CommandRef::key`). The gate answers from what the app knew /// before the frame, so the board asks it once per command per frame, whichever readers and passes resolve it. @@ -633,6 +635,7 @@ pub(crate) fn set_input(ctx: &Context, input: &CommandInput) { let BuiltKeymap { keymap, edit_chords, window_shortcuts } = keymap_for(&board.registry, input.catalog.as_ref(), platform, input.overrides.as_ref()); board.keymap = Some(KeymapCache { keymap, platform, overrides: input.overrides.clone(), generation, edit_chords, window_shortcuts }); + board.keymaps += 1; for def in input.catalog.as_ref().map_or(&[][..], AppCatalog::defs) { if board.registry.get(&def.command.id).is_some() && board.shadowed.insert(def.command.id.clone()) { shadowed.push(def.command.id.clone()); @@ -653,18 +656,31 @@ pub(crate) fn edit_chords(ctx: &Context) -> Arc<[(EditCommand, Chord)]> { with(ctx, |board| board.keymap.as_ref().map(|cache| Arc::clone(&cache.edit_chords)).unwrap_or_default()) } +/// The generation of the window's keymap: it moves each time a new keymap is built. +pub(crate) fn keymap_generation(ctx: &Context) -> u64 { + with(ctx, |board| board.keymaps) +} + +/// Whether the queue holds a command for one of `instances`: only a run of the view they registered in takes it. +pub(crate) fn queued_for(ctx: &Context, instances: &[Id]) -> bool { + !instances.is_empty() && with(ctx, |board| board.queue.iter().any(|fired| fired.target.is_some_and(|target| instances.contains(&target)))) +} + /// The bindings the window's keymap gives `command`; none before the first frame builds one. pub(crate) fn bindings(ctx: &Context, command: &CommandRef) -> Vec { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); with(ctx, |board| board.keymap.as_ref().map(|cache| cache.keymap.bindings(command)).unwrap_or_default()) } /// The chord the window's keymap shows for `command` (`Keymap::shown_chord`); none before the first frame builds one. pub(crate) fn chord(ctx: &Context, command: &CommandRef) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); with(ctx, |board| board.keymap.as_ref().and_then(|cache| cache.keymap.shown_chord(command))) } /// The command that holds `chord` in the window's keymap (`Keymap::holder`); none before the first frame builds one. pub(crate) fn holder(ctx: &Context, chord: &Chord) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); with(ctx, |board| board.keymap.as_ref().and_then(|cache| cache.keymap.holder(chord))) } @@ -686,6 +702,7 @@ pub(crate) fn take_delivered(ctx: &Context) -> Vec { /// Whether the component that holds key focus sits inside the instance `id`. #[doc(hidden)] pub fn focus_within(ctx: &Context, id: Id) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Focus); with(ctx, |board| board.here.focused.iter().any(|(_, chain)| chain.contains(&id))) } @@ -697,6 +714,7 @@ pub(crate) fn register_instance(ctx: &Context, scope: CommandScope, id: Id) { /// `register_instance` in the layer `layer`, which a replay of the registration keeps. fn register_in(ctx: &Context, scope: CommandScope, id: Id, layer: Option) { crate::runtime::replay::journal(ctx, || (scope, id, layer), |ctx, &(scope, id, layer)| register_in(ctx, scope, id, layer)); + crate::runtime::replay::note_instance(ctx, id); let viewport = pass::current_viewport(ctx); let stamp = pass::pass_nr(ctx, viewport); with(ctx, |board| match board.instances.iter_mut().find(|i| i.id == id) { @@ -797,6 +815,8 @@ fn resolve_in( reach: Reach<'_>, from: Option<&Vantage>, ) -> (ResolvedCommand, Option) { + // The resolved command carries the chord the keymap shows. + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keymap); let ((mut resolved, key), first_unknown, gate) = with(ctx, |board| { let first_unknown = board.def(&command.id).is_none() && board.unknown.insert(command.id.clone()); // A command no state named yet has a key too, so a state given later reaches the regions that read it. diff --git a/crates/ui-contract/src/runtime/commands/mod.rs b/crates/ui-contract/src/runtime/commands/mod.rs index 40c43af07..cfb1ba239 100644 --- a/crates/ui-contract/src/runtime/commands/mod.rs +++ b/crates/ui-contract/src/runtime/commands/mod.rs @@ -30,6 +30,7 @@ pub(crate) use board::{ #[doc(hidden)] pub use board::{bound_around, take_around}; pub(crate) use board::{fire_bound, fire_resolved, resolve_bound, resolve_scoped}; +pub(crate) use board::{keymap_generation, queued_for}; use craft_behavior::CommandFlags; use craft_behavior::edit_history::Step; diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index fdfea4948..8e5f7e281 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -328,12 +328,14 @@ pub fn amend(ctx: &Context, change: impl FnOnc /// The active drag payload of type `P`, from any viewport. For code without a `Cx`. pub fn active(ctx: &Context) -> Option> { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Drag); active_of(ctx, TypeId::of::

())?.downcast::

().ok() } /// The active drag payload whose type is `payload`: the session's own payload, else its `also`. For a target that /// picks the payload types it takes at run time. pub(crate) fn active_of(ctx: &Context, payload: TypeId) -> Option> { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Drag); let (own, also) = board(ctx, |board| board.session.as_ref().map(|session| (session.payload.clone(), session.also.clone())))?; if Any::type_id(&*own) == payload { return Some(own); @@ -344,9 +346,21 @@ pub(crate) fn active_of(ctx: &Context, payload: TypeId) -> Option u64 { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Drag); board(ctx, |board| board.started) } +/// What a drag reader sees of the session, as the tracked input `Drag` compares it: the sessions started, and the +/// payloads of the running one. +pub(crate) fn state(ctx: &Context) -> (u64, Option<(usize, Option)>) { + board(ctx, |board| { + let payloads = board.session.as_ref().map(|session| { + (Arc::as_ptr(&session.payload) as *const () as usize, session.also.as_ref().map(|also| Arc::as_ptr(also) as *const () as usize)) + }); + (board.started, payloads) + }) +} + /// The mark of the target that would take a drop now. #[doc(hidden)] pub fn mark(ctx: &Context) -> Option { @@ -374,7 +388,7 @@ pub fn cancel(ctx: &Context, reason: CancelReason) { /// The begin hook: the window losing focus ends the session. pub(crate) fn begin(ctx: &Context) { - if source_viewport(ctx) == Some(pass::current_viewport(ctx)) && pointer::with_pass_pointer(ctx, |pointer| pointer.focus_lost) { + if source_viewport(ctx) == Some(pass::current_viewport(ctx)) && pointer::with_pass_raw(ctx, |pointer| pointer.focus_lost) { cancel(ctx, CancelReason::Blur); } os_files(ctx); @@ -460,7 +474,7 @@ pub fn cross_window_pointer(ctx: &Context, viewport: ViewportId) -> Option pub(crate) fn dragging_of(ctx: &Context, payload: TypeId) -> Option<(Arc, Pos2)> { let payload = active_of(ctx, payload)?; let os = board(ctx, |board| board.session.as_ref().is_some_and(|session| session.os)); - let frame = pointer::frame(ctx).pos; + let frame = pointer::frame_raw(ctx).pos; let host = WindowHost::of(ctx); let pointer = if os && host.desktop_pointer().is_some() { host.pointer_in(pass::current_viewport(ctx)) } else { frame }; Some((payload, pointer?)) @@ -537,7 +551,7 @@ pub fn next_ordinal(ctx: &Context, owner: Id) -> u32 { /// The operation the held modifiers pick now. pub(crate) fn current_operation(ctx: &Context) -> DropOperation { - operation(ctx, pointer::frame(ctx).mods) + operation(ctx, pointer::frame_raw(ctx).mods) } /// Whether the session's button was released in this pass. @@ -549,7 +563,7 @@ fn released(ctx: &Context) -> bool { if os { return board(ctx, |board| board.session.as_ref().is_some_and(|session| session.dropped == Some(frame))); } - pointer::frame(ctx).release == Some(button) + pointer::frame_raw(ctx).release == Some(button) || board(ctx, |board| board.session.as_ref().is_some_and(|session| session.released.is_some() && session.viewport != viewport)) } @@ -667,9 +681,9 @@ pub(crate) fn end_pass(ctx: &Context) { best.map(|(_, mark)| mark) }); let op = current_operation(ctx); - let over_this_window = pointer::frame(ctx).pos.is_some(); - let primary_down = pointer::with_pass_pointer(ctx, |pointer| pointer.primary_down); - let buttons = pointer::frame(ctx).buttons; + let over_this_window = pointer::frame_raw(ctx).pos.is_some(); + let primary_down = pointer::with_pass_raw(ctx, |pointer| pointer.primary_down); + let buttons = pointer::frame_raw(ctx).buttons; let frame = pass::root_frame_nr(ctx); let held = board(ctx, |board| board.session.as_ref().map(|session| (session.os, session.button, session.dropped))).is_none_or( |(os, button, dropped)| match (os, button) { @@ -681,7 +695,7 @@ pub(crate) fn end_pass(ctx: &Context) { let source = source_viewport(ctx); let is_source = source == Some(viewport); if is_source { - windows::note_source_pointer(ctx, viewport, pointer::frame(ctx).pos); + windows::note_source_pointer(ctx, viewport, pointer::frame_raw(ctx).pos); } let foreign_target = is_source && !held && foreign_winner(ctx, viewport); let running = board(ctx, |board| { diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 151339c28..ec3180b4a 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -89,6 +89,8 @@ pub struct Scoped { /// The key of everything above that the style cache depends on. #[doc(hidden)] pub key: EnvKey, + /// The key of what a memoized view shown in the scope inherits beyond `key` (`scope_key`), once a view asked. + scope_key: std::sync::OnceLock, /// Ambient control size; the root default is `Md`. pub size: ControlSize, /// How the icon-only buttons of the scope show their glyph; the root default and a layer's is `Control`. @@ -235,6 +237,8 @@ pub struct Inherited { pub(crate) host: Option>, #[doc(hidden)] pub values: AppValues, + /// The context the env was built in: the accessors of tracked inputs note their reads into its records. + pub(crate) ctx: Context, } impl Deref for Scoped { @@ -386,6 +390,41 @@ impl Scoped { self.offered = None; } + /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its + /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the + /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line + /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. The + /// flow fields of the enclosing body are not in it: a memoized view's content starts a layout room of its own + /// (`start_room`). Computed once per scope, on the first view that asks; the bytes it fed are counted then. + pub(crate) fn scope_key(&self) -> u128 { + *self.scope_key.get_or_init(|| { + use crate::contract::{MemoKey, MemoProps as _}; + let mut key = MemoKey::of_view(&self.ctx); + key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel)); + key.feed_hash(&(self.direction, self.text_direction, self.ids_stable, self.cell_fills, self.least, self.unbounded)); + key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view)))); + self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key); + self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key); + self.measure.key(&mut key); + // State a key cannot follow, rebuilt each pass: a view under it runs in every pass. + if self.item_facts.is_some() || self.inside_label.is_some() { + key.changes_every_pass(); + } + for id in self.commands.ids() { + id.key(&mut key); + } + key.feed_hash(&(std::mem::discriminant(&self.motion.mode), self.canvas_pattern, self.tab_toggles_chrome, self.today)); + key.feed_hash(&(Arc::as_ptr(&self.format) as usize, Arc::as_ptr(&self.dates) as usize)); + key.feed_hash(&self.host.as_ref().map(|host| Arc::as_ptr(host) as usize)); + let value_bytes = self.values.key(&mut key); + #[cfg(feature = "testing")] + crate::runtime::measure::count_memo_key_bytes(&self.ctx, key.bytes() + value_bytes); + #[cfg(not(feature = "testing"))] + let _ = value_bytes; + key.finish() + }) + } + /// The facts the collection recorded for the item `id`. pub(crate) fn facts_of(&self, id: Id) -> Option<&ItemFacts> { self.item_facts.as_deref().filter(|facts| facts.item == id) @@ -458,6 +497,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()); + 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()) .with_line(line_ratio) @@ -483,8 +525,10 @@ impl Env { canvas_pattern: root.canvas_pattern, host, values: root.values.clone(), + ctx: ctx.clone(), }), key, + scope_key: std::sync::OnceLock::new(), ink: Ink::default(), surface: SurfaceKind::Background, size: ControlSize::Md, @@ -579,6 +623,7 @@ impl Env { pub(crate) fn derive(&self, f: impl FnOnce(&mut Scoped)) -> Env { let mut scoped = (*self.scoped).clone(); f(&mut scoped); + scoped.scope_key = std::sync::OnceLock::new(); scoped.key = EnvKey::new(scoped.tokens.key(), scoped.direction, scoped.scale, scoped.os, scoped.active, scoped.values.style_hash()) .with_line(scoped.line_ratio) .with_words(scoped.words.generation()); @@ -602,6 +647,7 @@ impl Env { pub(crate) fn derive_local(&self, f: impl FnOnce(&mut Scoped)) -> Env { let mut scoped = (*self.scoped).clone(); f(&mut scoped); + scoped.scope_key = std::sync::OnceLock::new(); Env { scoped: Arc::new(scoped) } } diff --git a/crates/ui-contract/src/runtime/env/app_values.rs b/crates/ui-contract/src/runtime/env/app_values.rs index 35e0f58a4..41cb894ea 100644 --- a/crates/ui-contract/src/runtime/env/app_values.rs +++ b/crates/ui-contract/src/runtime/env/app_values.rs @@ -1,12 +1,14 @@ //! App-defined env values: EnvValue, StyleValue and AppValues. +use crate::contract::{MemoKey, MemoProps}; use std::any::{Any, TypeId}; use std::collections::HashMap; use std::hash::{Hash, Hasher}; use std::sync::Arc; -/// An app-defined value inherited down the tree like the library's own. -pub trait EnvValue: Clone + PartialEq + Send + Sync + 'static { +/// An app-defined value inherited down the tree like the library's own. `MemoProps`, because a memoized view under a +/// scope that sets it keys on it (`MemoView`): its key follows every value the view can read. +pub trait EnvValue: Clone + PartialEq + MemoProps + Send + Sync + 'static { /// A value that changes how components look is folded into the style key, so cached styles follow it. const AFFECTS_STYLE: bool = false; @@ -31,9 +33,20 @@ pub struct AppValues { entries: Arc, } +/// Feeds the value behind an entry into a key. +type Keyer = fn(&(dyn Any + Send + Sync), &mut MemoKey); + +fn keyer(value: &(dyn Any + Send + Sync), key: &mut MemoKey) { + if let Some(value) = value.downcast_ref::() { + value.key(key); + } +} + #[derive(Clone, Default)] struct ValueEntries { map: HashMap>, + /// How each value feeds a key, by type. + keyers: HashMap, /// The hash of each style-affecting value, by type. style: HashMap, /// The hash of every style-affecting value, independent of the order they were set in. @@ -68,6 +81,7 @@ impl AppValues { None => entries.style.remove(&TypeId::of::()), }; entries.map.insert(TypeId::of::(), Arc::new(value)); + entries.keyers.insert(TypeId::of::(), keyer::); entries.rehash(); self } @@ -77,6 +91,22 @@ impl AppValues { self.entries.style_hash } + /// Feeds every value into `key`, independent of the order they were set in: each value keys its own `MemoKey` (of + /// `key`'s view), and the sum of those keys is fed. Returns the bytes the values fed. + pub(crate) fn key(&self, key: &mut MemoKey) -> usize { + let (mut sum, mut bytes) = (0u128, 0); + for (ty, value) in &self.entries.map { + let Some(keyer) = self.entries.keyers.get(ty) else { continue }; + let mut one = key.child(); + one.feed_hash(ty); + keyer(&**value, &mut one); + sum = sum.wrapping_add(one.finish()); + bytes += one.bytes(); + } + key.write(&sum.to_le_bytes()); + bytes + } + /// A clone of the value, else `T::root()`. pub(crate) fn get(&self) -> T { self.entries.map.get(&TypeId::of::()).and_then(|value| value.downcast_ref::()).cloned().unwrap_or_else(T::root) @@ -92,6 +122,9 @@ impl AppValues { let entries = Arc::make_mut(&mut self.entries); for (ty, value) in &other.entries.map { entries.map.insert(*ty, Arc::clone(value)); + if let Some(keyer) = other.entries.keyers.get(ty) { + entries.keyers.insert(*ty, *keyer); + } match other.entries.style.get(ty) { Some(hash) => entries.style.insert(*ty, *hash), None => entries.style.remove(ty), diff --git a/crates/ui-contract/src/runtime/env/shell.rs b/crates/ui-contract/src/runtime/env/shell.rs index 3e36d5e4a..3dd178554 100644 --- a/crates/ui-contract/src/runtime/env/shell.rs +++ b/crates/ui-contract/src/runtime/env/shell.rs @@ -317,6 +317,28 @@ impl ShellCx { #[doc(hidden)] pub struct ShellEntry(#[doc(hidden)] pub Option); +/// The shell's input fields: the window, the body's mode, the reveal and visibility flags, the regions and the float +/// bounds. The registries the body writes into (revealed rects, the dialog count) are its output, not an input. +impl crate::contract::MemoProps for ShellEntry { + fn key(&self, key: &mut crate::contract::MemoKey) { + let Some(shell) = &self.0 else { return key.write_u32(0) }; + let Inner { window, mode, tab_reveal, edges, tabs, panels_hidden, regions, float_bounds, region, revealed_rects: _, dialog: _ } = + &*shell.inner; + key.write_u32(1); + key.feed_hash(window); + key.feed_hash(&std::mem::discriminant(mode)); + (*tab_reveal, *edges, *tabs, *panels_hidden).key(key); + regions.body.key(key); + key.write_u32(regions.slots.len() as u32); + for (slot, rect) in ®ions.slots { + slot.key(key); + rect.key(key); + } + float_bounds.key(key); + region.key(key); + } +} + impl EnvValue for ShellEntry { fn root() -> Self { ShellEntry(None) diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index 5e9de334e..a504fb4b7 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -52,7 +52,7 @@ const PERCENT: f64 = 100.0; /// The size of a point, the Point/Pica Size of the Units preference. An app sets it once on its root env with /// `RootEnv::values`; `Units` reads it for typed Points and Picas and for their conversion to other lengths. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, crate::contract::MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum PointSize { diff --git a/crates/ui-contract/src/runtime/env/values.rs b/crates/ui-contract/src/runtime/env/values.rs index 2c61c3e52..ef81fc3da 100644 --- a/crates/ui-contract/src/runtime/env/values.rs +++ b/crates/ui-contract/src/runtime/env/values.rs @@ -83,7 +83,7 @@ pub enum RowPressed { /// takes a box wider than its line, a select fits its widest entry up to a field length, a rule shows only with the /// member after it, and a row too long for its room narrows its last units first. A layer or pane opened from the bar /// starts without it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, crate::contract::MemoProps)] #[doc(hidden)] pub struct InBar(pub bool); diff --git a/crates/ui-contract/src/runtime/env/view.rs b/crates/ui-contract/src/runtime/env/view.rs index 3d4ca14d7..8e8deace2 100644 --- a/crates/ui-contract/src/runtime/env/view.rs +++ b/crates/ui-contract/src/runtime/env/view.rs @@ -113,11 +113,13 @@ impl<'a> EnvView<'a> { /// The platform and the running viewport's window facts: the OS, the capabilities and the window's kind, /// chrome, state, insets and focus. pub fn shell(&self) -> &'a ShellInfo { + crate::runtime::replay::note_input(&self.scoped.ctx, crate::runtime::inputs::Input::Shell); &self.scoped.shell } /// The keyboard layout: which character each key position types, for text that names a key. pub fn keyboard_layout(&self) -> &'a craft_keymap::Layout { + crate::runtime::replay::note_input(&self.scoped.ctx, crate::runtime::inputs::Input::Keyboard); &self.scoped.keyboard } diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 803cd2572..ef0b0791c 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -603,6 +603,7 @@ pub(crate) fn stop_rec(ctx: &Context, key: StopKey) -> Option { /// The registration of the stop focus is on. #[doc(hidden)] pub fn focused_rec(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Focus); let focused = egui_focus::focused(ctx); with(ctx, |state| { state.focus_now = focused; @@ -850,6 +851,11 @@ pub(crate) fn scope_chain(ctx: &Context, rec: &StopRec) -> Vec { }) } +/// Where key focus is, as the tracked input `Focus` compares it: the focused widget and whether its ring shows. +pub(crate) fn focus_state(ctx: &Context) -> (Option, bool) { + (egui_focus::focused(ctx), with(ctx, |state| state.visible)) +} + /// Whether focus sits inside a menu and arrived by keyboard. #[doc(hidden)] pub fn keyboard_in_menu(ctx: &Context) -> bool { diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 75214d3bd..189165888 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -543,7 +543,24 @@ pub(crate) fn facts(ctx: &Context) -> PassFacts { }) } -/// The running pass's time in seconds, read once by the begin hook. +/// The pass clock in seconds rounded down to a multiple of `step`, for content that changes with time (a rescan every +/// few seconds, a "5 minutes ago"): the running view is shown again at the next multiple. Between two steps a run +/// shows what the last one showed, so a memoized view that reads it replays until the next step and runs then. A +/// `step` of zero or less returns the clock and shows the view again in every pass. +pub fn stepped_clock(ctx: &Context, step: f64) -> f64 { + let now = clock(ctx); + if step <= 0.0 { + crate::runtime::motion::note_unsettled(ctx); + return now; + } + let at = (now / step).floor() * step; + crate::runtime::motion::wake_at(ctx, at + step); + at +} + +/// The running pass's time in seconds, read once by the begin hook. Content that changes with time reads +/// [`stepped_clock`], which shows it again when the value it read changes; this read notes nothing, for timing +/// events in the component that has the pointer or the focus. #[doc(hidden)] pub fn clock(ctx: &Context) -> f64 { match running(ctx) { diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs new file mode 100644 index 000000000..0d3bbe8f9 --- /dev/null +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -0,0 +1,145 @@ +//! 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), 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. +//! +//! The scroll view a nested `Lazy` child decides by is noted too, as `Scroll`; it has no generation: the record keeps +//! the view it ran with, and a replay needs the same view. + +use crate::runtime::egui::pass; +use crate::runtime::frame::PerViewport; +use egui::Context; +use std::any::Any; + +/// A framework input a view reads outside its props. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub(crate) enum Input { + /// The modifiers held (`Cx::modifiers`, `pointer::mods`). + Modifiers, + /// The pointer's frame (`pointer::frame`, `pointer::with_pass_pointer`). + Pointer, + /// 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`). + Shell, + /// The keyboard layout (`EnvView::keyboard_layout`). + Keyboard, + /// The keymap: the chords commands show (`commands::chord`, `bindings`, `holder`, a resolved command's chord). + Keymap, + /// A drag session and its payloads (`drag::active`, `started`). + Drag, + /// Where key focus is (`focus::focused_rec`, `focus_in_scope`, `commands::focus_within`). + Focus, + /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). + Overlays, + /// The view of the scroll area a nested `Lazy` child decides by. No generation: compared by value. + Scroll, +} + +impl Input { + const ALL: [Input; 10] = [ + Input::Modifiers, + Input::Pointer, + Input::Keys, + Input::Shell, + Input::Keyboard, + Input::Keymap, + Input::Drag, + Input::Focus, + Input::Overlays, + Input::Scroll, + ]; + + fn bit(self) -> u16 { + 1 << self as u16 + } +} + +/// The inputs a run read. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Inputs(u16); + +impl Inputs { + pub(crate) fn insert(&mut self, input: Input) { + self.0 |= input.bit(); + } + + pub(crate) fn extend(&mut self, other: Inputs) { + self.0 |= other.0; + } + + pub(crate) fn contains(self, input: Input) -> bool { + self.0 & input.bit() != 0 + } + + /// The inputs in the set that have a generation. + pub(crate) fn generational(self) -> impl Iterator { + Input::ALL.into_iter().filter(move |input| *input != Input::Scroll && self.contains(*input)) + } +} + +/// The generations of the inputs a run read, taken when it started. +pub(crate) type Seen = [u64; Input::ALL.len()]; + +/// A viewport's generations, and the last value each observed input had. +#[derive(Default)] +struct Generations { + gens: Seen, + last: [Option>; Input::ALL.len()], +} + +impl crate::runtime::frame::Stored for Generations {} + +fn with(ctx: &Context, f: impl FnOnce(&mut Generations) -> R) -> R { + PerViewport::::with(ctx, pass::current_viewport(ctx), f) +} + +/// Moves the generation of `input` in the running viewport: its value changed. +pub(crate) fn bump(ctx: &Context, input: Input) { + with(ctx, |generations| generations.gens[input as usize] += 1); +} + +/// Notes the value `input` has now in the running viewport, and moves its generation when it differs from the last +/// one noted. +pub(crate) fn observe(ctx: &Context, input: Input, value: T) { + with(ctx, |generations| { + let slot = &mut generations.last[input as usize]; + if slot.as_ref().and_then(|last| last.downcast_ref::()) != Some(&value) { + if slot.is_some() { + generations.gens[input as usize] += 1; + } + *slot = Some(Box::new(value)); + } + }); +} + +/// 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. +pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { + match input { + Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(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_generation(ctx), + Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {} + } + with(ctx, |generations| generations.gens[input as usize]) +} + +/// The generation of every input now, for a run that starts. +pub(crate) fn seen(ctx: &Context) -> Seen { + let mut seen = Seen::default(); + for input in Input::ALL { + seen[input as usize] = generation(ctx, input); + } + seen +} + +/// Whether an input of `read` has another generation now than in `seen`. +pub(crate) fn moved(ctx: &Context, read: Inputs, seen: &Seen) -> bool { + read.generational().any(|input| generation(ctx, input) != seen[input as usize]) +} diff --git a/crates/ui-contract/src/runtime/keys.rs b/crates/ui-contract/src/runtime/keys.rs index 61f108ae8..e39d2b30f 100644 --- a/crates/ui-contract/src/runtime/keys.rs +++ b/crates/ui-contract/src/runtime/keys.rs @@ -28,7 +28,7 @@ pub use claims::take_claimed; pub use craft_behavior::{AccessRequest, Intent, MoveMods, NavMove, PartRef}; #[doc(hidden)] pub use input::{down, keyed}; -pub(crate) use input::{input_hook, queue_nav, take_menu_keys, take_nav}; +pub(crate) use input::{input_hook, keys_state, queue_nav, take_menu_keys, take_nav}; pub use intents::Intents; #[doc(hidden)] pub use intents::intents_of; diff --git a/crates/ui-contract/src/runtime/keys/input.rs b/crates/ui-contract/src/runtime/keys/input.rs index f4effa840..b3b978b2a 100644 --- a/crates/ui-contract/src/runtime/keys/input.rs +++ b/crates/ui-contract/src/runtime/keys/input.rs @@ -522,12 +522,20 @@ fn note_down(down: &mut Vec, event: &KeyEvent) { /// down). #[doc(hidden)] pub fn down(ctx: &Context) -> Vec { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keys); current(ctx, |stage| stage.down.clone()) } +/// The key state, as the tracked input `Keys` compares it: the keys down, whether a key arrived and Caps Lock. +pub(crate) fn keys_state(ctx: &Context) -> (Vec, bool, bool) { + let (down, keyed) = current(ctx, |stage| (stage.down.clone(), stage.keyed)); + (down, keyed, crate::runtime::lock_keys::caps_on(ctx)) +} + /// 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 { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keys); current(ctx, |stage| stage.keyed) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index f1b7a5fca..9505c0683 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -19,6 +19,7 @@ use crate::runtime::egui::areas::Layer; use crate::runtime::egui::{focus as focus_state, input as input_state, pass}; use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame::{self, PerViewport}; +use crate::runtime::inputs::{self, Input}; use crate::runtime::reads::BindKey; use crate::runtime::replay::{self, Record}; use crate::style::EnvKey; @@ -60,6 +61,15 @@ pub(crate) struct View { } impl View { + /// Whether the children of `a` and `b` decide alike (`decide`): the same area, view rect, content rect, axes, + /// direction and reveal. The anchor is the area's own record of where its children landed, not an input of theirs. + pub(crate) fn decides_alike(a: Option, b: Option) -> bool { + match (a, b) { + (Some(a), Some(b)) => View { anchor: None, ..a } == View { anchor: None, ..b }, + (a, b) => a.is_none() && b.is_none(), + } + } + /// How far `rect` starts from the content's start edge, along each axis. pub(crate) fn start_of(&self, rect: Rect) -> Vec2 { let x = if self.rtl { self.content.max.x - rect.max.x } else { rect.min.x - self.content.min.x }; @@ -186,6 +196,12 @@ struct Settled { output: Option, /// The generation of ended shown lives after the run (`memory::ended_generation`). lives: u64, + /// The generation of each framework input when the run started (`runtime::inputs`): a memoized view whose run read + /// one replays only while it is the same. + seen: inputs::Seen, + /// The view of the scroll area around it when it ran: a run that decided a nested `Lazy` child by it replays only + /// while it is the same. + view: Option, } /// What changed in the frame for every settling child. @@ -365,9 +381,13 @@ 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. /// +/// - for a memoized view: 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, and no command waits for a command scope instance +/// of it. +/// /// A memoized view's props hold every input it reads, so the two rules that infer a change of app data (input /// arrived, a repaint was asked) do not apply to it. -pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, key: Key) -> Option { +pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option, view: Option, key: Key) -> Option { let input = ctx.input(|input| { input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) }); @@ -413,10 +433,13 @@ pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, pl let kind = usize::from(!sizing); settled.map(|settled| (entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(settled.rect.size()), settled)) }); - // The pointer over it, a press that started on it, and the memory of the components it showed are read outside the - // store. + // The pointer over it, a press that started on it, the memory of the components it showed, the framework inputs it + // read and the commands queued for its instances are read outside the store. let (size, settled) = settled?; - if engaged(ctx, &settled) || crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives) { + if engaged(ctx, &settled) + || crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives) + || (memo && moved(ctx, &settled, place.map(|_| view))) + { with(ctx, |store, pass_nr, _| { if let Some(entry) = store.entries.get_mut(&id) { entry.replays = Some((pass_nr, false)); @@ -427,6 +450,17 @@ pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, pl Some(size) } +/// 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 (`view`, in a real run: 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. +fn moved(ctx: &Context, settled: &Settled, view: Option>) -> bool { + let facts = &settled.record.facts; + inputs::moved(ctx, facts.inputs, &settled.seen) + || (facts.inputs.contains(Input::Scroll) && view.is_some_and(|view| !View::decides_alike(settled.view, view))) + || crate::runtime::commands::queued_for(ctx, &facts.instances) +} + /// Whether the pointer is over the rect the settled run took on its layer, or a press that is held started there. fn engaged(ctx: &Context, settled: &Settled) -> bool { let rect = settled.rect.intersect(settled.place.clip); @@ -459,20 +493,23 @@ pub(crate) fn keep(ctx: &Context, owner: Option, id: Id) { }); } -/// What a settling child's real run found besides its record: what it ran for, the edit serial when it started -/// (`edits`) and what a memoized view's run returned. +/// What a settling child's real run found besides its record: what it ran for, the edit serial and the framework +/// inputs' generations when it started (`edits`, `inputs::seen`), the scroll view around it and what a memoized view's +/// run returned. pub(crate) struct Ran { pub(crate) key: Key, pub(crate) edits: u64, + pub(crate) seen: inputs::Seen, + pub(crate) view: Option, pub(crate) output: Option, } /// Keeps the real run `record` of the settling child `id`, which ran at `place` and took `rect`. -pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, Ran { key, edits, output }: Ran) { +pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, Ran { key, edits, seen, view, output }: Ran) { let targets = focus::targets(ctx); let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&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 }; + let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now, key, pass: 0, edits, output, lives, seen, view }; settled.engaged |= engaged(ctx, &settled); with(ctx, |store, pass_nr, frame| { settled.frame = frame; diff --git a/crates/ui-contract/src/runtime/lock_keys.rs b/crates/ui-contract/src/runtime/lock_keys.rs index 948ec7779..453e18d85 100644 --- a/crates/ui-contract/src/runtime/lock_keys.rs +++ b/crates/ui-contract/src/runtime/lock_keys.rs @@ -16,6 +16,12 @@ struct Reading { /// Whether Caps Lock is on in this pass: the state injected input holds, else the platform's. #[doc(hidden)] pub fn caps_lock(ctx: &Context) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Keys); + caps_on(ctx) +} + +/// `caps_lock` without noting the read. +pub(crate) fn caps_on(ctx: &Context) -> bool { if let Some(on) = crate::runtime::egui::injected::caps_lock(ctx) { return on; } diff --git a/crates/ui-contract/src/runtime/mod.rs b/crates/ui-contract/src/runtime/mod.rs index 6ec5255d8..aa8c2d54e 100644 --- a/crates/ui-contract/src/runtime/mod.rs +++ b/crates/ui-contract/src/runtime/mod.rs @@ -10,6 +10,7 @@ pub mod env; pub mod focus; pub mod frame; pub mod ime; +pub(crate) mod inputs; pub mod inspect; pub mod install; pub mod keys; diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index a2ddc33f1..c7e75cd97 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -224,7 +224,7 @@ pub fn now() -> web_time::Instant { } /// Marks the running viewport as having an animation that is not at its end value. -fn note_unsettled(ctx: &Context) { +pub(crate) fn note_unsettled(ctx: &Context) { crate::runtime::replay::note_unsettled(ctx); PerViewport::::with(ctx, pass::current_viewport(ctx), |wanted| wanted.unsettled = true); } @@ -396,7 +396,7 @@ impl Driver<'_> { } /// Asks for a pass of the running viewport at `at`; the earliest request wins. -fn wake_at(ctx: &Context, at: f64) { +pub(crate) fn wake_at(ctx: &Context, at: f64) { crate::runtime::replay::note_wake(ctx, at); PerViewport::::with(ctx, pass::current_viewport(ctx), |wanted| wanted.wake = Some(wanted.wake.map_or(at, |old| old.min(at)))); } diff --git a/crates/ui-contract/src/runtime/overlay.rs b/crates/ui-contract/src/runtime/overlay.rs index 1553099a3..a69b0b7c3 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -292,9 +292,15 @@ fn with_persist(ctx: &Context, viewport: ViewportId, f: impl FnOnce(&mut Pers /// Whether the layer `id` was shown last frame. pub fn is_open(ctx: &Context, id: Id) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| pass.last.iter().any(|entry| entry.id == id)) } +/// The layers shown last frame, as the tracked input `Overlays` compares them: each one's id and whether it exits. +pub(crate) fn open_state(ctx: &Context) -> Vec<(Id, bool)> { + with_pass(ctx, |pass| pass.last.iter().map(|entry| (entry.id, entry.exiting)).collect()) +} + /// Queues a close of the layer `id` (a popup or a container). The owner's step 9 or `OverlayUi::show` collects it and /// step 15 writes it. pub fn request_close(ctx: &Context, id: Id, why: CloseReason) { @@ -361,6 +367,7 @@ pub(crate) fn peek_close(ctx: &Context, id: Id) -> Option { /// Whether any layer of the running viewport that `filter` counts was shown last frame. pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| { pass.last.iter().filter(|entry| !entry.exiting).any(|entry| match filter { OpenFilter::Any => true, @@ -372,6 +379,7 @@ pub fn any_open(ctx: &Context, filter: OpenFilter) -> bool { /// The layer that receives Cancel: the newest member of the topmost family that takes keys. pub fn top(ctx: &Context) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); let viewport = pass::current_viewport(ctx); let raised = with_persist(ctx, viewport, |persist| persist.raised.clone()); with_pass(ctx, |pass| { @@ -396,6 +404,7 @@ pub(crate) fn popup_above(ctx: &Context, layer: Layer, below: Layer) -> bool { /// `id` and everything opened from inside it, shown last frame. pub fn family(ctx: &Context, id: Id) -> SmallVec<[Id; 4]> { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| { let mut out: SmallVec<[Id; 4]> = SmallVec::new(); if pass.last.iter().any(|entry| entry.id == id) { @@ -420,6 +429,7 @@ pub(crate) fn open_entries(ctx: &Context) -> Vec { /// The entry of the layer `id` shown last frame. #[doc(hidden)] pub fn entry(ctx: &Context, id: Id) -> Option { + crate::runtime::replay::note_input(ctx, crate::runtime::inputs::Input::Overlays); with_pass(ctx, |pass| pass.last.iter().find(|entry| entry.id == id).cloned()) } @@ -479,7 +489,7 @@ pub(crate) fn begin_layer(ctx: &Context, id: Id, tier: Tier, exiting: bool, side }); let viewport = pass::current_viewport(ctx); let first = (pass::root_frame_nr(ctx), pass::pass_nr(ctx, viewport)); - let (down, released) = pointer::with_pass_pointer(ctx, |read| { + let (down, released) = pointer::with_pass_raw(ctx, |read| { let released = read.frame.as_ref().filter(|frame| frame.release == Some(craft_behavior::PointerButton::Primary)).map(|frame| frame.pos); (read.primary_down, released) }); @@ -720,7 +730,7 @@ fn families(entries: &[OpenEntry], raised: &IdMap) -> Vec> { pub(crate) fn end_pass(ctx: &Context) { let viewport = pass::current_viewport(ctx); let (current, last_ids) = with_pass(ctx, |pass| (pass.current.clone(), pass.last.iter().map(|entry| entry.id).collect::>())); - let pressed = pointer::frame(ctx).press.map(|press| press.origin); + let pressed = pointer::frame_raw(ctx).press.map(|press| press.origin); let order = with_persist(ctx, viewport, |persist| { let stamp = |id: Id, persist: &mut Persist| { persist.counter += 1; diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index b2511074e..a2db5670d 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -7,6 +7,7 @@ use crate::runtime::drag; use crate::runtime::egui::areas::{self, Layer}; use crate::runtime::egui::{input, pass}; use crate::runtime::frame::{PerViewport, Stamped}; +use crate::runtime::inputs::{self, Input}; use craft_behavior::{ Buttons, MultiTouch, PartRef, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressStart, ResolveFor, Shape, Winner, count_clicks, resolve, @@ -218,6 +219,25 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) { stirred: read.stirred, }; let hover_at = pass_pointer.hover; + // The pointer and the modifiers are tracked inputs: their generations move when the held facts change or the pass + // brings pointer events. + if let Some(frame) = &pass_pointer.frame { + inputs::observe(ctx, Input::Modifiers, frame.mods); + inputs::observe(ctx, Input::Pointer, (frame.pos, frame.buttons, pass_pointer.hover, pass_pointer.primary_down)); + let events = frame.delta != Vec2::ZERO + || frame.press.is_some() + || frame.release.is_some() + || frame.scroll != Vec2::ZERO + || frame.zoom != 1.0 + || frame.rotation != 0.0 + || frame.multi_touch.is_some() + || pass_pointer.stirred + || pass_pointer.focus_lost + || !pass_pointer.events.is_empty(); + if events { + inputs::bump(ctx, Input::Pointer); + } + } PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| *record = Arc::new(pass_pointer)); PerViewport::::with(ctx, viewport, |shapes| { shapes.last = std::mem::take(&mut shapes.this); @@ -259,9 +279,17 @@ pub(crate) fn pass_pointer(ctx: &Context) -> Arc { PerViewport::>>::with_pass(ctx, viewport, pass::pass_nr(ctx, viewport), |_, _| {}, |record| Arc::clone(record)) } -/// Reads what the begin hook read of the running pass in place, without cloning its events. +/// Reads what the begin hook read of the running pass in place, without cloning its events. A tracked input +/// (`runtime::inputs`): a memoized view that reads it runs when the pointer changes. #[doc(hidden)] pub fn with_pass_pointer(ctx: &Context, f: impl FnOnce(&PassPointer) -> R) -> R { + crate::runtime::replay::note_input(ctx, Input::Pointer); + with_pass_raw(ctx, f) +} + +/// `with_pass_pointer` without noting the read: for the hit sensing, press and drag steps of the component under the +/// pointer, which the pointer engages, and for the pass machinery. +pub(crate) fn with_pass_raw(ctx: &Context, f: impl FnOnce(&PassPointer) -> R) -> R { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); PerViewport::>>::with_pass(ctx, viewport, pass_nr, |_, _| {}, |record| f(record)) @@ -280,12 +308,26 @@ pub(crate) fn buttons_of(ctx: &Context, viewport: ViewportId) -> Buttons { /// Reads the running pass's pointer frame, `None` before the begin hook, and its hover position in place. pub(crate) fn with_frame(ctx: &Context, f: impl FnOnce(Option<&PointerFrame>, Option) -> R) -> R { - with_pass_pointer(ctx, |pointer| f(pointer.frame.as_ref(), pointer.hover)) + with_pass_raw(ctx, |pointer| f(pointer.frame.as_ref(), pointer.hover)) } -/// The running pass's pointer input. +/// The running pass's pointer input. A tracked input (`runtime::inputs`): a memoized view that reads it runs when the +/// pointer changes. A view that reads only the modifiers reads [`mods`]. pub fn frame(ctx: &Context) -> PointerFrame { - with_pass_pointer(ctx, |pointer| pointer.frame.clone()).unwrap_or_else(|| PointerFrame { + crate::runtime::replay::note_input(ctx, Input::Pointer); + frame_raw(ctx) +} + +/// The modifiers held in the running pass, with the latched ones (`PointerFrame::mods`). A tracked input: a memoized +/// view that reads them runs when they change, and only then. +pub fn mods(ctx: &Context) -> Mods { + crate::runtime::replay::note_input(ctx, Input::Modifiers); + with_pass_raw(ctx, |pointer| pointer.frame.as_ref().map_or(Mods::NONE, |frame| frame.mods)) +} + +/// `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 { pos: None, delta: Vec2::ZERO, buttons: Buttons::empty(), @@ -356,7 +398,7 @@ pub(crate) fn cancel_of_pass(ctx: &Context) -> Option { let viewport = pass::current_viewport(ctx); let pass_nr = pass::pass_nr(ctx, viewport); let requested = PerViewport::::with(ctx, viewport, |memory| memory.requested.filter(|(nr, _)| *nr == pass_nr).map(|(_, reason)| reason)); - requested.or_else(|| with_pass_pointer(ctx, |pointer| pointer.focus_lost).then_some(PressCancel::FocusLost)) + requested.or_else(|| with_pass_raw(ctx, |pointer| pointer.focus_lost).then_some(PressCancel::FocusLost)) } /// Writes `shapes` of the arena rooted at `root`, shown through `clip` (layer space), into the running pass's shape diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 0ee8bacb3..0a97fe0db 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -13,6 +13,7 @@ use crate::runtime::egui::areas::Layer; use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame; +use crate::runtime::inputs::{Input, Inputs}; use crate::runtime::pass_state; use crate::runtime::reads::BindKey; use egui::{Context, IdSet}; @@ -122,6 +123,11 @@ pub(crate) struct Facts { /// The components whose memory owners registered in the run (`memory::register_owner`): a replay needs their /// shown-tier state still kept (`memory::ended_since`). pub(crate) owners: Vec, + /// The framework inputs the run read outside its props (`runtime::inputs`). + pub(crate) inputs: Inputs, + /// 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, } /// What one real run of a region added to its pass. @@ -166,6 +172,8 @@ pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { outer.facts.owners.extend(open.facts.owners.iter().copied()); outer.facts.wake = min_wake(outer.facts.wake, open.facts.wake); outer.facts.reads.extend(open.facts.reads.iter().copied()); + outer.facts.inputs.extend(open.facts.inputs); + outer.facts.instances.extend(open.facts.instances.iter().copied()); } else { recorder.journal.clear(); } @@ -207,6 +215,7 @@ pub(crate) fn replay(ctx: &Context, record: &Record) { } with_open(ctx, |facts| { facts.reads.extend(record.facts.reads.iter().copied()); + facts.inputs.extend(record.facts.inputs); facts.wake = min_wake(facts.wake, record.facts.wake); }); } @@ -249,6 +258,16 @@ pub(crate) fn note_read(ctx: &Context, key: BindKey) { }); } +/// Notes that the running code read the framework input `input`. +pub(crate) fn note_input(ctx: &Context, input: Input) { + with_open(ctx, |facts| facts.inputs.insert(input)); +} + +/// Notes that the command scope instance `id` registered in the running code. +pub(crate) fn note_instance(ctx: &Context, id: egui::Id) { + with_open(ctx, |facts| facts.instances.push(id)); +} + /// Notes that something in the running code still moves. pub(crate) fn note_unsettled(ctx: &Context) { with_open(ctx, |facts| facts.unsettled = true); diff --git a/crates/ui-contract/tests/it/contract/fixes.rs b/crates/ui-contract/tests/it/contract/fixes.rs index fc1da8d47..e9c4e5fbd 100644 --- a/crates/ui-contract/tests/it/contract/fixes.rs +++ b/crates/ui-contract/tests/it/contract/fixes.rs @@ -18,7 +18,7 @@ use std::cell::RefCell; type Log = RefCell>; /// A style-affecting app value the body hands to its children. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnvValue)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnvValue, craft_ui::contract::MemoProps)] #[env(style, root = Tone(1))] struct Tone(u8); diff --git a/crates/ui-contract/tests/it/runtime/env.rs b/crates/ui-contract/tests/it/runtime/env.rs index d6155f189..0923dfab5 100644 --- a/crates/ui-contract/tests/it/runtime/env.rs +++ b/crates/ui-contract/tests/it/runtime/env.rs @@ -6,7 +6,7 @@ use craft_ui::runtime::env::{Env, EnvValue, with_env}; use craft_ui::testing::memory::scoped; use craft_ui::testing::{Frames, trial}; -#[derive(Clone, Debug, PartialEq, EnvValue)] +#[derive(Clone, Debug, PartialEq, EnvValue, craft_ui::contract::MemoProps)] #[env(root = Units("pt"))] struct Units(&'static str); diff --git a/crates/ui-panels/src/sections/footer.rs b/crates/ui-panels/src/sections/footer.rs index 517dbe2a4..f92486eb3 100644 --- a/crates/ui-panels/src/sections/footer.rs +++ b/crates/ui-panels/src/sections/footer.rs @@ -237,7 +237,7 @@ impl

Outcome for DropActionOutput

{ } /// Whether an accepted drag is over the enclosing drop slot, which the slot's body reads to show its child enabled. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] struct Accepting(bool); impl EnvValue for Accepting { diff --git a/crates/ui-widgets/src/choice/radio.rs b/crates/ui-widgets/src/choice/radio.rs index 518309780..0b9af26ae 100644 --- a/crates/ui-widgets/src/choice/radio.rs +++ b/crates/ui-widgets/src/choice/radio.rs @@ -23,7 +23,7 @@ impl GroupKind for RadioKind { } /// Whether the group's value is refused or an error, read by its members so each radio shows the invalid look. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, crate::contract::MemoProps)] struct GroupInvalid(bool); impl EnvValue for GroupInvalid { diff --git a/crates/ui-widgets/src/menu/level.rs b/crates/ui-widgets/src/menu/level.rs index e6b9e8eb3..d90e50878 100644 --- a/crates/ui-widgets/src/menu/level.rs +++ b/crates/ui-widgets/src/menu/level.rs @@ -97,6 +97,13 @@ pub(crate) struct MenuLevel { state: Option>>, } +/// A handle to the level's state, which its rows write during the pass: a view under a menu level runs in every pass. +impl crate::contract::MemoProps for MenuLevel { + fn key(&self, key: &mut crate::contract::MemoKey) { + key.changes_every_pass(); + } +} + impl PartialEq for MenuLevel { fn eq(&self, other: &Self) -> bool { match (&self.state, &other.state) { diff --git a/crates/ui-widgets/tests/it/body/memo_reads.rs b/crates/ui-widgets/tests/it/body/memo_reads.rs new file mode 100644 index 000000000..81c945782 --- /dev/null +++ b/crates/ui-widgets/tests/it/body/memo_reads.rs @@ -0,0 +1,335 @@ +//! Memoized views and the framework inputs they read outside their props (`runtime::inputs`): a change of one runs +//! only the views that read it. Count trials, as relations: how views took part in a pass (`last_pass_memo_runs`). + +use craft_keymap::Overrides; +use craft_ui::buttons::Button; +use craft_ui::contract::{ContainerProps, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; +use craft_ui::runtime::commands::{self, CommandInput, CommandRef}; +use craft_ui::runtime::env::{Env, EnvValue, with_env}; +use craft_ui::runtime::{frame, pointer}; +use craft_ui::testing::input::{key_press, text}; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::{Frames, MemoRun, last_pass_memo_runs, trial}; +use craft_ui_test_kit::body::Slab; +use craft_ui_test_kit::windows::Windows; +use egui::{Context, Key, Modifiers, Pos2, Rect, Ui, Vec2, ViewportInfo}; +use std::cell::Cell; +use std::sync::Arc; + +/// Idle frames that settle every view after a change, hover fades included. +const SETTLE: usize = 30; +const SIZE: Vec2 = Vec2::new(140.0, 40.0); +/// A place outside every view. +const AWAY: Pos2 = Pos2::new(400.0, 400.0); + +/// Where the view `at` is shown, each in its own region. +fn region(at: usize) -> Rect { + Rect::from_min_size(Pos2::new(10.0, 10.0 + 50.0 * at as f32), SIZE) +} + +/// How the views whose props type is named `name` took part in the last pass. +fn runs_of(ctx: &Context, name: &str) -> Vec { + last_pass_memo_runs(ctx).into_iter().filter(|(of, _, _)| of.ends_with(name)).map(|(_, _, run)| run).collect() +} + +/// A view that reads no framework input. +#[derive(MemoProps)] +struct Plain; + +fn plain(_: &mut Plain, ui: &mut Ui) { + Button::new("Plain").show(ui); +} + +fn show_plain(ui: &mut Ui) { + in_region(ui, region(0), |ui| MemoView::new("plain", Plain, plain).show(ui)); +} + +/// A view that shows whether Alt is held. +#[derive(MemoProps)] +struct Alt; + +fn alt(_: &mut Alt, ui: &mut Ui) { + let held = pointer::mods(ui.ctx()).alt; + Button::new(if held { "Alt held" } else { "Alt up" }).show(ui); +} + +/// Holding Alt runs only the view that reads the modifiers, once when it goes down and once when it comes up; a reader +/// that was not shown while Alt went down runs when it is shown again. +#[trial] +fn holding_alt_runs_only_the_views_that_read_modifiers() { + let reader_shown = Cell::new(true); + let mut show = |ui: &mut Ui| { + show_plain(ui); + if reader_shown.get() { + in_region(ui, region(1), |ui| MemoView::new("alt", Alt, alt).show(ui)); + } + }; + let mut frames = Frames::new(); + frames.frame(vec![pointer_away()], &mut show); + frames.idle(SETTLE, &mut show); + for held in [Modifiers::ALT, Modifiers::NONE] { + frames.hold(held); + frames.frame(vec![egui::Event::ModifiersChanged(held)], &mut show); + assert_eq!(runs_of(&frames.ctx, "Alt"), [MemoRun::Ran], "the reader runs when Alt changes to {held:?}"); + assert_eq!(runs_of(&frames.ctx, "Plain"), [MemoRun::Replayed], "a view that does not read the modifiers replays"); + frames.frame(vec![], &mut show); + assert_eq!(runs_of(&frames.ctx, "Alt"), [MemoRun::Replayed], "the reader settles on {held:?}"); + } + reader_shown.set(false); + frames.idle(2, &mut show); + frames.hold(Modifiers::ALT); + frames.frame(vec![egui::Event::ModifiersChanged(Modifiers::ALT)], &mut show); + frames.idle(2, &mut show); + reader_shown.set(true); + frames.frame(vec![], &mut show); + assert_eq!(runs_of(&frames.ctx, "Alt"), [MemoRun::Ran], "a reader absent while Alt went down runs when shown again"); +} + +fn pointer_away() -> egui::Event { + craft_ui::testing::pointer::moved(AWAY) +} + +/// A view that shows where the pointer is. +#[derive(MemoProps)] +struct Follow; + +fn follow(_: &mut Follow, ui: &mut Ui) { + let at = pointer::frame(ui.ctx()).pos.map(|pos| (pos.x.round(), pos.y.round())); + Button::new(format!("{at:?}")).show(ui); +} + +/// A pointer move outside every view runs the view that reads the pointer's frame; the others replay. +#[trial] +fn a_pointer_reader_runs_on_pointer_motion_and_the_others_replay() { + let mut show = |ui: &mut Ui| { + show_plain(ui); + in_region(ui, region(1), |ui| MemoView::new("follow", Follow, follow).show(ui)); + }; + let mut frames = Frames::new(); + frames.frame(vec![pointer_away()], &mut show); + frames.idle(SETTLE, &mut show); + assert_eq!(runs_of(&frames.ctx, "Follow"), [MemoRun::Replayed], "a still pointer replays its reader"); + frames.frame(vec![craft_ui::testing::pointer::moved(AWAY + Vec2::new(20.0, 0.0))], &mut show); + assert_eq!(runs_of(&frames.ctx, "Follow"), [MemoRun::Ran], "the pointer moved: its reader runs"); + assert_eq!(runs_of(&frames.ctx, "Plain"), [MemoRun::Replayed], "a view that does not read the pointer replays"); +} + +/// A view that shows the window's display state. +#[derive(MemoProps)] +struct WindowState; + +fn window_state(_: &mut WindowState, ui: &mut Ui) { + let state = Env::of(ui).view().shell().window.state; + Button::new(format!("{state:?}")).show(ui); +} + +/// Maximizing the window runs only the view that reads the window facts. +#[trial] +fn a_shell_change_runs_only_its_readers() { + let windows = Windows::new(); + let mut show = |ui: &mut Ui| { + show_plain(ui); + in_region(ui, region(1), |ui| MemoView::new("window", WindowState, window_state).show(ui)); + }; + for _ in 0..SETTLE { + windows.frame(vec![], vec![], &mut show); + } + assert_eq!(runs_of(&windows.ctx, "WindowState"), [MemoRun::Replayed], "an idle frame replays the reader"); + windows.root_info(ViewportInfo { maximized: Some(true), ..ViewportInfo::default() }); + windows.frame(vec![], vec![], &mut show); + assert_eq!(runs_of(&windows.ctx, "WindowState"), [MemoRun::Ran], "the window was maximized: its reader runs"); + assert_eq!(runs_of(&windows.ctx, "Plain"), [MemoRun::Replayed], "a view that does not read the window facts replays"); + windows.frame(vec![], vec![], &mut show); + assert_eq!(runs_of(&windows.ctx, "WindowState"), [MemoRun::Replayed], "the reader settles on the new facts"); +} + +/// A view that shows the character the Q key types. +#[derive(MemoProps)] +struct KeyCap; + +fn key_cap(_: &mut KeyCap, ui: &mut Ui) { + let typed = Env::of(ui).view().keyboard_layout().char_at(craft_keymap::Key::Q); + Button::new(format!("{typed:?}")).show(ui); +} + +/// Typing "a" on the Q key (an AZERTY layout) teaches the layout: only the view that reads the layout runs. +#[trial] +fn a_keyboard_layout_change_runs_only_its_readers() { + let mut show = |ui: &mut Ui| { + show_plain(ui); + in_region(ui, region(1), |ui| MemoView::new("cap", KeyCap, key_cap).show(ui)); + }; + let mut frames = Frames::new(); + frames.frame(vec![pointer_away()], &mut show); + frames.idle(SETTLE, &mut show); + frames.frame(vec![key_press(Key::Q, Modifiers::NONE), text("a")], &mut show); + assert_eq!(runs_of(&frames.ctx, "KeyCap"), [MemoRun::Ran], "the layout learned a key: its reader runs"); + assert_eq!(runs_of(&frames.ctx, "Plain"), [MemoRun::Replayed], "a view that does not read the layout replays"); + frames.frame(vec![], &mut show); + assert_eq!(runs_of(&frames.ctx, "KeyCap"), [MemoRun::Replayed], "the reader settles on the new layout"); +} + +/// A view that shows the chord of Undo. +#[derive(MemoProps)] +struct UndoChord; + +fn undo_chord(_: &mut UndoChord, ui: &mut Ui) { + let chord = commands::chord(ui.ctx(), &CommandRef::new("edit.undo")); + Button::new(format!("{chord:?}")).show(ui); +} + +/// A new keymap (the user's overrides changed) runs only the view that shows a chord. +#[trial] +fn a_keymap_change_runs_only_views_that_show_chords() { + let mut show = |ui: &mut Ui| { + show_plain(ui); + in_region(ui, region(1), |ui| MemoView::new("chord", UndoChord, undo_chord).show(ui)); + }; + let mut frames = Frames::new(); + frames.frame(vec![pointer_away()], &mut show); + frames.idle(SETTLE, &mut show); + frames.commands(CommandInput::new().overrides(Arc::new(Overrides::default()))); + frames.frame(vec![], &mut show); + assert_eq!(runs_of(&frames.ctx, "UndoChord"), [MemoRun::Ran], "the keymap was built again: the chord's view runs"); + assert_eq!(runs_of(&frames.ctx, "Plain"), [MemoRun::Replayed], "a view that shows no chord replays"); + frames.frame(vec![], &mut show); + assert_eq!(runs_of(&frames.ctx, "UndoChord"), [MemoRun::Replayed], "the chord's view settles on the new keymap"); +} + +thread_local! { + static CLOCK_RUNS: Cell = const { Cell::new(0) }; +} + +/// A view that shows the whole seconds on the pass clock. +#[derive(MemoProps)] +struct Seconds; + +fn seconds(_: &mut Seconds, ui: &mut Ui) { + CLOCK_RUNS.with(|runs| runs.set(runs.get() + 1)); + let at = frame::stepped_clock(ui.ctx(), 1.0); + Button::new(format!("{at} s")).show(ui); +} + +/// A view that reads the clock in whole seconds runs once per second and replays in the frames between; the view +/// beside it never runs. +#[trial] +fn a_clock_reader_runs_only_at_its_wake_time() { + const STEP: f64 = 0.25; + const SECONDS: usize = 3; + let mut show = |ui: &mut Ui| { + show_plain(ui); + in_region(ui, region(1), |ui| MemoView::new("seconds", Seconds, seconds).show(ui)); + }; + let mut frames = Frames::new(); + frames.still_clock(); + frames.frame(vec![pointer_away()], &mut show); + frames.idle(SETTLE, &mut show); + CLOCK_RUNS.with(|runs| runs.set(0)); + let mut ran_at = Vec::new(); + for frame in 0..SECONDS * 4 { + frames.advance(STEP); + frames.frame(vec![], &mut show); + if runs_of(&frames.ctx, "Seconds") == [MemoRun::Ran] { + ran_at.push(frame); + } + assert_eq!(runs_of(&frames.ctx, "Plain"), [MemoRun::Replayed], "the view that reads no clock replays in frame {frame}"); + } + assert_eq!(CLOCK_RUNS.with(Cell::get), SECONDS, "one run per second: {ran_at:?}"); + assert_eq!(ran_at, [3, 7, 11], "the runs fall on the frames that reach a whole second"); +} + +/// An app value the scope around a view sets. +#[derive(Clone, Copy, Debug, PartialEq, MemoProps)] +struct Tint(u8); + +impl EnvValue for Tint { + fn root() -> Self { + Tint(0) + } +} + +/// A view that shows the scope's tint and whether it is enabled. +#[derive(MemoProps)] +struct Scoped; + +fn scoped(_: &mut Scoped, ui: &mut Ui) { + let env = Env::of(ui); + Button::new(format!("{:?} {}", env.view().get::(), env.enabled)).show(ui); +} + +/// A view's scope disabling it, or setting another app value, runs it once; then it replays. +#[trial] +fn a_scope_change_around_a_view_runs_it() { + let enabled = Cell::new(true); + let tint = Cell::new(Tint(1)); + let mut show = |ui: &mut Ui| { + show_plain(ui); + in_region(ui, region(1), |ui| { + with_env( + ui, + |set| { + set.enabled = Some(enabled.get()); + set.values.set(tint.get()); + }, + |ui| MemoView::new("scoped", Scoped, scoped).show(ui), + ) + }); + }; + let mut frames = Frames::new(); + frames.frame(vec![pointer_away()], &mut show); + frames.idle(SETTLE, &mut show); + assert_eq!(runs_of(&frames.ctx, "Scoped"), [MemoRun::Replayed], "an unchanged scope replays the view"); + for change in [|_: &Cell, tint: &Cell| tint.set(Tint(2)), |enabled: &Cell, _: &Cell| enabled.set(false)] { + change(&enabled, &tint); + frames.frame(vec![], &mut show); + assert_eq!(runs_of(&frames.ctx, "Scoped"), [MemoRun::Ran], "the scope changed: the view runs"); + assert_eq!(runs_of(&frames.ctx, "Plain"), [MemoRun::Replayed], "the view outside the scope replays"); + frames.frame(vec![], &mut show); + assert_eq!(runs_of(&frames.ctx, "Scoped"), [MemoRun::Replayed], "the view settles in the new scope"); + } +} + +thread_local! { + static ROWS_RUNS: Cell = const { Cell::new(0) }; +} + +/// A view of rows that run only in view (`Lazy`), inside a scrolling body. +#[derive(MemoProps)] +struct Rows; + +fn rows(_: &mut Rows, ui: &mut Ui) { + const ROWS: usize = 30; + ROWS_RUNS.with(|runs| runs.set(runs.get() + 1)); + for at in 0..ROWS { + craft_ui::contract::Lazy::new(at, 40.0).show(ui, |ui| { + Button::new(format!("Row {at}")).show(ui); + }); + } +} + +/// A view in a scrolling body whose rows decide by the scroll view runs when the body scrolls, though the pointer that +/// scrolled it is beside the view, never over it; then it replays. +#[trial] +fn a_view_with_lazy_rows_runs_when_its_scroll_area_scrolls() { + let view = Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(300.0, 200.0)); + let mut show = |ui: &mut Ui| { + in_region(ui, view, |ui| { + Slab::new(ContainerProps::new().sizing(Sizing::Fill).scroll(Scroll::vertical())).id_salt("area").show(ui, |ui, _| { + MemoView::new("rows", Rows, rows).show(ui); + }); + }); + }; + let beside = Pos2::new(view.max.x - 20.0, view.center().y); + let mut frames = Frames::new(); + frames.frame(vec![craft_ui::testing::pointer::moved(beside)], &mut show); + frames.idle(SETTLE, &mut show); + ROWS_RUNS.with(|runs| runs.set(0)); + frames.frame(vec![], &mut show); + assert_eq!(ROWS_RUNS.with(Cell::get), 0, "an idle frame replays the rows"); + frames.frame(vec![craft_ui::testing::pointer::wheel(-200.0)], &mut show); + assert!(ROWS_RUNS.with(Cell::get) > 0, "the body scrolled: the view of rows ran"); + frames.idle(SETTLE, &mut show); + ROWS_RUNS.with(|runs| runs.set(0)); + frames.frame(vec![], &mut show); + assert_eq!(ROWS_RUNS.with(Cell::get), 0, "the view settles at the new scroll position"); +} diff --git a/crates/ui-widgets/tests/it/body/mod.rs b/crates/ui-widgets/tests/it/body/mod.rs index adfd16218..7a4c15fd0 100644 --- a/crates/ui-widgets/tests/it/body/mod.rs +++ b/crates/ui-widgets/tests/it/body/mod.rs @@ -1,5 +1,6 @@ //! The body step and the mount host: regions, scrolling, move and resize, and viewport mounts. +mod memo_reads; mod memo_view; mod scroll; mod settle;