diff --git a/Cargo.lock b/Cargo.lock index 52b706b5a..e17999446 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2372,7 +2372,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "bytemuck", "emath", @@ -2381,7 +2381,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "ahash", "bytemuck", @@ -2416,7 +2416,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "accesskit", "ahash", @@ -2435,7 +2435,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "ahash", "bytemuck", @@ -2454,7 +2454,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "block2 0.6.2", "bytemuck", @@ -2474,7 +2474,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "bytemuck", "egui", @@ -2487,7 +2487,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "eframe", "egui", @@ -2510,7 +2510,7 @@ checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "bytemuck", ] @@ -2571,7 +2571,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" dependencies = [ "ahash", "bytemuck", @@ -2597,7 +2597,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" [[package]] name = "equivalent" @@ -9149,19 +9149,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/aiongg/egui.git?rev=4b93a86c52348eb53e883c9b6b9f59c573608e07#4b93a86c52348eb53e883c9b6b9f59c573608e07" +source = "git+https://github.com/aiongg/egui.git?rev=3f56db2d932d5ce35ff420f8679896b646be9e77#3f56db2d932d5ce35ff420f8679896b646be9e77" diff --git a/Cargo.toml b/Cargo.toml index cd70743ac..8a73c3a6a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -196,20 +196,20 @@ hayro-jbig2 = { path = "vendor/hayro-jbig2" } hayro-cmap = { path = "vendor/hayro-cmap" } hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } -ecolor = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -emath = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -epaint = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -epaint_default_fonts = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui-winit = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui-wgpu = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui_glow = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui_extras = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui_kittest = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui_system_font_provider = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -eframe = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui_demo_lib = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } -egui_inspection = { git = "https://github.com/aiongg/egui.git", rev = "4b93a86c52348eb53e883c9b6b9f59c573608e07" } +ecolor = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +emath = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +epaint = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +epaint_default_fonts = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui-winit = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui-wgpu = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui_glow = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui_extras = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui_kittest = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui_system_font_provider = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +eframe = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui_demo_lib = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } +egui_inspection = { git = "https://github.com/aiongg/egui.git", rev = "3f56db2d932d5ce35ff420f8679896b646be9e77" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 4616d12a0..6bbde21fe 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -1,12 +1,14 @@ -//! `Lazy`: a child of a scroll area that runs only while it is in view (`runtime::lazy`). +//! `Lazy`: a child of a scroll area that runs only while it is in view, and a child that runs only when something it +//! shows changed (`runtime::lazy`). use crate::layout::{flow_region, take_in_flow}; use crate::runtime::egui::alloc; use crate::runtime::env::Env; use crate::runtime::focus; use crate::runtime::layout_memory; -use crate::runtime::lazy::{self, Decision}; +use crate::runtime::lazy::{self, Decision, Place}; use crate::runtime::memory::sub; +use crate::runtime::replay; use egui::{Pos2, Rect, Ui, UiBuilder, Vec2}; use std::hash::Hash; @@ -25,11 +27,15 @@ use std::hash::Hash; /// The key names the child among every `Lazy` of its scroll area, nested containers included. The idiom is /// `Lazy::new(key, estimate).show(ui, |ui| ..)` around each large child (a card, a section of a panel) in the scroll /// body. +/// +/// A settling child ([`Lazy::settles`]) also keeps what its last run painted and registered, and while it is settled +/// it adds that again in place of running, in view or not. #[must_use] pub struct Lazy { key: u64, estimate: f32, reveal: bool, + settles: bool, } impl Lazy { @@ -39,7 +45,7 @@ impl Lazy { use std::hash::Hasher; let mut hasher = std::collections::hash_map::DefaultHasher::new(); key.hash(&mut hasher); - Lazy { key: hasher.finish(), estimate, reveal: false } + Lazy { key: hasher.finish(), estimate, reveal: false, settles: false } } /// When `reveal` holds, the scroll area glides until the child starts at the view's start (as far as the @@ -50,6 +56,21 @@ impl Lazy { self } + /// When `settles` holds, the child runs only when something it shows may have changed, inside a scroll area or + /// not. Otherwise it repaints its last run and registers again what that run registered (its stops, hit shapes, + /// widgets and accessibility nodes), as if it ran. It runs in a frame where any of these holds: + /// - the pointer is over it or was in its last run, a press started on it, or it holds focus or held it; + /// - an animation in it is not at its end, something in it asked for a repaint, or a wake time it asked for came; + /// - a bound value it read was written; + /// - its place, room, clip or scale differs from its last run; + /// - the frame or the one before had input other than pointer motion, the app asked for a repaint, or a given + /// value was edited: the framework cannot see which children show plain app data, so every child runs then; + /// - its last run showed an overlay or painted on another layer. + pub fn settles(mut self, settles: bool) -> Lazy { + self.settles = settles; + self + } + /// Runs `add` in a child `Ui` placed in flow in `ui`, or takes the remembered extent there; `None` when it did not /// run. pub fn show(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option { @@ -65,6 +86,9 @@ impl Lazy { // The child is not part of its body's transcript: in a real run it counts there by its extent, whether it // runs or not, so what scrolls into reach does not change the body's content. let real = !sizing && !crate::runtime::measure::active(&ctx); + let owner = view.map(|view| view.owner); + // A run around this one that is replayed later keeps the child's entry. + replay::journal(&ctx, || move |ctx: &egui::Context| lazy::keep(ctx, owner, id)); if let Some(view) = view { let at = |size: Vec2| { let x = if rtl { available.max.x - size.x } else { available.min.x }; @@ -84,21 +108,48 @@ impl Lazy { return None; } } - let mark = focus::mark(&ctx); let layout = *ui.layout(); + let place = Place { room: available, clip: ui.clip_rect(), layer: ui.layer_id(), layout, pixels_per_point: ctx.pixels_per_point() }; + if self.settles + && let Some(size) = lazy::settled(&ctx, owner, id, sizing, real.then_some(place)) + { + let (took, _) = take_in_flow(ui, size); + if real { + layout_memory::backstop(&ctx, id, size); + lazy::replay_settled(&ctx, id); + if let Some(view) = view { + lazy::place(&ctx, &view, id, took); + } + } + return None; + } + let mark = focus::mark(&ctx); + let records = self.settles && real; + if records { + replay::open(&ctx); + } let mut child = alloc::child(ui, UiBuilder::new().max_rect(available).layout(layout).scope_id(id)); // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. let out = layout_memory::boundary(&ctx, false, || add(&mut child)); let rect = child.min_rect(); + // The child `Ui` writes its widget rect when it drops: the record holds it as written. + drop(child); + let record = records.then(|| replay::close(&ctx, place.layer)); if real { layout_memory::backstop(&ctx, id, rect.size()); } alloc::advance_past(ui, rect); - if let Some(view) = view { - lazy::shown(&ctx, view.owner, id, rect.size(), sizing, real.then(|| focus::transcript(&ctx, mark))); - if real { - lazy::place(&ctx, &view, id, rect); - } + if view.is_some() || self.settles { + let registered = real.then(|| record.as_ref().map_or_else(|| focus::transcript(&ctx, mark), |record| record.focus.clone())); + lazy::shown(&ctx, owner, id, rect.size(), sizing, registered); + } + if let Some(view) = view + && real + { + lazy::place(&ctx, &view, id, rect); + } + if let Some(record) = record { + lazy::ran(&ctx, id, record, place, rect); } Some(out) } diff --git a/crates/ui-contract/src/contract/steps/apply.rs b/crates/ui-contract/src/contract/steps/apply.rs index cf279cbab..440c4b2e4 100644 --- a/crates/ui-contract/src/contract/steps/apply.rs +++ b/crates/ui-contract/src/contract/steps/apply.rs @@ -155,11 +155,15 @@ pub(crate) fn rerun_after_edit( leaf: bool, ) { if edit.given { + crate::runtime::lazy::unsettle(&p.core_ref().ctx); sizing::request_discard(&p.core_ref().ctx, sizing::Rerun::Edit); return; } let Some(key) = edit.key.filter(|_| edit.written || edit.shown) else { return }; let (ctx, id) = (p.core_ref().ctx.clone(), p.core_ref().id); + if edit.written { + crate::runtime::lazy::note_edit(&ctx, key); + } let earlier = reads::earlier(&ctx, key, id); if edit.written && earlier.other { return sizing::request_discard(&ctx, sizing::Rerun::Edit); diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index da2f1e527..558b6bf1d 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -148,6 +148,11 @@ pub(crate) struct ResetFact { #[derive(Default)] pub(crate) struct Stack(Vec); +/// How many label and merge scopes are open around the running code. +pub(crate) fn depth(ctx: &Context) -> usize { + pass_state::with::(ctx, |stack| stack.0.len()) +} + /// Opens the scope of `container`; its body shows inside it. pub(crate) fn begin(ctx: &Context, container: Id, owner: Id, kind: Kind) { pass_state::with::(ctx, |stack| { diff --git a/crates/ui-contract/src/runtime/commands/board.rs b/crates/ui-contract/src/runtime/commands/board.rs index 2f2b99820..e2e7a75d5 100644 --- a/crates/ui-contract/src/runtime/commands/board.rs +++ b/crates/ui-contract/src/runtime/commands/board.rs @@ -372,6 +372,7 @@ pub fn focus_within(ctx: &Context, id: Id) -> bool { /// Records that the container `id` is an instance of `scope` in the running pass of its viewport. pub(crate) fn register_instance(ctx: &Context, scope: CommandScope, id: Id) { + crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_instance(ctx, scope, 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) { diff --git a/crates/ui-contract/src/runtime/drag.rs b/crates/ui-contract/src/runtime/drag.rs index dbeac58e1..d56326356 100644 --- a/crates/ui-contract/src/runtime/drag.rs +++ b/crates/ui-contract/src/runtime/drag.rs @@ -419,6 +419,7 @@ pub(crate) fn show_mark(ctx: &Context, mark: Option) { /// Records that `owner`'s `ordinal`th target on `layer` accepts at the pointer, with its mark in layer space. A /// `window` target covers the whole window. pub(crate) fn register(ctx: &Context, owner: Id, layer: Layer, mark: DropMark, window: bool) { + crate::runtime::replay::journal(ctx, || move |ctx: &Context| register(ctx, owner, layer, mark, window)); let mark = match areas::layer_map(ctx, layer) { Some(map) => mark.mapped(|point| map.to_screen(point)), None => mark, diff --git a/crates/ui-contract/src/runtime/egui/access.rs b/crates/ui-contract/src/runtime/egui/access.rs index 22c32652d..7d02b4ed0 100644 --- a/crates/ui-contract/src/runtime/egui/access.rs +++ b/crates/ui-contract/src/runtime/egui/access.rs @@ -45,7 +45,7 @@ pub(crate) fn with_parent(builder: egui::UiBuilder, parent: Id) -> egui::UiBuild /// Creates the node of `id` empty if it has none. False while AccessKit is off or the widget is invisible (a /// popup in its first-show sizing pass). pub(crate) fn create_node(ctx: &Context, id: Id) -> bool { - with_emitted(ctx, |emitted| emitted.emit(id)); + emit(ctx, id); ctx.accesskit_node_builder(id, |_| ()).is_some() } @@ -104,7 +104,13 @@ fn with_emitted(ctx: &Context, f: impl FnOnce(&mut Emitted) -> R) -> R { /// Makes `parent` the node `id` attaches to. Call it before the node of `id` is created. pub(crate) fn register_parent(ctx: &Context, id: Id, parent: Id) { ctx.register_accesskit_parent(id, parent); + emit(ctx, id); +} + +/// Notes that the runtime emitted the node of `id`. +fn emit(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| emitted.emit(id)); + crate::runtime::replay::journal(ctx, || move |ctx: &Context| emit(ctx, id)); } /// Notes that the node of the text widget `widget` folds into the node of `owner`. @@ -112,6 +118,7 @@ fn note_folded(ctx: &Context, widget: Id, owner: Id) { with_emitted(ctx, |emitted| { emitted.folded.insert(widget, owner); }); + crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_folded(ctx, widget, owner)); } /// Notes that the runtime wrote the node of `id`. @@ -119,6 +126,7 @@ pub(crate) fn note_written(ctx: &Context, id: Id) { with_emitted(ctx, |emitted| { emitted.written.insert(id); }); + crate::runtime::replay::journal(ctx, || move |ctx: &Context| note_written(ctx, id)); } /// The pass-end step: the children of each node the runtime wrote follow the order the runtime emitted them in, diff --git a/crates/ui-contract/src/runtime/egui/repaint.rs b/crates/ui-contract/src/runtime/egui/repaint.rs index 2411e549f..b69792cf8 100644 --- a/crates/ui-contract/src/runtime/egui/repaint.rs +++ b/crates/ui-contract/src/runtime/egui/repaint.rs @@ -4,16 +4,19 @@ use egui::Context; /// Asks for one more pass after this one. pub(crate) fn request(ctx: &Context) { + crate::runtime::replay::note_unsettled(ctx); ctx.request_repaint(); } /// Asks for a pass of `viewport` at once. pub(crate) fn request_of(ctx: &Context, viewport: egui::ViewportId) { + crate::runtime::replay::note_unsettled(ctx); ctx.request_repaint_of(viewport); } /// Asks for one pass of `viewport` after `seconds`; the earliest request of a frame wins. pub(crate) fn request_after(ctx: &Context, viewport: egui::ViewportId, seconds: f64) { + crate::runtime::replay::note_wake(ctx, crate::runtime::frame::clock(ctx) + seconds); ctx.request_repaint_after_for(std::time::Duration::from_secs_f64(seconds.max(0.0)), viewport); } diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index f6acd827b..282366ab5 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -367,6 +367,7 @@ pub(crate) fn announce(ctx: &Context, text: String) { /// Asks for another pass of the viewport the running pass belongs to. #[doc(hidden)] pub fn request_repaint(ctx: &Context) { + crate::runtime::lazy::unsettle(ctx); raw_input::request_repaint_of(ctx, pass::current_viewport(ctx)); } diff --git a/crates/ui-contract/src/runtime/keys/nodes.rs b/crates/ui-contract/src/runtime/keys/nodes.rs index 50b14d7a3..9426a018b 100644 --- a/crates/ui-contract/src/runtime/keys/nodes.rs +++ b/crates/ui-contract/src/runtime/keys/nodes.rs @@ -19,6 +19,7 @@ pub(crate) fn redirect_node(ctx: &Context, node: Id, owner: Id, part: PartRef) { /// Records the expanded state of the node registered by `register_node`: an `Expand` or `Collapse` request on a node /// with the state asks to change it, and acts as the node's activation. pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option) { + crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_expanded(ctx, node, expanded)); current(ctx, |stage| { if let Some(entry) = stage.nodes.get_mut(&node_key(node)) { entry.expanded = expanded; @@ -28,6 +29,7 @@ pub(crate) fn register_expanded(ctx: &Context, node: Id, expanded: Option) /// Registers an AccessKit node so a request that targets it reaches `owner`. pub(crate) fn register_node(ctx: &Context, node: Id, owner: Id, part: Option, focusable: bool) { + crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_node(ctx, node, owner, part, focusable)); current(ctx, |stage| { stage.nodes.insert(node_key(node), Node { owner, part, focusable, expanded: None }); }); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 0fda179bc..74f62effe 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -287,6 +287,7 @@ pub(crate) fn read(ctx: &Context, id: Id) -> Option { if crate::runtime::measure::active(ctx) { return peeking(ctx, |read| read(id)); } + journal_keep(ctx, id); let moment = Moment::of(ctx); with(ctx, &moment, |memory| { let entry = memory.entries.entry(id).or_default(); @@ -315,6 +316,7 @@ pub(crate) fn peeking(ctx: &Context, f: impl FnOnce(&dyn Fn(Id) -> Option(ctx: &Context, body: Id, key: K) { + journal_keep(ctx, body); let moment = Moment::of(ctx); with(ctx, &moment, |memory| { let Some(at) = memory.measuring.iter().rposition(|open| matches!(open, Open::Body { id, .. } if *id == body)) else { return }; @@ -723,6 +726,7 @@ pub(crate) fn kept_serves(ctx: &Context, b if !reuse_allowed(ctx) || !crate::runtime::measure::outermost(ctx) { return false; } + journal_keep(ctx, body); let moment = Moment::of(ctx); if with(ctx, &moment, |memory| memory.probing()) { return false; @@ -877,6 +881,24 @@ pub(crate) fn ask_discard(ctx: &Context) { with(ctx, &moment, |memory| memory.ask = true); } +/// Notes in the run records open around the running code that a replay keeps the entry and the kept transcript of +/// `id`: the replayed run does not reach them, and an entry no pass touched in a frame is dropped. +fn journal_keep(ctx: &Context, id: Id) { + crate::runtime::replay::journal(ctx, || { + move |ctx: &Context| { + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| { + if let Some(entry) = memory.entries.get_mut(&id) { + entry.touched = moment.frame; + } + if let Some(kept) = memory.kept.get_mut(&id) { + kept.touched = moment.frame; + } + }); + } + }); +} + /// The end hook: asks egui for at most one discard pass per frame, and for a repaint when a change cannot get one, so /// the next frame shows it; then drops the entries no pass touched in the last frame. pub(crate) fn end_hook(ctx: &Context) { @@ -946,6 +968,7 @@ pub(crate) mod guard { ("runtime::drag::", "drag board and targets: read; targets register in real runs"), ("runtime::overlay::", "overlays: read; opens and closes are effects skipped in measuring runs"), ("contract::overlay::popups::Popups", "popups: read"), + ("runtime::replay::Recorder", "run records: opened and closed by real runs; registrations journal there only while one is open"), ( "runtime::lazy::Store", "lazy extents: the kept extent of content out of view, its own mechanism; a pass a kept transcript serves decides in its real run, which compares each row by its backstop", diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index ed10b6c4b..61873e815 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -8,11 +8,17 @@ //! The store also hands a scroll area, for the run that lays its content out, where its children start: the child //! its scroll position names (`Anchor`) and the first child at or after the view's start, so the area keeps the //! content in view in place when extents before it change. +//! +//! A settling child (`Lazy::settles`) also keeps its last real run (`runtime::replay`): while it is settled, it adds +//! that run to the pass again in place of running, in view or not, inside a scroll area or not. It is settled when +//! nothing the framework tracks has changed for it since that run (`settled`). use crate::runtime::egui::pass; use crate::runtime::focus::{self, Transcript}; -use crate::runtime::frame::PerViewport; -use egui::{Context, Id, Rect, Vec2}; +use crate::runtime::frame::{self, PerViewport}; +use crate::runtime::reads::BindKey; +use crate::runtime::replay::{self, Record}; +use egui::{Context, Id, LayerId, Layout, Rect, Vec2}; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -104,13 +110,53 @@ struct Entry { focus: Arc, /// Whether this pass skips the child, under the pass number that decided it. decided: Option<(u64, bool)>, + /// The last real run of a settling child. + settled: Option>, + /// Whether this pass replays the settling child's last run, under the pass number that decided it. + replays: Option<(u64, bool)>, /// The last frame that read or wrote the entry. touched: u64, } +/// Where a settling child ran: it is settled only while it runs at the same place. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Place { + /// The region its parent offered it. + pub(crate) room: Rect, + pub(crate) clip: Rect, + pub(crate) layer: LayerId, + pub(crate) layout: Layout, + pub(crate) pixels_per_point: f32, +} + +/// The last real run of a settling child. +struct Settled { + record: Record, + /// The frame it ran in. + frame: u64, + place: Place, + /// The rect its content took. + rect: Rect, + /// The pointer was over it, or one of its stops held focus: it runs again to show that they left. + engaged: bool, +} + +/// What changed in the frame for every settling child. +#[derive(Default)] +struct Changes { + /// Every settling child runs through this frame: a frame with input other than pointer motion, an app's repaint + /// request or an edit of a given value unsettles every child for that frame and the next. + unsettled_through: u64, + /// The pass whose input was looked at. + scanned: u64, + /// The bound values written in a frame, and the frame. + edited: (u64, HashSet), +} + #[derive(Default)] pub(crate) struct Store { entries: HashMap, + changes: Changes, /// The last frame each scroll area reached one of its children in. reached: HashMap, /// What the real run that lays a scroll area's content out found, by area, from `begin` to `placed`. @@ -121,10 +167,12 @@ pub(crate) struct Store { impl Store { /// The entry of the child `id` of the scroll area `owner`, touched in `frame`. - fn touch(&mut self, owner: Id, id: Id, frame: u64) -> &mut Entry { - self.reached.insert(owner, frame); + fn touch(&mut self, owner: Option, id: Id, frame: u64) -> &mut Entry { + if let Some(owner) = owner { + self.reached.insert(owner, frame); + } let entry = self.entries.entry(id).or_default(); - entry.owner = Some(owner); + entry.owner = owner; entry.touched = frame; entry } @@ -139,9 +187,9 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { if store.pruned != frame { store.pruned = frame; let reached = &store.reached; - store - .entries - .retain(|_, entry| entry.touched + 1 >= frame || entry.owner.and_then(|owner| reached.get(&owner)).is_none_or(|ran| ran + 1 < frame)); + store.entries.retain(|_, entry| { + entry.touched + 1 >= frame || entry.owner.is_some_and(|owner| reached.get(&owner).is_none_or(|ran| ran + 1 < frame)) + }); let owners: HashSet = store.entries.values().filter_map(|entry| entry.owner).collect(); store.reached.retain(|owner, _| owners.contains(owner)); } @@ -156,7 +204,7 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) -> Rect, sizing: bool, estimate: Vec2) -> Decision { let targets = crate::runtime::focus::targets(ctx); with(ctx, |store, pass_nr, frame| { - let entry = store.touch(view.owner, id, frame); + let entry = store.touch(Some(view.owner), id, frame); let kind = usize::from(!sizing); // A child the other kind of run showed last takes that run's extent. let size = entry.sizes[kind].or(entry.sizes[1 - kind]).unwrap_or(estimate); @@ -175,7 +223,7 @@ pub(crate) fn decide(ctx: &Context, id: Id, view: &View, at: impl FnOnce(Vec2) - /// Records what a run that showed the child `id` found: its extent in a run of this kind and, from a real run, what /// it registered with the focus service. -pub(crate) fn shown(ctx: &Context, owner: Id, id: Id, size: Vec2, sizing: bool, registered: Option) { +pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, size: Vec2, sizing: bool, registered: Option) { with(ctx, |store, _, frame| { let entry = store.touch(owner, id, frame); entry.sizes[usize::from(!sizing)] = Some(size); @@ -194,10 +242,135 @@ pub(crate) fn replay(ctx: &Context, id: Id) { } } +/// Whether the settling child `id` adds its last real run to this pass in place of running, and the extent that run +/// took in a run of this kind (`sizing`). The first run of a pass decides from what changed since that run; a real run +/// also needs the child at the `place` it ran at, which a measuring run cannot tell. +/// +/// It replays when its last run was in an earlier frame and since then: +/// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no wake time reached; +/// - the pointer is not over it, no press started on it and none of its widgets is dragged or holds egui focus, and +/// none of that held in its last run; +/// - none of its stops holds focus or is the target of a focus request, now or in its last run; +/// - no bound value it read was written this frame (`note_edit`); +/// - no frame unsettled every child (`unsettle`): input other than pointer motion this frame or the one before, an app's +/// repaint request or an edit of a given value; +/// - the run did nothing a replay cannot repeat (`runtime::replay`). +pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, sizing: bool, place: Option) -> Option { + let input = ctx.input(|input| { + input.events.iter().any(|event| !matches!(event, egui::Event::PointerMoved(_) | egui::Event::MouseMoved(_) | egui::Event::PointerGone)) + }); + let targets = focus::targets(ctx); + let now = frame::clock(ctx); + let held = (ctx.dragged_id(), ctx.memory(|memory| memory.focused())); + let settled = with(ctx, |store, pass_nr, frame| { + if store.changes.scanned != pass_nr { + store.changes.scanned = pass_nr; + if input { + store.changes.unsettled_through = store.changes.unsettled_through.max(frame + 1); + } + } + let changes = &store.changes; + // Usually empty: only the values written this frame. + let edited = (changes.edited.0 == frame).then(|| changes.edited.1.clone()); + let unsettled = changes.unsettled_through >= frame; + let entry = store.touch(owner, id, frame); + let replays = match entry.replays { + Some((decided_in, replays)) if decided_in == pass_nr => replays, + _ => { + let replays = !unsettled + && entry.settled.as_ref().is_some_and(|settled| { + let facts = &settled.record.facts; + settled.frame < frame + && !settled.engaged + && !facts.unsettled + && !facts.blocked + && facts.wake.is_none_or(|at| at > now) + && edited.as_ref().is_none_or(|edited| facts.reads.is_disjoint(edited)) + && !settled.record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))) + && ![held.0, held.1].iter().flatten().any(|widget| settled.record.widgets.contains(widget)) + }); + entry.replays = Some((pass_nr, replays)); + replays + } + }; + let at = |settled: &Settled| place.is_none_or(|place| place == settled.place); + let settled = entry.settled.clone().filter(|settled| replays && at(settled)); + if replays && settled.is_none() { + entry.replays = Some((pass_nr, false)); + } + 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, or a press that started on it, is read outside the store. + let (size, settled) = settled?; + if engaged(ctx, &settled) { + with(ctx, |store, pass_nr, _| { + if let Some(entry) = store.entries.get_mut(&id) { + entry.replays = Some((pass_nr, false)); + } + }); + return None; + } + Some(size) +} + +/// 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); + let screen = ctx.layer_transform_to_global(settled.place.layer).map_or(rect, |transform| transform * rect); + ctx.rect_contains_pointer(settled.place.layer, rect) + || ctx.input(|input| input.pointer.any_down() && input.pointer.press_origin().is_some_and(|origin| screen.contains(origin))) +} + +/// Adds the last real run of the settling child `id` to the running pass, in place of running it. +pub(crate) fn replay_settled(ctx: &Context, id: Id) { + let settled = with(ctx, |store, _, _| store.entries.get(&id).and_then(|entry| entry.settled.clone())); + if let Some(settled) = settled { + replay::replay(ctx, &settled.record); + } +} + +/// Keeps the entry of the child `id` this frame: a replayed run does not reach the children inside it. +pub(crate) fn keep(ctx: &Context, owner: Option, id: Id) { + with(ctx, |store, _, frame| { + store.touch(owner, id, frame); + }); +} + +/// 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) { + let targets = focus::targets(ctx); + let engaged_now = record.focus.stop_ids().any(|stop| targets.contains(&Some(stop))); + let mut settled = Settled { record, frame: 0, place, rect, engaged: engaged_now }; + settled.engaged |= engaged(ctx, &settled); + with(ctx, |store, _, frame| { + settled.frame = frame; + if let Some(entry) = store.entries.get_mut(&id) { + entry.settled = Some(Arc::new(settled)); + } + }); +} + +/// Notes that the bound value `key` was written in this frame: a settling child that read it runs. +pub(crate) fn note_edit(ctx: &Context, key: BindKey) { + with(ctx, |store, _, frame| { + let edited = &mut store.changes.edited; + if edited.0 != frame { + *edited = (frame, HashSet::new()); + } + edited.1.insert(key); + }); +} + +/// Unsettles every settling child for this frame and the next: a change the framework cannot attribute to a child. +pub(crate) fn unsettle(ctx: &Context) { + with(ctx, |store, _, frame| store.changes.unsettled_through = store.changes.unsettled_through.max(frame + 1)); +} + /// Records the extent of a row of the collection `owner` that was built this pass. The collection places the rows it /// does not build by it (its item layout answers for rows it never built). pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) { - shown(ctx, owner, id, size, false, None); + shown(ctx, Some(owner), id, size, false, None); } /// Runs `f` with a reader of the extents the rows of the collection `owner` had in the last pass that built them, for diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index ae105216d..90ad280a8 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -163,6 +163,7 @@ struct Seen(u64); /// Registers `owner`'s pass, at step 3: eviction tests only owners. Shown entries of an owner not registered /// for 3 passes of the viewport that last showed it and 0.5 s are evicted by `evict`. pub(crate) fn register_owner(ctx: &Context, owner: Id) { + crate::runtime::replay::journal(ctx, || move |ctx: &Context| register_owner(ctx, owner)); let facts = frame::facts(ctx); pass_state::with::(ctx, |reg| { reg.owners.insert(owner, OwnerRecord { viewport: facts.viewport, pass: facts.pass_nr, at: facts.now }); diff --git a/crates/ui-contract/src/runtime/mod.rs b/crates/ui-contract/src/runtime/mod.rs index a09b4a2ad..62cac5a2d 100644 --- a/crates/ui-contract/src/runtime/mod.rs +++ b/crates/ui-contract/src/runtime/mod.rs @@ -26,6 +26,7 @@ pub(crate) mod pass_state; pub mod pending; pub mod pointer; pub(crate) mod reads; +pub(crate) mod replay; pub mod requests; pub mod sampler; pub mod toast; diff --git a/crates/ui-contract/src/runtime/motion.rs b/crates/ui-contract/src/runtime/motion.rs index dabc3d777..a2ddc33f1 100644 --- a/crates/ui-contract/src/runtime/motion.rs +++ b/crates/ui-contract/src/runtime/motion.rs @@ -225,6 +225,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) { + crate::runtime::replay::note_unsettled(ctx); PerViewport::::with(ctx, pass::current_viewport(ctx), |wanted| wanted.unsettled = true); } @@ -396,6 +397,7 @@ impl Driver<'_> { /// Asks for a pass of the running viewport at `at`; the earliest request wins. 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 b783d1b4f..a8a7662a6 100644 --- a/crates/ui-contract/src/runtime/overlay.rs +++ b/crates/ui-contract/src/runtime/overlay.rs @@ -386,6 +386,7 @@ pub(crate) fn appears(ctx: &Context, id: Id, exiting: bool) -> bool { /// Marks the layer `id`'s body as running, so layers opened from inside it become its children. A layer shown /// again while it fades out opens anew: it appears in this frame and pass. pub(crate) fn begin_layer(ctx: &Context, id: Id, exiting: bool) { + crate::runtime::replay::block(ctx); let reopened = reopened(ctx, id, exiting); with_pass(ctx, |pass| pass.drawing.push(id)); let viewport = pass::current_viewport(ctx); @@ -533,6 +534,7 @@ pub(crate) fn note_peers(ctx: &Context, id: Id, peers: Vec) { /// from inside it, so it goes in front of them, and every layer then stacks above the layer it was opened from. A /// layer shown again in a discarded pass replaces its entry. pub(crate) fn record(ctx: &Context, entry: OpenEntry) { + crate::runtime::replay::block(ctx); with_pass(ctx, |pass| { if let Some(at) = pass.current.iter().position(|recorded| recorded.id == entry.id) { pass.current[at] = entry; diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 8105c789d..e30f85b02 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -99,6 +99,7 @@ pass_state! { drag_board: crate::runtime::drag::Board, commands: crate::runtime::commands::board::Board, inspect: crate::runtime::inspect::Log, + recorder: crate::runtime::replay::Recorder, #[cfg(feature = "testing")] noted: crate::runtime::egui::widgets::noted::Noted, #[cfg(feature = "testing")] diff --git a/crates/ui-contract/src/runtime/pointer.rs b/crates/ui-contract/src/runtime/pointer.rs index 3643d392d..5dceaf10d 100644 --- a/crates/ui-contract/src/runtime/pointer.rs +++ b/crates/ui-contract/src/runtime/pointer.rs @@ -259,6 +259,11 @@ pub(crate) fn record_shapes(ctx: &Context, layer: Layer, root: Id, shapes: impl /// `record_shapes` for a caller that already read the running viewport. pub(crate) fn record_shapes_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, shapes: impl IntoIterator>) { + let shapes: Vec> = shapes.into_iter().collect(); + crate::runtime::replay::journal(ctx, || { + let shapes = shapes.clone(); + move |ctx: &Context| record_shapes(ctx, layer, root, shapes.iter().cloned()) + }); PerViewport::::with(ctx, viewport, |record| record.this.entry(layer).or_default().entry(root).or_default().shapes.extend(shapes)); } @@ -270,6 +275,10 @@ pub(crate) fn record_widgets(ctx: &Context, layer: Layer, root: Id, widgets: &[I /// `record_widgets` for a caller that already read the running viewport. pub(crate) fn record_widgets_in(ctx: &Context, viewport: ViewportId, layer: Layer, root: Id, widgets: &[Id], click: bool) { + crate::runtime::replay::journal(ctx, || { + let widgets = widgets.to_vec(); + move |ctx: &Context| record_widgets(ctx, layer, root, &widgets, click) + }); PerViewport::::with(ctx, viewport, |record| { let entry = record.this.entry(layer).or_default().entry(root).or_default(); entry.widgets.extend_from_slice(widgets); diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index 221f822e7..565d758d7 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -32,7 +32,7 @@ pub(crate) struct Sample { pub took: Vec2, } -#[derive(Debug)] +#[derive(Clone, Debug)] struct Read { key: BindKey, reader: Id, @@ -87,7 +87,13 @@ pub(crate) fn note(ctx: &Context, key: BindKey, reader: Id, measuring: bool, sam if measuring && crate::runtime::measure::active(ctx) { layout_memory::contribute(ctx, Arc::new(MeasuredRead { key, reader, runs, samples })); } else { - with(ctx, |reads| reads.reads.push(Read { key, reader, measuring, runs, samples })); + let read = Read { key, reader, measuring, runs, samples }; + crate::runtime::replay::note_read(ctx, key); + crate::runtime::replay::journal(ctx, || { + let read = read.clone(); + move |ctx: &Context| with(ctx, |reads| reads.reads.push(read.clone())) + }); + with(ctx, |reads| reads.reads.push(read)); } } diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs new file mode 100644 index 000000000..a0bba7cec --- /dev/null +++ b/crates/ui-contract/src/runtime/replay.rs @@ -0,0 +1,178 @@ +//! Run records: what a real run of a settling region (`Lazy::settles`) added to its pass, so a later pass adds it again +//! in place of running the region. A record holds the region's paint, egui widget rects and AccessKit nodes (egui's +//! pass records), what it registered with the focus service (`focus::Transcript`), and a journal of every other +//! registration the services below take per pass: each service that keeps one notes it here while a record is open, +//! as the call that makes it again. Records nest: a region's record holds the records its settled regions replayed. +//! +//! The record also holds the facts the settled test reads (`runtime::lazy`): the bound values the run read, whether +//! something in it still moves (an animation that is not at its end, a repaint request) and the earliest time it asked +//! to be shown again, and whether it did something a replay cannot repeat (an overlay it shows, paint on another +//! layer, a label scope open around it). Such a record is never replayed: the region runs. + +use crate::runtime::focus::{self, Transcript}; +use crate::runtime::frame; +use crate::runtime::pass_state; +use crate::runtime::reads::BindKey; +use egui::{Context, Id, LayerId}; +use std::collections::HashSet; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +/// A registration of the recorded run, made again by calling it. +type Entry = Arc; + +/// Records open across all contexts, so a registration made while none is open takes no lock. +static OPEN: AtomicUsize = AtomicUsize::new(0); + +/// The journal of the running pass while a record is open, and the records open around the running code. +#[derive(Default)] +pub(crate) struct Recorder { + journal: Vec, + open: Vec, +} + +struct Open { + from: usize, + focus: focus::Mark, + egui: egui::PassMark, + facts: Facts, +} + +impl Open { + /// A record that starts at what the pass holds now. + fn empty(ctx: &Context) -> Open { + Open { + from: 0, + focus: focus::mark(ctx), + egui: ctx.pass_mark(), + facts: Facts { blocked: crate::runtime::access::scope::depth(ctx) > 0, ..Facts::default() }, + } + } +} + +/// What the settled test reads from a record. +#[derive(Clone, Default)] +pub(crate) struct Facts { + /// The bound values the run read. + pub(crate) reads: HashSet, + /// Something in the run still moves: it runs again next pass. + pub(crate) unsettled: bool, + /// The earliest pass-clock time the run asked to be shown again. + pub(crate) wake: Option, + /// The run did something a replay cannot repeat. + pub(crate) blocked: bool, +} + +/// What one real run of a region added to its pass. +pub(crate) struct Record { + pub(crate) focus: Transcript, + journal: Vec, + egui: egui::PassRecords, + /// The egui widgets of the run. + pub(crate) widgets: HashSet, + pub(crate) facts: Facts, +} + +fn recording(ctx: &Context) -> bool { + OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| !recorder.open.is_empty()) +} + +/// Opens a record around the real run of a region, which `close` ends. A run inside an open label scope cannot be +/// replayed: the scope's patches reach nodes the record would not hold. +pub(crate) fn open(ctx: &Context) { + let open = Open::empty(ctx); + pass_state::with::(ctx, |recorder| recorder.open.push(Open { from: recorder.journal.len(), ..open })); + OPEN.fetch_add(1, Ordering::AcqRel); +} + +/// Ends the innermost record, the one around a run on `layer`: paint or widgets on another layer block it. +pub(crate) fn close(ctx: &Context, layer: LayerId) -> Record { + OPEN.fetch_sub(1, Ordering::AcqRel); + let (open, journal) = pass_state::with::(ctx, |recorder| { + // A close with no open record ends one that holds nothing and is never replayed. + let open = recorder.open.pop().unwrap_or_else(|| { + let mut open = Open::empty(ctx); + open.from = recorder.journal.len(); + open.facts.blocked = true; + open + }); + let journal = recorder.journal.get(open.from..).unwrap_or_default().to_vec(); + if let Some(outer) = recorder.open.last_mut() { + outer.facts.unsettled |= open.facts.unsettled; + outer.facts.blocked |= open.facts.blocked; + outer.facts.wake = min_wake(outer.facts.wake, open.facts.wake); + outer.facts.reads.extend(open.facts.reads.iter().copied()); + } else { + recorder.journal.clear(); + } + (open, journal) + }); + let egui = ctx.pass_records_since(&open.egui); + let mut facts = open.facts; + facts.blocked |= egui.layers().any(|on| on != layer); + Record { focus: focus::transcript(ctx, open.focus), journal, widgets: egui.widgets().iter().map(|widget| widget.id).collect(), egui, facts } +} + +fn min_wake(a: Option, b: Option) -> Option { + match (a, b) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } +} + +/// Adds `record` to the running pass in place of the run that made it. +pub(crate) fn replay(ctx: &Context, record: &Record) { + ctx.replay_pass_records(&record.egui); + focus::replay(ctx, &record.focus); + for entry in &record.journal { + entry(ctx); + } + if let Some(at) = record.facts.wake { + crate::runtime::egui::repaint::request_after(ctx, crate::runtime::egui::pass::current_viewport(ctx), at - frame::clock(ctx)); + } + with_open(ctx, |facts| { + facts.reads.extend(record.facts.reads.iter().copied()); + facts.wake = min_wake(facts.wake, record.facts.wake); + }); +} + +fn with_open(ctx: &Context, f: impl FnOnce(&mut Facts)) { + if OPEN.load(Ordering::Acquire) > 0 { + pass_state::with::(ctx, |recorder| { + if let Some(open) = recorder.open.last_mut() { + f(&mut open.facts); + } + }); + } +} + +/// Notes, in the records open around the running code, the registration `make` builds: called again, it registers +/// what the running code registered. +pub(crate) fn journal(ctx: &Context, make: impl FnOnce() -> F) { + if recording(ctx) { + let entry: Entry = Arc::new(make()); + pass_state::with::(ctx, |recorder| recorder.journal.push(entry)); + } +} + +/// Notes that the running code read the bound value `key`. +pub(crate) fn note_read(ctx: &Context, key: BindKey) { + with_open(ctx, |facts| { + facts.reads.insert(key); + }); +} + +/// Notes that something in the running code still moves. +pub(crate) fn note_unsettled(ctx: &Context) { + with_open(ctx, |facts| facts.unsettled = true); +} + +/// Notes that the running code asks to be shown again at `at` on the pass clock. +pub(crate) fn note_wake(ctx: &Context, at: f64) { + with_open(ctx, |facts| facts.wake = min_wake(facts.wake, Some(at))); +} + +/// Notes that the running code did something a replay cannot repeat. +pub(crate) fn block(ctx: &Context) { + with_open(ctx, |facts| facts.blocked = true); +} diff --git a/crates/ui-contract/src/runtime/wheel.rs b/crates/ui-contract/src/runtime/wheel.rs index 36a847e24..e01dd376c 100644 --- a/crates/ui-contract/src/runtime/wheel.rs +++ b/crates/ui-contract/src/runtime/wheel.rs @@ -22,6 +22,7 @@ pub(crate) struct State { /// Registers a taker for next pass's split. pub(crate) fn register(ctx: &Context, taker: WheelTaker) { + crate::runtime::replay::journal(ctx, || move |ctx: &Context| register(ctx, taker)); PerViewport::::with(ctx, pass::current_viewport(ctx), |state| state.this.push(taker)); } diff --git a/crates/ui-widgets/tests/it/body/mod.rs b/crates/ui-widgets/tests/it/body/mod.rs index 574bb638e..823404bfe 100644 --- a/crates/ui-widgets/tests/it/body/mod.rs +++ b/crates/ui-widgets/tests/it/body/mod.rs @@ -1,3 +1,4 @@ //! The body step and the mount host: regions, scrolling, move and resize, and viewport mounts. mod scroll; +mod settle; diff --git a/crates/ui-widgets/tests/it/body/settle.rs b/crates/ui-widgets/tests/it/body/settle.rs new file mode 100644 index 000000000..579ef7bfe --- /dev/null +++ b/crates/ui-widgets/tests/it/body/settle.rs @@ -0,0 +1,197 @@ +//! Settling children (`Lazy::settles`): a settled child adds its last run to the pass in place of running, and runs +//! when something it shows may have changed: the pointer over it, a bound value it read, its room, an animation. + +use crate::values::kit::{AT, INITIAL, Scrub, Seen}; +use craft_ui::buttons::Button; +use craft_ui::contract::{Bind, Lazy, Props as _, Show as _, ShowContainer as _}; +use craft_ui::display::Spinner; +use craft_ui::layout_components::Stack; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::{Frames, last_pass_measuring_runs, trial}; +use egui::{Id, Pos2, Rect, Ui, Vec2}; +use std::cell::{Cell, RefCell}; + +const ORIGIN: Pos2 = Pos2::new(10.0, 60.0); +const ROOM: Vec2 = Vec2::new(300.0, 200.0); +/// Where the bound scrub of the reader child is shown, inside that child's room. +const READER: Rect = Rect { min: Pos2::new(150.0, 70.0), max: Pos2::new(250.0, 90.0) }; +/// Settled frames a trial looks at. +const SETTLED: usize = 4; + +/// Two settling children, `reader` and `other`, under a scrub bound to the value the reader's own scrub shows. The +/// scrub that edits comes before the children in the pass when `editor_first`, else after them. +struct Scene { + value: RefCell, + room: Cell, + editor_first: bool, + spinner: bool, + runs: [Cell; 2], + buttons: [Cell<(Id, Rect)>; 2], + seen: Seen, +} + +impl Scene { + fn new(editor_first: bool, spinner: bool) -> Scene { + Scene { + value: RefCell::new(INITIAL), + room: Cell::new(ROOM), + editor_first, + spinner, + runs: Default::default(), + buttons: [Cell::new((Id::NULL, Rect::NOTHING)), Cell::new((Id::NULL, Rect::NOTHING))], + seen: Seen::default(), + } + } + + fn show(&self, ui: &mut Ui) { + if self.editor_first { + self.editor(ui); + } + in_region(ui, Rect::from_min_size(ORIGIN, self.room.get()), |ui| { + Lazy::new("reader", 0.0).settles(true).show(ui, |ui| { + self.runs[0].set(self.runs[0].get() + 1); + let response = Button::new("Alpha").show(ui).response; + self.buttons[0].set((response.id, response.rect)); + Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("reader").seen(&self.seen).show_at(ui, READER); + }); + Lazy::new("other", 0.0).settles(true).show(ui, |ui| { + self.runs[1].set(self.runs[1].get() + 1); + // In a body, whose measure a run that is not settled takes from what its last run kept. + Stack::new().show(ui, |ui, _| { + let response = Button::new("Beta").show(ui).response; + self.buttons[1].set((response.id, response.rect)); + }); + if self.spinner { + Spinner::new().show(ui); + } + }); + }); + if !self.editor_first { + self.editor(ui); + } + } + + fn editor(&self, ui: &mut Ui) { + Scrub::new(Bind::bound(&mut *self.value.borrow_mut())).id_salt("editor").show_at(ui, AT); + } + + /// The runs of each child in one frame with `events`. + fn frame(&self, frames: &mut Frames, events: Vec) -> [usize; 2] { + self.runs.iter().for_each(|runs| runs.set(0)); + frames.frame(events, |ui| self.show(ui)); + [self.runs[0].get(), self.runs[1].get()] + } + + /// Frames with no input until both children are settled. + fn settle(&self, frames: &mut Frames) { + frames.idle(30, |ui| self.show(ui)); + } +} + +fn painted(frames: &Frames, text: &str) -> bool { + frames.texts().iter().any(|run| run.text == text) +} + +/// An untouched settled child runs no component, yet its paint shows in each frame and its accessibility nodes stay +/// in the tree, under the same parents. +#[trial] +fn a_settled_child_does_not_run_and_still_paints() { + let scene = Scene::new(false, false); + let mut frames = Frames::new(); + frames.frame(vec![], |ui| scene.show(ui)); + let ids = scene.buttons.each_ref().map(|button| button.get().0); + let tree = frames.tree(); + let parents = ids.map(|id| tree.parent_of(id)); + assert!(parents.iter().all(Option::is_some), "the buttons have nodes in a frame that runs them"); + scene.settle(&mut frames); + for frame in 0..SETTLED { + assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "settled frame {frame} ran a child"); + assert!(painted(&frames, "Alpha") && painted(&frames, "Beta"), "settled frame {frame} paints both children"); + let tree = frames.tree(); + assert_eq!( + ids.map(|id| tree.name(id).map(str::to_owned)), + [Some("Alpha".to_owned()), Some("Beta".to_owned())], + "settled frame {frame} keeps the nodes" + ); + assert_eq!(ids.map(|id| tree.parent_of(id)), parents, "settled frame {frame} keeps the nodes' parents"); + } +} + +/// The pointer over a settled child runs it, and only it, in the frame it arrives, from the measures its last run +/// kept; leaving, the child runs until its hover has faded out, then settles again. +#[trial] +fn hovering_a_settled_child_runs_it_alone() { + let scene = Scene::new(false, false); + let mut frames = Frames::new(); + scene.settle(&mut frames); + let over = scene.buttons[1].get().1.center(); + let [reader, other] = scene.frame(&mut frames, vec![moved(over)]); + assert!(other > 0, "the hovered child runs in the frame the pointer arrives"); + let measured = last_pass_measuring_runs(&frames.ctx); + assert!(measured.is_empty(), "the hovered child's body takes its kept measure: {measured:?}"); + assert_eq!(reader, 0, "the child beside it stays settled"); + let away = Pos2::new(ORIGIN.x + ROOM.x - 2.0, ORIGIN.y + ROOM.y - 2.0); + let [_, other] = scene.frame(&mut frames, vec![moved(away)]); + assert!(other > 0, "the child the pointer left runs to show its hover leaving"); + scene.settle(&mut frames); + assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "once its hover faded, the child settles again"); +} + +/// Drags the editor right in steps; returns per drag frame the passes, the runs of each child, and whether the +/// reader showed the dragged value. +fn drag(scene: &Scene) -> Vec<(usize, [usize; 2], bool)> { + let mut frames = Frames::new(); + scene.settle(&mut frames); + let from = Pos2::new(AT.left() + 10.0, AT.center().y); + scene.frame(&mut frames, vec![moved(from)]); + scene.frame(&mut frames, vec![press(from)]); + let mut seen = Vec::new(); + for step in 1..=4 { + scene.runs.iter().for_each(|runs| runs.set(0)); + let passes = frames.frame(vec![moved(from + Vec2::new(10.0 * step as f32 + 10.0, 0.0))], |ui| scene.show(ui)); + let shows = scene.seen.shown.get() == Some(*scene.value.borrow()); + seen.push((passes, [scene.runs[0].get(), scene.runs[1].get()], shows)); + } + scene.frame(&mut frames, vec![release(from + Vec2::new(50.0, 0.0))]); + seen +} + +/// A drag of a control outside both children, bound to a value one of them reads, runs that child in each drag frame +/// and leaves the other settled, with the editor before the children in the pass and after them. The frame after the +/// press runs both: input unsettles every child for its frame and the next. +#[trial] +fn an_edit_runs_the_settled_child_that_read_the_value() { + for editor_first in [true, false] { + let frames = drag(&Scene::new(editor_first, false)); + for (passes, [reader, other], shows) in &frames[1..] { + assert!(*reader > 0, "the reader runs in each drag frame (editor first: {editor_first}): {frames:?}"); + assert_eq!(*other, 0, "the other child stays settled (editor first: {editor_first}): {frames:?}"); + assert!(*shows, "the reader shows the dragged value (editor first: {editor_first}): {frames:?}"); + let expected = if editor_first { 1 } else { 2 }; + assert_eq!(*passes, expected, "passes per drag frame (editor first: {editor_first}): {frames:?}"); + } + } +} + +/// A settled child whose room changes runs in that frame. +#[trial] +fn a_settled_child_runs_when_its_room_changes() { + let scene = Scene::new(false, false); + let mut frames = Frames::new(); + scene.settle(&mut frames); + scene.room.set(ROOM + Vec2::new(40.0, 0.0)); + assert_eq!(scene.frame(&mut frames, vec![]), [1, 1], "both children run at the new room"); + assert_eq!(scene.frame(&mut frames, vec![]), [0, 0], "and settle at it"); +} + +/// A child with a running animation (a spinner) runs every frame; the child beside it stays settled. +#[trial] +fn a_child_with_a_running_animation_runs_every_frame() { + let scene = Scene::new(false, true); + let mut frames = Frames::new(); + scene.settle(&mut frames); + for frame in 0..SETTLED { + assert_eq!(scene.frame(&mut frames, vec![]), [0, 1], "frame {frame}: the spinner's child runs, the other does not"); + } +} diff --git a/crates/ui-widgets/tests/it/values/mod.rs b/crates/ui-widgets/tests/it/values/mod.rs index e620185c8..f121dc92d 100644 --- a/crates/ui-widgets/tests/it/values/mod.rs +++ b/crates/ui-widgets/tests/it/values/mod.rs @@ -6,7 +6,7 @@ mod gestures; mod history; -mod kit; +pub(crate) mod kit; mod reads;