diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index a89e495b67..28b9138e1e 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -160,13 +160,13 @@ impl Lazy { None }; // The replay audit runs a view that would replay for real in place of the replay, and compares the two. - let audited = settled.as_ref().filter(|_| audits(&ctx, real)).map(|(_, _, shift)| *shift); - if let Some((size, ran_at, shift)) = settled + let audited = settled.as_ref().filter(|_| audits(&ctx, real)).map(|(_, _, _, shift)| *shift); + if let Some((size, fills, ran_at, shift)) = settled && audited.is_none() { // A real replay is where the run's content went, moved with the room. let rect = if real { ran_at } else { Rect::from_min_size(at_start(available, rtl, size), size) }; - let fills = if memo && !real { lazy::fills(&ctx, id, sizing) } else { None }; + let fills = fills.filter(|_| !real); let took = place_unit(ui, &env, (shrink, fills), id, rect, rtl); let kept = if real { layout_memory::backstop(&ctx, id, size); diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 2b5285431a..ae83abce34 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -27,6 +27,7 @@ use crate::runtime::{Clip, Shift}; use crate::style::EnvKey; use egui::emath::GuiRounding as _; use egui::{Context, Id, IdMap, IdSet, Layout, RecordShift, Rect, Vec2}; +use smallvec::SmallVec; use std::any::Any; use std::collections::{HashMap, HashSet}; use std::sync::Arc; @@ -162,6 +163,11 @@ pub(crate) enum Decision { Skip(Vec2), } +/// The most sizing measures a memoized view keeps (`Entry::measures`). A body measures a view in at most two layout +/// contexts in a pass (a capped body or a layer with a footer drafts it at its content height, then lays it out at its +/// room); the others keep a context that returns after a change of key or room. +const MEASURES: usize = 4; + #[derive(Clone, Default)] struct Entry { /// The scroll area the child is kept under. @@ -173,6 +179,14 @@ struct Entry { sizes: [Option; 2], /// The pass of the last measuring run in `sizes`. measuring_pass: u64, + /// What the sizing runs that showed a memoized view measured, one per layout context (the key of the content it + /// showed, the flow of the body around it and the room's size), each with the last pass that measured or took it, + /// the most recently used last, at most `MEASURES`. A sizing run in one of these contexts replays (`settled`). A + /// draft taken back keeps them (`write`): a measure is a fact of its inputs, so a view a body drafts at its content + /// height and then lays out at its room replays in both in the next pass. A real run keeps only the ones of its own + /// pass (`ran`): it may show content its key does not name (a value it read was edited), which a measure of an + /// earlier pass does not hold. + measures: SmallVec<[(Measured, u64); MEASURES]>, /// What the child registered with the focus service in the last real run that showed it. Out of view the /// child registers it again in its place, so Tab and F6 reach its stops; it runs while one of them holds focus /// or a focus request asks to reveal one. @@ -205,6 +219,13 @@ pub(crate) struct Measured { pub(crate) fills: Option, } +impl Measured { + /// Whether the measure is of the content keyed `key`, in `flow` and a room of the size `room`. + fn of(&self, key: Key, flow: Flow, room: Vec2) -> bool { + self.key == key && self.flow == flow && self.room.size() == room + } +} + /// Where a memoized view ran: it replays only at a place of the same size, layer, layout, AccessKit state, opacity, flow /// and environment, and its record moves with the room's position (`Place::shift_to`). #[derive(Clone, Copy, Debug, PartialEq)] @@ -388,6 +409,25 @@ impl Entry { fn memo(&self) -> bool { self.settled.as_ref().is_some_and(|settled| matches!(settled.key, Key::Memo(_))) } + + /// Keeps the sizing measure `measured` of the pass `pass` as the most recently used, in place of the one of its + /// layout context; the least recently used goes when `MEASURES` are kept. + fn keep_measure(&mut self, measured: Measured, pass: u64) { + self.measures.retain(|(kept, _)| !kept.of(measured.key, measured.flow, measured.room.size())); + if self.measures.len() == MEASURES { + self.measures.remove(0); + } + self.measures.push((measured, pass)); + } + + /// The sizing measure of the content keyed `key` in `flow` and a room of the size `room`, taken in the pass `pass`: + /// it becomes the most recently used. + fn measure_in(&mut self, key: Key, flow: Flow, room: Vec2, pass: u64) -> Option { + let at = self.measures.iter().position(|(kept, _)| kept.of(key, flow, room))?; + let (measured, _) = self.measures.remove(at); + self.measures.push((measured, pass)); + Some(measured) + } } impl Store { @@ -443,7 +483,8 @@ fn with(ctx: &Context, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { /// Runs `f` on the store as `with` does, for a write to the entry of the child `id`: inside a draft /// (`layout_memory::draft`) the entry as it was goes to the draft, so a measuring run taken back leaves the entry, its -/// extents and this pass's decisions included, as it found it. +/// extents and this pass's decisions included, as it found it. It keeps the sizing measures the draft found +/// (`Entry::measures`): they are facts of their inputs, not state of the pass. fn write(ctx: &Context, id: Id, f: impl FnOnce(&mut Store, u64, u64) -> R) -> R { let drafting = layout_memory::drafting(ctx); let (out, before) = with(ctx, |store, pass_nr, frame| { @@ -455,9 +496,19 @@ fn write(ctx: &Context, id: Id, f: impl FnOnce(&mut Store, u64, u64) -> R) -> layout_memory::note_undo( ctx, Box::new(move |ctx: &Context| { - PerViewport::::with(ctx, viewport, |store| match before { - Some(entry) => drop(store.entries.insert(id, entry)), - None => drop(store.entries.remove(&id)), + PerViewport::::with(ctx, viewport, |store| { + let now = store.entries.remove(&id); + let restored = match (before, now) { + (Some(entry), None) => Some(entry), + (Some(entry), Some(now)) => Some(Entry { measures: now.measures, ..entry }), + (None, Some(now)) if !now.measures.is_empty() => { + Some(Entry { owner: now.owner, touched: now.touched, measures: now.measures, ..Entry::default() }) + } + (None, _) => None, + }; + if let Some(entry) = restored { + store.entries.insert(id, entry); + } }); }), ); @@ -500,6 +551,9 @@ pub(crate) fn shown(ctx: &Context, owner: Option, id: Id, sizing: bool, meas entry.sizes[usize::from(!sizing)] = Some(measured); if sizing { entry.measuring_pass = pass_nr; + if matches!(measured.key, Key::Memo(_)) { + entry.keep_measure(measured, pass_nr); + } } if let Some(registered) = registered { entry.focus = Arc::new(registered); @@ -534,14 +588,14 @@ pub(crate) fn replay(ctx: &Context, id: Id) { } /// Whether the memoized view `id` adds its last real run to this pass in place of running, the extent that run took in -/// a run of this kind (`call`), the rect the kept real run takes now and the shift its record moves by. The first real -/// run of a pass decides from what changed since that run and from its key, and every later real run of the pass takes -/// its answer; a real run also needs a place the run can move to (`Place::shift_to`), which a measuring run cannot -/// tell. A measuring run asks the same each time, with its own key, and decides nothing for the pass: a call that shows -/// other content runs and leaves the decision to the calls after it. A sizing run takes the extent the last sizing run -/// measured of the content the kept run showed (its key) in the room it offers now and in the same flow; when that -/// sizing run showed other content or had another room or flow, or there was none, it runs once as a measuring run, -/// which keeps no record, so the real run still replays. +/// a run of this kind (`call`) with the axis its content filled there (`Measured::fills`), the rect the kept real run +/// takes now and the shift its record moves by. The first real run of a pass decides from what changed since that run +/// and from its key, and every later real run of the pass takes its answer; a real run also needs a place the run can +/// move to (`Place::shift_to`), which a measuring run cannot tell. A measuring run asks the same each time, with its own key, and decides nothing for the pass: a call that shows +/// other content runs and leaves the decision to the calls after it. A sizing run takes the extent a sizing run +/// measured of the content the kept run showed (its key) in a room of the size it offers now and in the same flow +/// (`Entry::measures`); when none did, it runs once as a measuring run, which keeps no record, so the real run still +/// replays. /// /// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then: /// - nothing in it moves: no animation off its end value, no repaint asked from inside it, no texture it shows still @@ -580,7 +634,7 @@ pub(crate) fn settled( view: Option, key: Key, moving: &[Id], -) -> Option<(Vec2, Rect, RecordShift)> { +) -> Option<(Vec2, Option, Rect, RecordShift)> { let (place, sizing, flow) = match call { Call::Real(place) => (Some(place), None, place.flow), Call::Measuring { room, flow } => (None, room, flow), @@ -633,24 +687,26 @@ pub(crate) fn settled( } settled.and_then(|(moved, settled)| { // An extent depends on the room's size, not on where the room is. - let size = match sizing { + let (size, fills) = match sizing { Some(room) => { - entry.sizes[0] - .filter(|measured| measured.key == settled.key && measured.flow == flow && measured.room.size() == room.size())? - .size + let measured = entry.measure_in(settled.key, flow, room.size(), pass_nr)?; + (measured.size, measured.fills) + } + None => { + let fills = entry.sizes[1].or(entry.sizes[0]).and_then(|measured| measured.fills); + match entry.sizes[1].filter(|measured| measured.key == settled.key && measured.flow == flow) { + Some(measured) => (measured.size, fills), + // A real run's place has the kept run's flow (`Place::shift_to`); a measuring run checks it here. + None => ((settled.place.flow == flow).then(|| settled.rect.size())?, fills), + } } - None => match entry.sizes[1].filter(|measured| measured.key == settled.key && measured.flow == flow) { - Some(measured) => measured.size, - // A real run's place has the kept run's flow (`Place::shift_to`); a measuring run checks it here. - None => (settled.place.flow == flow).then(|| settled.rect.size())?, - }, }; - Some((size, moved, settled)) + Some((size, fills, moved, settled)) }) }); // 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, Moved { shift, with_clip }, settled) = settled?; + let (size, fills, Moved { shift, with_clip }, settled) = settled?; let rect = shift.rect(settled.rect); // The scroll view a nested child decided by: the run's, moved with the record, while the clip moved with it; a run // that lay wholly in its clip ran every nested child, which holds at any view. @@ -670,7 +726,7 @@ pub(crate) fn settled( } return None; } - Some((size, rect, shift)) + Some((size, fills, rect, shift)) } /// Whether something a memoized view's run read outside its props moved since: a framework input it read has another @@ -783,6 +839,7 @@ pub(crate) struct Ran { /// Keeps the real run `record` of the memoized view `id`, which ran at `place` and took `rect`. A run in a pass egui /// will discard keeps none: egui paints nothing of that pass (`Painter::is_visible` is false in it), so the run registers /// invisible widgets and no nodes, which a shown pass's replay must not add. The kept record stays the last shown pass's. +/// The view keeps the sizing measures of this pass only (`Entry::measures`). pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rect, Ran { key, edits, seen, view, output }: Ran) { if ctx.will_discard() { return; @@ -800,6 +857,7 @@ pub(crate) fn ran(ctx: &Context, id: Id, record: Record, place: Place, rect: Rec settled.pass = pass_nr; if let Some(entry) = store.entries.get_mut(&id) { entry.settled = Some(Arc::new(settled)); + entry.measures.retain(|(_, seen)| *seen == pass_nr); } }); } diff --git a/crates/ui-contract/tests/it/runtime/layout_memory.rs b/crates/ui-contract/tests/it/runtime/layout_memory.rs index 7c656d6347..47fb7f40d9 100644 --- a/crates/ui-contract/tests/it/runtime/layout_memory.rs +++ b/crates/ui-contract/tests/it/runtime/layout_memory.rs @@ -1,10 +1,12 @@ //! Layout memory's handoffs: what a run hands forward reaches code that reads it later in the pass. -use craft_ui::contract::MemoView; +use craft_ui::contract::{MemoView, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::runtime::layout_memory; +use craft_ui::testing::layout::Block; use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; -use egui::Id; -use std::cell::RefCell; +use craft_ui_test_kit::contract::Panel; +use egui::{Id, Vec2}; +use std::cell::{Cell, RefCell}; use std::rc::Rc; /// Where the view in these trials hands forward the width it measured. @@ -38,3 +40,40 @@ fn a_replayed_view_hands_forward_the_width_its_run_measured() { assert!(read.borrow().iter().all(|width| *width == ran), "a replay hands forward the width the run measured: {:?}", read.borrow()); } } + +/// A capped body drafts its content at its content height and, taller than its room, takes the draft back and lays the +/// content out at its room, so a memoized view in it is measured in two contexts in one pass. The view around the body +/// takes a new key each frame, so the body measures afresh under its new content version; the inner view's own inputs +/// stay the same, so it replays in the draft, in the measure at the room and in the real run. Views are counted by their +/// props type: `u32` around the body, `u64` inside it. +#[trial] +fn a_view_in_a_drafted_body_replays_in_both_measures_while_the_view_around_it_changes() { + let step = Rc::new(Cell::new(0_u32)); + let shown = Rc::clone(&step); + let mut fixture = Fixture::new(move |ui| { + let _ = MemoView::new("around", shown.get(), |_: &mut u32, ui: &mut egui::Ui| { + Panel::new().id_salt("layer").show(ui, |ui, _| { + Panel::new().sizing(Sizing::Fill).id_salt("capped").show(ui, |ui, _| { + Block::new(Vec2::new(100.0, 20.0)).show(ui); + let _ = MemoView::new("list", 1_u64, |_: &mut u64, ui: &mut egui::Ui| { + Block::new(Vec2::new(100.0, 600.0)).show(ui); + }) + .show(ui); + }); + }); + }) + .show(ui); + }); + fixture.room(Vec2::new(300.0, 200.0)); + fixture.settle(); + for at in 1..5 { + step.set(at); + fixture.frame(Vec::new()); + let runs = last_frame_memo_runs(fixture.ctx()); + let of = |name: &str| runs.iter().filter(|(view, _, _)| *view == name).map(|(_, _, run)| *run).collect::>(); + let list = of("u64"); + assert!(of("u32").contains(&MemoRun::Ran), "step {at}: the new key runs the view around the body: {runs:?}"); + assert!(list.len() >= 3, "step {at}: the body measures the inner view as a draft and at its room, then shows it: {runs:?}"); + assert!(list.iter().all(|run| *run == MemoRun::Replayed), "step {at}: the inner view's inputs are unchanged, so no call runs it: {runs:?}"); + } +}