From f8888f8beba582edce24c9b859b988e1775474ce Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 03:56:13 +0000 Subject: [PATCH 1/4] Memoized views: the flow of the body around a view is a fact of its place, not of its key A container's measuring run lays its header and end regions out as a content column, and its real run does not; a shrinking row's counting sweep shows its units unbounded, and its least probe at their least. With those flow facts in the scope key, such a sizing call keyed apart from the kept real run, ran as a measure and could decide "run" for the whole pass, so the real call ran too. The flow facts (content column, given column, content axes, least measure, unbounded axes, cell fills, and whether the leaves fit the view's room) move into a Flow that Place (real calls) and Measured (sizing and measuring calls) hold, and each kind of call compares its own. Only a real call reads or writes the pass decision; a measuring call checks the key and the rest of the predicate itself each time and decides nothing for the pass. This replaces the per-call key exception and Place.fits. Env::local_mut clears the cached scope key, so a sweep that edits its scope keys again. --- crates/ui-contract/src/contract/lazy.rs | 16 +-- crates/ui-contract/src/contract/memo_view.rs | 7 +- crates/ui-contract/src/runtime/env.rs | 47 ++++++-- crates/ui-contract/src/runtime/lazy.rs | 118 +++++++++++-------- crates/ui-widgets/tests/it/body/memo_view.rs | 72 ++++++++++- 5 files changed, 188 insertions(+), 72 deletions(-) diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index e706ae1fc..74d9fc609 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -6,7 +6,7 @@ use crate::runtime::egui::alloc; use crate::runtime::env::{Env, Shrink}; use crate::runtime::focus; use crate::runtime::layout_memory; -use crate::runtime::lazy::{self, Decision, Key, Place}; +use crate::runtime::lazy::{self, Call, Decision, Key, Place}; #[cfg(feature = "testing")] use crate::runtime::measure::{MemoRun, count_memo_run}; use crate::runtime::memory::sub; @@ -71,7 +71,8 @@ impl Lazy { /// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view. pub(super) fn run_keyed(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown { let ctx = ui.ctx().clone(); - let view = Env::of(ui).view().lazy_view(); + let env = Env::of(ui); + let view = env.view().lazy_view(); let id = match view { Some(view) => sub(view.owner, ("lazy", self.key)), None => sub(ui.scope_id(), ("lazy", self.key)), @@ -82,7 +83,7 @@ impl Lazy { // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a // new content runs it once and the discard pass its new size asks for replays that run. - let shrink = Env::of(ui).shrink.filter(|_| memo); + let shrink = env.shrink.filter(|_| memo); let cap = match shrink { Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed), _ => None, @@ -125,13 +126,14 @@ impl Lazy { pixels_per_point: ctx.pixels_per_point(), atlas: ctx.fonts(|fonts| fonts.atlas_generation()), opacity: ui.opacity(), - env: Env::of(ui).key, - fits: Env::of(ui).view_fits(), + env: env.key, + flow: env.flow(), }; if real && memo { crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass"); } - let settled = if memo { lazy::settled(&ctx, owner, id, sizing.then_some(available), real.then_some(place), view, key) } else { None }; + let call = if real { Call::Real(place) } else { Call::Measuring { room: sizing.then_some(available), flow: place.flow } }; + let settled = if memo { lazy::settled(&ctx, owner, id, call, view, key) } else { 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 @@ -195,7 +197,7 @@ impl Lazy { } if view.is_some() || memo { let registered = real.then(|| record.as_ref().map_or_else(|| focus::transcript(&ctx, mark), |record| record.focus.clone())); - lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available }, registered); + lazy::shown(&ctx, owner, id, sizing, lazy::Measured { size: rect.size(), key, room: available, flow: place.flow }, registered); } if let Some(view) = view && real diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index a34352284..57088ece2 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -46,8 +46,11 @@ use std::sync::Arc; /// 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; +/// - its place: the room it is given, the clip, the layer, the layout, the scale, the scope's style inputs (tokens, +/// theme, density, direction, language, window active) and the flow of the body around it (whether that body is a +/// content-sized or a given column, the axes it sizes from its content, a least measure, the axes a scroll leaves +/// unbounded, a beside label's cell, whether its leaves fit the room), compared for every view and for each kind of +/// run on its own; /// - 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 diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 35fc87158..1e39dc9d6 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -75,6 +75,23 @@ pub(crate) struct FooterSlotOf { pub size: egui::Vec2, } +/// The flow facts of the body around a memoized view that its content is laid out by: whether that body is a +/// content-sized or a given column, the axes it sizes from its content, whether the view runs in a least measure, the +/// axes a scrolling body leaves unbounded, whether it fills a beside label's cell and whether its leaves fit the view's +/// room (`Scoped::view_fits`). A measuring run of a container or a row lays the view out under other facts than its +/// real run, so they are a fact of the view's place, which each kind of run compares on its own (`lazy::Place`, +/// `lazy::Measured`), not of its key. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) struct Flow { + content_column: bool, + given_column: bool, + content: (bool, bool), + least: bool, + unbounded: (bool, bool), + cell_fills: bool, + fits: bool, +} + /// The values of an env. #[derive(Clone)] #[non_exhaustive] @@ -391,7 +408,7 @@ impl Scoped { /// Ends the layout room of the enclosing body: its flow grid and content column. The axes the body sizes from its /// content stay (`content`): like `cell_fills` and `least`, they say what a child that fills takes there, its - /// measured size or the room, and the scope key holds them. + /// measured size or the room, and the place of a memoized view holds them (`flow`). pub(crate) fn start_room(&mut self) { self.grid = None; self.grid_top = false; @@ -437,20 +454,17 @@ impl Scoped { matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_) | Shrink::Fit)) } - /// 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. Of - /// the flow fields of the enclosing body only how it sizes from its content is in it: a memoized view's content - /// starts a layout room of its own (`start_view_room`) that keeps those facts. Computed once per scope, on the - /// first view that asks; the bytes it fed are counted then. + /// The key of everything a memoized view shown in this scope inherits beyond `key` and `flow` (the style inputs and + /// the flow facts, 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), the command chain, motion, the host's formats and date, and every + /// app value. 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, self.content)); - key.feed_hash(&(self.content_column, self.given_column)); + key.feed_hash(&(self.direction, self.text_direction, self.ids_stable)); 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); @@ -473,6 +487,19 @@ impl Scoped { }) } + /// The flow facts of the enclosing body a memoized view shown in this scope is laid out by (`Flow`). + pub(crate) const fn flow(&self) -> Flow { + Flow { + content_column: self.content_column, + given_column: self.given_column, + content: self.content, + least: self.least, + unbounded: self.unbounded, + cell_fills: self.cell_fills, + fits: self.view_fits(), + } + } + /// 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) diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index d27a97934..ff413d62e 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -16,6 +16,7 @@ use crate::runtime::egui::areas::Layer; use crate::runtime::egui::{input as input_state, pass}; +use crate::runtime::env::Flow; use crate::runtime::focus::{self, Transcript}; use crate::runtime::frame::{self, PerViewport}; use crate::runtime::inputs::{self, Input}; @@ -149,7 +150,8 @@ struct Entry { settled: Option>, /// The last measuring run of a measure-only child (`measured`). measured: Option, - /// Whether this pass replays the memoized view's last run, under the pass number that decided it. + /// Whether this pass replays the memoized view's last run, as the first real run of the pass decided, under the pass + /// number. replays: Option<(u64, bool)>, /// The pass a collection row's extent was last measured in (`remember`). measured_in: Option, @@ -157,17 +159,19 @@ struct Entry { touched: u64, } -/// What a run that showed a child measured: the extent it took, the key of the content it showed and the room it was -/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports). +/// What a run that showed a child measured: the extent it took, the key of the content it showed, the room it was +/// offered (`Rect::NOTHING` for a collection row, whose extent its collection reports) and the flow of the body around +/// it (the default for a collection row). #[derive(Clone, Copy, Debug)] pub(crate) struct Measured { pub(crate) size: Vec2, pub(crate) key: Key, pub(crate) room: Rect, + pub(crate) flow: Flow, } -/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, fit and -/// environment, and its record moves with the room's position (`Place::shift_to`). +/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, opacity, flow and environment, +/// and its record moves with the room's position (`Place::shift_to`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Place { /// The region its parent offered it. @@ -185,9 +189,16 @@ pub(crate) struct Place { /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, - /// Whether the leaves of the view's content fit the view's room, as in a `Stack` or a shrinking `Row` - /// (`Scoped::view_fits`). - pub(crate) fits: bool, + /// The flow of the body around the view (`Scoped::flow`). + pub(crate) flow: Flow, +} + +/// How a memoized view is shown: in a real run at its place, or in a measuring run laid out by the flow of the body +/// around it, offered `room` in a sizing pass (`None` outside one). +#[derive(Clone, Copy, Debug)] +pub(crate) enum Call { + Real(Place), + Measuring { room: Option, flow: Flow }, } /// How a kept run replays at another place: the shift its record moves by, and whether the clip moved with the room. @@ -198,13 +209,13 @@ struct Moved { } impl Place { - /// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; its - /// size, the layer, layout, scale, font atlas, opacity, fit and environment are the ones the run had. A record that - /// shows an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by the - /// room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run there gives) and, - /// for a move, the record holds nothing a move cannot place (`Record::movable`: no paint callback) on an - /// untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its clip rects follow - /// the clip when either: + /// How a run at this place that took `rect` replays at `now`, or `None` when it cannot. The room may have moved; + /// its size, the layer, layout, scale, font atlas, opacity, flow and environment are the ones the run had. A record + /// that shows an overlay replays only at the room and clip of its run (`Record::pinned`). Any other record moves by + /// the room's move when that keeps where a run places content (`keeps_placement`, so a moved record is what a run + /// there gives) and, for a move, the record holds nothing a move cannot place (`Record::movable`: no paint + /// callback) on an untransformed layer (`transformed`: egui's AccessKit bounds are layer space only there). Its + /// clip rects follow the clip when either: /// - the clip moved with the room (`with_clip`): every rect and clip moves exactly, whatever the clip cut; /// - the run lay wholly inside its clip: nothing of it was culled (widgets skip paint outside the clip, and every /// nested `Lazy` child in the scroll view around it ran), and every clip set inside it lies within the run's clip, @@ -220,7 +231,7 @@ impl Place { && now.atlas == self.atlas && now.opacity == self.opacity && now.env == self.env - && now.fits == self.fits; + && now.flow == self.flow; let placeable = if record.pinned() { offset == Vec2::ZERO && now.clip == self.clip } else { @@ -462,15 +473,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 (`sizing`: the room a sizing run offers it, `None` outside a sizing pass), the rect the kept real -/// run takes now and the shift its record moves by. The first run of a pass decides from what changed since that run; a -/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. Each call -/// also needs the key of the kept run: any other call with another key (a row's counting sweep shows the content -/// unbounded, and the scope key holds that) runs, and leaves the decision of the pass alone for the calls after it. A -/// sizing run of a pass that replays takes the extent the last sizing run measured of the content it shows (its key) in -/// the room it offers now; when that sizing run showed other content or had another room, or there was none, it runs -/// once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still -/// replays. +/// 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. /// /// 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 @@ -484,7 +494,7 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or, /// replaying a run of this frame, after that run started; /// - the call's key is the one of its last run (its props key after that run), and its environment (theme, density, -/// scale, language, window active) the one it ran in; +/// scale, language, window active) and the flow of the body around it (`Flow`) the ones it ran in; /// - the run did nothing a replay cannot repeat (`runtime::replay`) and asked for no discard pass: what it added is /// what the pass was thrown away for; /// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is @@ -492,15 +502,12 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - no framework input its run read outside its props has moved (`runtime::inputs`), the scroll view a nested `Lazy` /// child of it decided by is the same (moved with it, `moved`), no command waits for a command scope instance of /// it, and no close waits for a layer it shows. -pub(crate) fn settled( - ctx: &Context, - owner: Option, - id: Id, - sizing: Option, - place: Option, - view: Option, - key: Key, -) -> Option<(Vec2, Rect, RecordShift)> { +pub(crate) fn settled(ctx: &Context, owner: Option, id: Id, call: Call, view: Option, key: Key) -> Option<(Vec2, Rect, RecordShift)> { + let (place, sizing, flow) = match call { + Call::Real(place) => (Some(place), None, place.flow), + Call::Measuring { room, flow } => (None, room, flow), + }; + let real = place.is_some(); let revealed = focus::targets(ctx)[1]; let routed = crate::runtime::keys::routed_to(ctx); let now = frame::clock(ctx); @@ -512,11 +519,7 @@ pub(crate) fn settled( // Usually `None`: only the values written this frame. let edited = changes.edited_in(frame); let entry = store.touch(owner, id, frame); - // The decision of the pass covers the kept run; the key is the call's own. A call that shows other content (a - // row's counting sweep, which shows it unbounded) leaves the decision alone for the calls after it: a sizing call - // takes the extent the last sizing run measured of its own content, and any other runs. - let keyed = entry.settled.as_ref().is_some_and(|settled| settled.key == key) || sizing.is_some(); - let replays = match entry.replays { + let replays = match entry.replays.filter(|_| real) { Some((decided_in, replays)) if decided_in == pass_nr => replays, _ => { let replays = entry.settled.as_ref().is_some_and(|settled| { @@ -524,6 +527,7 @@ pub(crate) fn settled( // A run of this frame read the values edited before it started. let edited = edited_since(edited.as_ref(), if settled.frame < frame { 0 } else { settled.edits }); (settled.frame < frame || settled.pass < pass_nr) + && settled.key == key && !settled.engaged && !facts.blocked && !facts.discards @@ -533,7 +537,9 @@ pub(crate) fn settled( && !dragged.is_some_and(|widget| settled.record.widgets.contains(&widget)) && focused.within(&settled.record.focus, &settled.record.widgets) == settled.record.held }); - entry.replays = Some((pass_nr, replays)); + if real { + entry.replays = Some((pass_nr, replays)); + } replays } }; @@ -542,15 +548,23 @@ pub(crate) fn settled( Some(place) => settled.place.shift_to(settled.rect, place, &settled.record, transformed), None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }), }; - let settled = entry.settled.clone().filter(|_| replays && keyed).and_then(|settled| Some((moved(&settled)?, settled))); - if replays && keyed && settled.is_none() { + let settled = entry.settled.clone().filter(|_| replays).and_then(|settled| Some((moved(&settled)?, settled))); + if real && replays && settled.is_none() { entry.replays = Some((pass_nr, false)); } settled.and_then(|(moved, settled)| { // An extent depends on the room's size, not on where the room is. let size = match sizing { - Some(room) => entry.sizes[0].filter(|measured| measured.key == key && measured.room.size() == room.size())?.size, - None => entry.sizes[1].filter(|measured| measured.key == settled.key).map_or(settled.rect.size(), |measured| measured.size), + Some(room) => { + entry.sizes[0] + .filter(|measured| measured.key == settled.key && measured.flow == flow && measured.room.size() == room.size())? + .size + } + 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)) }) @@ -566,11 +580,13 @@ pub(crate) fn settled( || crate::runtime::memory::ended_since(ctx, &settled.record.facts.owners, settled.lives) || moved(ctx, &settled, view) { - write(ctx, id, |store, pass_nr, _| { - if let Some(entry) = store.entries.get_mut(&id) { - entry.replays = Some((pass_nr, false)); - } - }); + if real { + write(ctx, id, |store, pass_nr, _| { + if let Some(entry) = store.entries.get_mut(&id) { + entry.replays = Some((pass_nr, false)); + } + }); + } return None; } Some((size, rect, shift)) @@ -714,7 +730,7 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) { pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) { write(ctx, id, |store, pass_nr, frame| { let entry = store.touch(Some(owner), id, frame); - entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING }); + entry.sizes[1] = Some(Measured { size, key: Key::None, room: Rect::NOTHING, flow: Flow::default() }); entry.measured_in = Some(pass_nr); }); } diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 657f59440..0e128ff9b 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -5,7 +5,8 @@ use crate::values::kit::Scrub; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; use craft_ui::contract::{ - Bind, CollectionEvent, MemoProps, MemoView, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Tracked, request_rename, + Bind, BodyCx, CollectionEvent, Common, Component, Container, ContainerProps, Cx, HeaderRegion, MemoProps, MemoView, Props as _, Role, Show as _, + ShowCollection as _, ShowContainer as _, Tracked, request_rename, }; use craft_ui::display::{Elide, Text}; use craft_ui::layout_components::{Row, Stack}; @@ -16,6 +17,7 @@ use craft_ui::runtime::focus::Initial; use craft_ui::runtime::memory::{SaveKey, set_saved_value}; use craft_ui::runtime::overlay::{Backdrop, Rank}; use craft_ui::runtime::{frame, inspect}; +use craft_ui::style::StyleCx; use craft_ui::testing::access::{NodeKey, layer_root}; use craft_ui::testing::in_audit_run; use craft_ui::testing::input::key_press; @@ -26,7 +28,8 @@ use craft_ui::testing::{ last_pass_text_layouts, measuring_run, trial, }; use craft_ui::text::TextField; -use egui::{Id, Key, Modifiers, Pos2, Rect, Ui, Vec2}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Id, Key, Modifiers, Pos2, Rect, Response, Ui, Vec2}; use std::cell::Cell; thread_local! { @@ -708,6 +711,71 @@ fn a_changed_view_its_container_measures_first_runs_in_the_sizing_pass_and_the_r assert_eq!(title_runs(), 0, "then the view replays in every run"); } +/// A content-sized container whose header shows the memoized view `title`. +#[derive(Component)] +#[component(container)] +struct Headed { + #[common] + common: Common, + #[container] + props: ContainerProps, +} + +impl Component for Headed { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: HeadedStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +impl Container for Headed { + fn header(&mut self, ui: &mut Ui, _: &mut BodyCx<'_>) { + let _ = MemoView::new("heading", Title { title: "Heading".to_owned() }, title).show(ui); + } +} + +/// One frame of `Headed` with the body text `label`; returns how many sizing passes its body ran in. +fn headed_frame(frames: &mut Frames, label: &str) -> usize { + let sizing = Cell::new(0); + frames.frame(vec![], |ui| { + in_region(ui, STACK_ROOM, |ui| { + let headed = Headed { common: Common::new(), props: ContainerProps::new().header(HeaderRegion::new()) }; + headed.show(ui, |ui, _| { + if ui.is_sizing_pass() { + sizing.set(sizing.get() + 1); + } + Text::new(label.to_owned()).show(ui); + }); + }); + }); + sizing.get() +} + +/// A view in the header of a content-sized container replays when the container measures its regions again: its +/// measuring run lays the header out as a content column and the real run does not, and that is a fact of the place, +/// not of the view's inputs. +#[trial] +fn a_view_in_a_measured_header_replays_in_the_sizing_pass_and_the_real_run() { + let mut frames = Frames::new(); + for _ in 0..SETTLE { + headed_frame(&mut frames, "Short"); + } + title_runs(); + headed_frame(&mut frames, "Short"); + assert_eq!(title_runs(), 0, "settled: an idle frame replays the header's view"); + // A second line, no wider than the first: the container's width, and with it the header's room, stays. + let sizing = headed_frame(&mut frames, "Short\nShort"); + assert!(sizing > 0, "the taller label made the container measure its regions again"); + assert_eq!(title_runs(), 0, "the unchanged view replayed in every call: {:?}", last_frame_memo_runs(&frames.ctx)); +} + /// A paragraph that wraps at its room's width. #[derive(MemoProps)] struct Paragraph { From f300c5954a69606cae4421376f15e769bc5e57ef Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 04:08:59 +0000 Subject: [PATCH 2/4] Memoized views: the header trial asserts every call replayed; a measuring replay's value holds the real run's layout The trial checks the frame's memo log: three replays (the sizing pass and the real run of each of the frame's two passes), the last pass's real run among them. MemoView::show and the runner say that a measuring call that replays returns the kept real run's value, laid out in that run's room and flow, so a caller that measures takes the extent the call reports. --- crates/ui-contract/src/contract/lazy.rs | 2 ++ crates/ui-contract/src/contract/memo_view.rs | 4 +++- crates/ui-widgets/tests/it/body/memo_view.rs | 21 +++++++++++++++----- 3 files changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 74d9fc609..bb622ea9f 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -150,6 +150,8 @@ impl Lazy { } kept } else { + // The kept real run's output, laid out in that run's room and flow: a caller that measures sizes from + // the extent this call takes, never from rects in it. lazy::kept_output(&ctx, id) }; report_unit(&ctx, shrink, id, rect.size()); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index 57088ece2..de103c619 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -110,7 +110,9 @@ impl MemoVie } /// Runs the view in a child `Ui` placed in flow in `ui`, or adds its last run again. Returns what the run returned, - /// the kept value when it replayed; `None` only when it is out of view in a scroll area. + /// the kept value when it replayed; `None` only when it is out of view in a scroll area. A measuring run that + /// replays returns the kept real run's value, laid out in that run's room and flow: code that measures sizes from + /// the extent the view takes in `ui`, never from rects in the value. pub fn show(self, ui: &mut Ui) -> Option { let MemoView { lazy, mut props, show } = self; let ctx = ui.ctx().clone(); diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 0e128ff9b..cceab4213 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -741,10 +741,11 @@ impl Container for Headed { } } -/// One frame of `Headed` with the body text `label`; returns how many sizing passes its body ran in. -fn headed_frame(frames: &mut Frames, label: &str) -> usize { +/// One frame of `Headed` with the body text `label`; returns the frame's passes and how many sizing passes its body ran +/// in. +fn headed_frame(frames: &mut Frames, label: &str) -> (usize, usize) { let sizing = Cell::new(0); - frames.frame(vec![], |ui| { + let passes = frames.frame(vec![], |ui| { in_region(ui, STACK_ROOM, |ui| { let headed = Headed { common: Common::new(), props: ContainerProps::new().header(HeaderRegion::new()) }; headed.show(ui, |ui, _| { @@ -755,7 +756,7 @@ fn headed_frame(frames: &mut Frames, label: &str) -> usize { }); }); }); - sizing.get() + (passes, sizing.get()) } /// A view in the header of a content-sized container replays when the container measures its regions again: its @@ -771,9 +772,19 @@ fn a_view_in_a_measured_header_replays_in_the_sizing_pass_and_the_real_run() { headed_frame(&mut frames, "Short"); assert_eq!(title_runs(), 0, "settled: an idle frame replays the header's view"); // A second line, no wider than the first: the container's width, and with it the header's room, stays. - let sizing = headed_frame(&mut frames, "Short\nShort"); + let (passes, sizing) = headed_frame(&mut frames, "Short\nShort"); assert!(sizing > 0, "the taller label made the container measure its regions again"); + assert_eq!(passes, 2, "the taller container asks for one discard pass"); assert_eq!(title_runs(), 0, "the unchanged view replayed in every call: {:?}", last_frame_memo_runs(&frames.ctx)); + let heading = |runs: Vec<(&'static str, Id, MemoRun)>| -> Vec { + runs.into_iter().filter(|(name, _, _)| name.ends_with("::Title")).map(|(_, _, run)| run).collect() + }; + assert_eq!(heading(last_pass_memo_runs(&frames.ctx)), [MemoRun::Replayed], "the discard pass's real run replayed the view"); + assert_eq!( + heading(last_frame_memo_runs(&frames.ctx)), + [MemoRun::Replayed; 3], + "the view was called and replayed in the sizing pass and in the real run of each of the two passes" + ); } /// A paragraph that wraps at its room's width. From cfe04c3ab41ccb5d041d89af160c3dac5e12a091 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 13:18:26 +0000 Subject: [PATCH 3/4] Memoized views: a row unit replays in the row's measuring sweeps With the flow facts out of the key, the counting sweep's call keys as the real call does, and an idle frame or a frame at the same width runs a memoized row unit in none of the row's sweeps. The trials say so: the row-unit trial asserts no measuring run, and the counting-call trial describes the call by its flow. --- crates/ui-contract/tests/it/contract/memo_row.rs | 11 ++++++----- crates/ui-widgets/tests/it/body/memo_view.rs | 11 +++-------- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/crates/ui-contract/tests/it/contract/memo_row.rs b/crates/ui-contract/tests/it/contract/memo_row.rs index 1c5019b3e..7fd587c01 100644 --- a/crates/ui-contract/tests/it/contract/memo_row.rs +++ b/crates/ui-contract/tests/it/contract/memo_row.rs @@ -1,5 +1,6 @@ -//! A memoized view that is one unit of a shrinking row: the row's counting sweep calls it with another key than its -//! real run, and that call leaves the replay decision of the pass to the calls after it and reuses its own measure. +//! A memoized view that is one unit of a shrinking row: the row's counting sweep calls it in another flow than its real +//! run (the content shows unbounded there), and that call leaves the replay decision of the pass to the real call and +//! reuses the measure of the last counting call. use craft_ui::contract::{MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::layout::BodyLayout; @@ -26,11 +27,11 @@ fn of_view(runs: Vec<(&'static str, egui::Id, MemoRun)>) -> Vec { } /// A memoized view in a row that is not short, whose new content is wider: it runs once in the real run that meets the -/// new props and once as a measuring run in the row's counting sweep, whose call keys apart from the real run's -/// (the content shows unbounded there). The real run of the discard pass that sweep belongs to replays, and so does +/// new props and once as a measuring run in the row's counting sweep, whose flow is not the real run's (the content +/// shows unbounded there). The real run of the discard pass that sweep belongs to replays, and so does /// every call of the next frame, a counting sweep's included. #[trial] -fn a_memoized_row_unit_replays_after_the_rows_counting_call_with_another_key() { +fn a_memoized_row_unit_replays_after_the_rows_counting_call() { let width = Cell::new(60.0); let mut frames = Frames::new(); let frame = |frames: &mut Frames| { diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index cceab4213..8ad63631a 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -1687,7 +1687,7 @@ fn line(props: &mut Line, ui: &mut Ui) -> Rect { /// A memoized view is one unit of the shrinking row around it: with room it is as wide as its content, and when a /// sibling after it grows it narrows so the row fits, though the region it is offered stays the same. It replays while -/// the row's width for it is unchanged and runs once when that width changes. +/// the row's width for it is unchanged, in the row's measuring sweeps too, and runs once when that width changes. #[trial] fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { const ROOM: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(310.0, 50.0) }; @@ -1710,7 +1710,7 @@ fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { } let (wide, _) = frame(&mut frames, "B"); assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "an idle frame replays the view"); - assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "an idle frame runs the view at most once per measuring sweep of the row"); + assert_eq!(measuring_runs_of(&frames, "Line"), 0, "an idle frame replays the view in the row's measuring sweeps too"); let (narrow, after) = frame(&mut frames, "A much longer button label"); assert_eq!(runs_of(&frames, "Line"), [MemoRun::Ran], "a new width runs the view"); assert!(narrow.width() < wide.width(), "the view narrows: {narrow:?} from {wide:?}"); @@ -1719,14 +1719,9 @@ fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { frame(&mut frames, "A much longer button label"); } assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "at the same width it replays again"); - assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "at the same width the view runs at most once per measuring sweep of the row"); + assert_eq!(measuring_runs_of(&frames, "Line"), 0, "at the same width the view replays in the row's measuring sweeps too"); } -/// The sweeps of a shrinking row's measuring run that show its units: the counting sweep and, for a short row, the -/// sweep that asks its body units for their least. Until FW-310 moves `unbounded` out of the scope key, the counting -/// sweep's call keys apart from the real call's and a memoized unit runs in each sweep; FW-310 tightens this to none. -const SWEEPS: usize = 2; - /// How many times the views named `name` ran in the last frame outside the real run of its last pass: in sizing and /// measuring runs. fn measuring_runs_of(frames: &Frames, name: &str) -> usize { From 059d8c9ea36c752101f6d793641d81df6d7446d2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 14:12:07 +0000 Subject: [PATCH 4/4] Memoized views: derived returns the same Arc while its key is unchanged --- crates/ui-contract/src/runtime/derived.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-contract/src/runtime/derived.rs b/crates/ui-contract/src/runtime/derived.rs index d934215a2..d2030df44 100644 --- a/crates/ui-contract/src/runtime/derived.rs +++ b/crates/ui-contract/src/runtime/derived.rs @@ -46,6 +46,9 @@ impl Store { /// The value of the component `id` derived from `key`: the kept one while `key` is the one it was built from, else /// `build`'s, which is kept in its place. One value is kept per id and value type `V`; a component that derives two /// values of one type gives each its own id. +/// +/// While the key is unchanged, every call returns the same `Arc` (`Arc::ptr_eq` holds), so a caller that keeps the +/// last result can tell "unchanged" from a pointer compare. pub fn derived(ctx: &Context, id: Id, key: &K, build: impl FnOnce() -> V) -> Arc { let mut memo = MemoKey::of_view(ctx); memo.feed_hash(&K::identity());