diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 695b6edde..f9ee20ab8 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1,8 +1,9 @@ //! Layout memory: sizes one pass measures and the next pass places by, the one discard pass a change asks for, what //! this pass's measuring runs found, and the measurements bodies keep across passes. //! -//! A body's measuring run leaves a transcript: every value it hands forward (a record by id, a contribution to an -//! aggregator open around it, the transcripts of the bodies nested in it, in order) and every measure call each +//! A body's measuring run leaves a transcript: every value it hands forward (a record by id, a measure or a text the +//! content beside the body shows, a contribution to an aggregator open around it, the transcripts of the bodies nested +//! in it, in order) and every measure call each //! component in it got. A later pass whose inputs are the body's key takes the transcript instead of running the //! content: its records serve this pass and its contributions are made again. The real run then asks each component //! the calls the transcript holds, at the measuring run's own proposal and room, and compares; a component added, @@ -82,9 +83,18 @@ pub(crate) trait Contribution: Send + Sync { fn report(&self) -> Option<(Id, f32)>; } +/// What a record holds: a measure, or a text the run found that content outside the body shows (the value text a +/// viewer shows beside a story). A text is an output of the measuring run as much as its size, so it serves exactly +/// when the run's measure does. +#[derive(Clone, Debug, PartialEq)] +enum Recorded { + Measured(Measured), + Text(Option>), +} + /// One thing a measuring run handed forward, in the order it did. enum Item { - Record(Id, Measured), + Record(Id, Recorded), Contribute(Arc), Body(Id, Arc), } @@ -120,12 +130,12 @@ struct Transcript { real: Mutex>>, } -/// A record of this pass's measures. -#[derive(Clone, Copy)] +/// A record of this pass's runs. +#[derive(Clone)] struct Found { /// The cumulative pass number that recorded it. pass: u64, - measured: Measured, + recorded: Recorded, /// The body whose kept transcript gave it, rather than a run of this pass. kept: Option, } @@ -327,35 +337,64 @@ fn real(ctx: &Context) -> bool { /// Hands forward what a measuring run found under `id`: it serves the rest of this pass, and joins the transcript of /// the innermost body whose measuring run is open. A run of this pass that finds, at the same room, something other /// than what a kept transcript gave the pass shows that transcript changed. -pub(crate) fn emit_record(ctx: &Context, id: Id, mut measured: Measured) { +pub(crate) fn emit_record(ctx: &Context, id: Id, measured: Measured) { + emit(ctx, id, Recorded::Measured(measured)); +} + +/// Hands forward a text a run found under `id` that content outside the body it runs in shows, as [`emit_record`] +/// hands forward a measure: it serves the rest of this pass, and a later pass that takes the kept measurement of a body +/// it ran in gets it with that measurement, where the content that found it does not run. A real run emits it too: a +/// text other than the one a kept transcript gave the pass shows that transcript changed. +pub fn emit_text(ctx: &Context, id: Id, text: Option<&str>) { + emit(ctx, id, Recorded::Text(text.map(Arc::from))); +} + +/// The text a run of this pass handed forward under `id` ([`emit_text`]), or a kept transcript gave this pass. +pub fn text(ctx: &Context, id: Id) -> Option> { + let moment = Moment::of(ctx); + let pass = ctx.cumulative_pass_nr(); + with(ctx, &moment, |memory| match memory.measured.get(&id).filter(|found| found.pass == pass) { + Some(Found { recorded: Recorded::Text(text), .. }) => text.clone(), + _ => None, + }) +} + +fn emit(ctx: &Context, id: Id, mut recorded: Recorded) { let moment = Moment::of(ctx); let pass = ctx.cumulative_pass_nr(); let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ctx)); with(ctx, &moment, |memory| { - // A record keys on what its measure read: the room, and the inputs the innermost open body read so far. - measured.inputs = memory - .measuring - .iter() - .rev() - .find_map(|open| match open { - Open::Body { inputs, .. } => Some(fingerprint(inputs)), - Open::Boundary | Open::Call { .. } => None, - }) - .unwrap_or(0); - let last = memory.measured.insert(id, Found { pass, measured, kept: None }); - if let Some(Found { pass: at, measured: was, kept: Some(from) }) = last + // A measure keys on what it read: the room, and the inputs the innermost open body read so far. + if let Recorded::Measured(measured) = &mut recorded { + measured.inputs = memory + .measuring + .iter() + .rev() + .find_map(|open| match open { + Open::Body { inputs, .. } => Some(fingerprint(inputs)), + Open::Boundary | Open::Call { .. } => None, + }) + .unwrap_or(0); + } + let last = memory.measured.insert(id, Found { pass, recorded: recorded.clone(), kept: None }); + if let Some(Found { pass: at, recorded: was, kept: Some(from) }) = last && at == pass - && was.inputs == measured.inputs - && (was.room - measured.room).abs().max_elem() <= tolerance - && (was.took - measured.took).abs().max_elem() > tolerance + && match (&was, &recorded) { + (Recorded::Measured(was), Recorded::Measured(now)) => { + was.inputs == now.inputs + && (was.room - now.room).abs().max_elem() <= tolerance + && (was.took - now.took).abs().max_elem() > tolerance + } + (was, now) => was != now, + } { #[cfg(feature = "testing")] if std::env::var_os("CRAFT_UI_TRACE_KEPT").is_some() { - eprintln!("layout memory: a run of this pass found {id:?} at {measured:?}, its kept record said {was:?}"); + eprintln!("layout memory: a run of this pass found {id:?} at {recorded:?}, its kept record said {was:?}"); } memory.changed(moment.frame, Some(from)); } - memory.push(Item::Record(id, measured)); + memory.push(Item::Record(id, recorded)); }); } @@ -580,7 +619,10 @@ pub(crate) fn backstop(ctx: &Context, id: Id, took: Vec2) { pub(crate) fn measured(ctx: &Context, id: Id) -> Option { let moment = Moment::of(ctx); let pass = ctx.cumulative_pass_nr(); - with(ctx, &moment, |memory| memory.measured.get(&id).filter(|found| found.pass == pass).map(|found| found.measured)) + with(ctx, &moment, |memory| match memory.measured.get(&id).filter(|found| found.pass == pass) { + Some(Found { recorded: Recorded::Measured(measured), .. }) => Some(*measured), + _ => None, + }) } /// Whether a run of this pass, not a kept transcript, recorded what serves under `id`. @@ -677,8 +719,8 @@ pub(crate) fn kept_serves(ctx: &Context, b let mut nested = Vec::new(); for item in &transcript.items { match item { - Item::Record(at, measured) => { - memory.measured.insert(*at, Found { pass, measured: *measured, kept: Some(body) }); + Item::Record(at, recorded) => { + memory.measured.insert(*at, Found { pass, recorded: recorded.clone(), kept: Some(body) }); } Item::Contribute(contribution) => contributions.push(contribution.clone()), Item::Body(at, inner) => nested.push((*at, inner.clone())), diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index f52fc0377..d2fe236cd 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -13,6 +13,7 @@ use craft_ui::contract::{CommandSet, Commands as _, Gap, Pad, Props as _, ShowCo use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::{Grid, Stack}; use craft_ui::runtime::env::{WindowKey, with_env}; +use craft_ui::runtime::layout_memory; use craft_ui::sections::{HeaderCommand, HeaderStrength, Panel}; use craft_ui::shell::AppShell; use craft_ui::style::SurfaceKind; @@ -180,8 +181,9 @@ impl Card<'_> { Grid::new(FORM_ROWS).fill_width().show(ui, |ui, _| { for story in self.stories { Text::new(story.caption.to_owned()).show(ui); - let shown = Stack::new().fill_width().show(ui, |ui, _| self.body(ui, story, None, cells)).inner; - Text::new(shown.and_then(|shown| shown.value_text).unwrap_or_default()).shade(Shade::Muted).show(ui); + let body = self.story_body(story, None); + Stack::new().fill_width().show(ui, |ui, _| body.show(ui, cells.entry(story.index).or_default())); + Text::new(body.value_text(ui).unwrap_or_default()).shade(Shade::Muted).show(ui); } }); } @@ -207,14 +209,18 @@ impl Card<'_> { /// The body of `story`, with its state, under `caption` when given. fn body(&self, ui: &mut Ui, story: &CardStory<'_>, caption: Option<&str>, cells: &mut Cells) -> BodyShown { + self.story_body(story, caption).show(ui, cells.entry(story.index).or_default()) + } + + /// The body of `story` under `caption` when given. + fn story_body(&self, story: &CardStory<'_>, caption: Option<&str>) -> StoryBody { let key = format!("{}/{}", self.key, story.story.story.name); - let body = StoryBody { + StoryBody { look: self.look, gated: self.gated, caption: caption.map(str::to_owned), ..StoryBody::new(key, story.story, self.surface, self.room, Pad::None) - }; - body.show(ui, cells.entry(story.index).or_default()) + } } } @@ -246,8 +252,6 @@ pub struct BodyShown { /// Where the story shows in flow: its surface, or the whole room for a story that takes no room in flow; `None` /// for a story that shows only a dialog. pub flow: Option, - /// The shown value as the story's component words it ([`StoryOutput::value_text`]). - pub value_text: Option, } impl StoryBody { @@ -290,13 +294,15 @@ impl StoryBody { let runs = state.dialog.painted || craft_ui::runtime::frame::discardable(ui.ctx()); let ran = std::cell::Cell::new(false); let flow = std::cell::Cell::new(None); - let output = std::cell::RefCell::new(None); + let value_key = self.value_key(); let shell = AppShell::embedded(window).body(|ui, _, data: &mut StoryData| { if runs { ran.set(!ui.is_sizing_pass()); let surface = host.stack().show(ui, |ui, _| host.content(ui, show, data)); flow.set(Some(surface.output.rect)); - *output.borrow_mut() = Some(surface.inner); + if let Some(output) = &surface.inner { + layout_memory::emit_text(ui.ctx(), value_key, output.value_text.as_deref()); + } } }); // A story that shows a dialog gets the whole room for it. @@ -327,8 +333,17 @@ impl StoryBody { } state.note_start(); let flow = if dialog_room { None } else { flow.get() }; - let value_text = output.into_inner().flatten().and_then(|output| output.value_text); - BodyShown { flow, value_text } + BodyShown { flow } + } + + /// The shown value as the story's component words it ([`StoryOutput::value_text`]), as this pass's run of the + /// story found it, or the kept measurement of a body around the story that this pass took in place of running it. + pub fn value_text(&self, ui: &Ui) -> Option { + layout_memory::text(ui.ctx(), self.value_key()).map(|text| text.to_string()) + } + + fn value_key(&self) -> Id { + craft_ui::testing::memory::global("gallery.card.value", &self.key) } } diff --git a/crates/ui-gallery/tests/it/overview.rs b/crates/ui-gallery/tests/it/overview.rs index 0937151b9..f85bc916d 100644 --- a/crates/ui-gallery/tests/it/overview.rs +++ b/crates/ui-gallery/tests/it/overview.rs @@ -53,6 +53,20 @@ fn a_settled_overview_pass_runs_no_measuring_run() { assert!(runs.is_empty(), "a settled pass measured {} bodies: {runs:?}", runs.len()); } +/// A card in form rows shows each story's value text beside it, as the story's run found it: a settled frame of the +/// Slider card, whose bodies take their kept measurements in place of running the stories, runs one pass. +#[trial] +fn a_settled_form_rows_card_runs_one_pass_per_frame() { + let mut gallery = gallery_filtered("Controls", "Slider"); + let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); + fixture.room(Vec2::new(1400.0, 900.0)).settle(); + for frame in 0..4 { + fixture.idle(1); + assert_eq!(fixture.passes(), 1, "settled frame {frame} ran {} passes", fixture.passes()); + assert!(painted(&fixture, "100.0"), "settled frame {frame} shows the Maximum story's value text"); + } +} + /// The registered type name of the component listed as `name`. fn type_of(name: &str) -> &'static str { Catalog::linked().components.iter().find(|component| component.name == name).unwrap_or_else(|| panic!("{name} is listed")).type_name