diff --git a/crates/browse/src/ui/places/stories.rs b/crates/browse/src/ui/places/stories.rs index 6eff96405..9338a387e 100644 --- a/crates/browse/src/ui/places/stories.rs +++ b/crates/browse/src/ui/places/stories.rs @@ -129,7 +129,9 @@ fn show_places(ui: &mut Ui, data: &mut StoryData, setup: Setup) -> StoryOutput { let mut out = None; { let Demo { cache, .. } = &mut *demo; - Stack::new().room_height(380.0).show(ui, |ui, _| { + // The old story's tree box: 380 points tall however many rows it holds. + let room = craft_ui::testing::stage_fitting(ui, |_| 380.0); + Stack::new().fill().show_at(ui, room, |ui, _| { let mut tree = PlacesTree::new("Places", &places, &mut *cache).row_menu(|_| vec![Entry::new(String::from("folder.rename"), "Rename Folder…")]); if let Some(current) = current.as_deref() { diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index ea89f7bf6..9923f1ff7 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -9,6 +9,7 @@ use super::regions::{ }; use super::reorder::REORDER_BAND; use super::scroll::{Glide, Jumps, ScrollState, aim_glide, follow_anchor, jump_frame, overflow_inset, scroll_of}; +use super::size::MeasureKey; use super::window::{WindowMode, os_window, window_instance}; use super::{BodyHooks, BodyView}; use crate::contract::cx::{BodyCx, BodyOwner}; @@ -282,7 +283,9 @@ impl ShapeHooks for BodyHooks<'_> { fn extent(&mut self, comp: &C, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { let props = comp.props(Internal::new()); self.room = self.mount_room(props, ui, id, at); - self.given = self.given_axes(props, &Env::of(ui), at); + let env = Env::of(ui); + self.given = self.given_axes(props, &env, at); + self.given.1 |= self.over_room(props, &env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; let room = self.room.x - 2.0 * pad_of(scx.tokens, props.pad); @@ -377,56 +380,27 @@ impl ShapeHooks for BodyHooks<'_> { if found { layout_memory::kept_also_under(&ctx, id, key); } + // A capped body whose content outgrew its room was laid out as given it: the record of its content says so. + if self.over_room(&props, at.env, at.at, &ctx, id) { + self.given.1 = true; + } took } - None => { - #[cfg(feature = "testing")] - crate::runtime::measure::count_body(&ctx, id); - layout_memory::begin_measure(&ctx, id); - let available = match at.at { - ShowAt::Rect(rect) => rect, - // Not the cursor: in a right-to-left layout it extends to -inf along the line. - ShowAt::Flow => at.ui.available_rect_before_wrap(), - }; - let origin = available.min; - // Along an axis with no room limit the content grows away from its start edge: in a right-to-left - // layout that edge is the right one, so the measuring rect is as wide as a scrolling region and - // ends where the room does, as the real run's region does. - let rect = if self.room.x.is_infinite() && at.env.direction.is_rtl() && available.max.x.is_finite() { - Rect::from_min_max( - Pos2::new(available.max.x - crate::contract::MAX_EXTENT, origin.y), - Pos2::new(available.max.x, origin.y + self.room.y), - ) + // A capped body takes its content height while that fits its room. Taller, the run is taken back and the body + // is laid out as given the room, at the footer and header this run measured, so the children that fill share + // it; its record of the content height lets later runs of the pass and kept transcripts lay it out the same. + None if self.capped(&props, at.env, at.at) => { + let fits = self.room.y + tolerance; + let (content, kept) = crate::contract::draft(&ctx, || self.measure_run(comp, at, cx, key.clone(), None), |took| took.y <= fits); + if kept { + content } else { - Rect::from_min_size(origin, self.room) - }; - cx.core.rect = rect; - cx.core.flow = craft_behavior::Flow::new(rect, at.env.direction.is_rtl()); - cx.core.content_rect = cx.core.flow.inset(cx.style.metrics().padding); - let builder = UiBuilder::new().layer_id(measure_layer(&props, id, at.ui)).max_rect(rect).sizing_pass().invisible(); - // The regions take explicit scope ids under `id`, so every component in them gets the id the real run - // gives it and the records it leaves match. - let mut measure_ui = Ui::new(ctx.clone(), sub(id, "measure"), builder); - let installed = Env::install_for(&measure_ui, at.env.clone()); - let mut values = AppValues::default(); - comp.content_env(cx, &mut values); - self.content(comp, &mut measure_ui, at.env, cx, &values); - Env::restore(&ctx, installed); - let record = |key: Id, took: Vec2| layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(self.room, took)); - record(id, self.body_size.unwrap_or(Vec2::ZERO)); - for (key, size) in - [("header", self.header_size), ("footer", self.footer_size), ("end", self.end_size), ("controls", self.controls_size)] - { - if let Some(size) = size { - record(sub(id, key), size); - } + self.given.1 = true; + self.measured_footer = self.footer_size.unwrap_or(Vec2::ZERO); + self.measure_run(comp, at, cx, key, Some(content)) } - layout_memory::end_measure(&ctx, id, key); - let body = if self.open { self.body_size.unwrap_or(Vec2::ZERO) } else { Vec2::ZERO }; - let (header, footer, end) = - (self.header_size.unwrap_or(Vec2::ZERO), self.footer_size.unwrap_or(Vec2::ZERO), self.end_size.unwrap_or(Vec2::ZERO)); - self.regions_size(&props, body, header, footer, end) + pad } + None => self.measure_run(comp, at, cx, key, None), }; // A layer hung from an opener is at least as wide as the opener its overlay asks for, in the measuring run too, // so the rows of a content-sized list inside it are placed at that width. @@ -1096,3 +1070,64 @@ impl ShapeHooks for BodyHooks<'_> { } } } + +impl BodyHooks<'_> { + /// The measuring run of the regions in `self.room`, under the inputs `key`: what they took together, padding + /// included. `content`: the size the body's content took in the run taken back before this one, recorded with it. + fn measure_run( + &mut self, + comp: &mut C, + at: &Measuring<'_, '_>, + cx: &mut Cx<'_, C>, + key: MeasureKey, + content: Option, + ) -> Vec2 { + let props = Arc::clone(&self.props); + let (id, ctx) = (cx.core.id, at.ui.ctx().clone()); + let pad = Vec2::splat(2.0 * pad_of(at.scx.tokens, props.pad)); + #[cfg(feature = "testing")] + crate::runtime::measure::count_body(&ctx, id); + layout_memory::begin_measure(&ctx, id); + let available = match at.at { + ShowAt::Rect(rect) => rect, + // Not the cursor: in a right-to-left layout it extends to -inf along the line. + ShowAt::Flow => at.ui.available_rect_before_wrap(), + }; + let origin = available.min; + // Along an axis with no room limit the content grows away from its start edge: in a right-to-left + // layout that edge is the right one, so the measuring rect is as wide as a scrolling region and + // ends where the room does, as the real run's region does. + let rect = if self.room.x.is_infinite() && at.env.direction.is_rtl() && available.max.x.is_finite() { + Rect::from_min_max(Pos2::new(available.max.x - crate::contract::MAX_EXTENT, origin.y), Pos2::new(available.max.x, origin.y + self.room.y)) + } else { + Rect::from_min_size(origin, self.room) + }; + cx.core.rect = rect; + cx.core.flow = craft_behavior::Flow::new(rect, at.env.direction.is_rtl()); + cx.core.content_rect = cx.core.flow.inset(cx.style.metrics().padding); + let builder = UiBuilder::new().layer_id(measure_layer(&props, id, at.ui)).max_rect(rect).sizing_pass().invisible(); + // The regions take explicit scope ids under `id`, so every component in them gets the id the real run + // gives it and the records it leaves match. + let mut measure_ui = Ui::new(ctx.clone(), sub(id, "measure"), builder); + let installed = Env::install_for(&measure_ui, at.env.clone()); + let mut values = AppValues::default(); + comp.content_env(cx, &mut values); + >::content(self, comp, &mut measure_ui, at.env, cx, &values); + Env::restore(&ctx, installed); + let record = |key: Id, took: Vec2| layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(self.room, took)); + record(id, self.body_size.unwrap_or(Vec2::ZERO)); + for (key, size) in [("header", self.header_size), ("footer", self.footer_size), ("end", self.end_size), ("controls", self.controls_size)] { + if let Some(size) = size { + record(sub(id, key), size); + } + } + if let Some(content) = content { + record(sub(id, "content"), content); + } + layout_memory::end_measure(&ctx, id, key); + let body = if self.open { self.body_size.unwrap_or(Vec2::ZERO) } else { Vec2::ZERO }; + let (header, footer, end) = + (self.header_size.unwrap_or(Vec2::ZERO), self.footer_size.unwrap_or(Vec2::ZERO), self.end_size.unwrap_or(Vec2::ZERO)); + self.regions_size(&props, body, header, footer, end) + pad + } +} diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 425cb72f5..ae4a9f600 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -94,8 +94,7 @@ impl BodyHooks<'_> { scoped.content_column = content_column; scoped.row_room = None; scoped.row_line = None; - // A body with a room height of its own gives that height to the children that fill it. - scoped.content = (!self.given.0, !self.given.1 && props.room_height.is_none()); + scoped.content = (!self.given.0, !self.given.1); // A content-sized container offers its children, in the real run, the width this pass measured it at: a // child that fits itself into its room (a bar moving items into "More") fits the width the container // takes, not the room it could have taken. A fill container that is not given the width still takes at diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 3ce9383c7..f2323cc86 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -3,18 +3,20 @@ use super::BodyHooks; use super::placement::overlay_of; use super::regions::{RegionSizes, end_full_height, footer_in_end}; +use super::scroll::scroll_of; use crate::contract::run::ShowAt; use crate::contract::{ContainerProps, Mount, ShellPane, Sizing}; use crate::runtime::egui::areas; use crate::runtime::env::Env; use crate::runtime::layout_memory; use crate::runtime::memory::sub; +use craft_behavior::layout_memory::measure_tolerance; use egui::{Context, Id, Rect, Ui, Vec2}; use std::sync::Arc; /// The inputs a body's measuring run measures under. A later pass offering the same takes the body's kept /// transcript (`layout_memory::kept_serves`); its real run checks that the content is the same. -#[derive(PartialEq)] +#[derive(Clone, PartialEq)] pub(super) struct MeasureKey { props: MeasuredProps, room: Vec2, @@ -28,6 +30,7 @@ pub(super) struct MeasureKey { } /// The props a body was measured under, compared on the fields its measure reads. +#[derive(Clone)] struct MeasuredProps(Arc); impl PartialEq for MeasuredProps { @@ -37,7 +40,7 @@ impl PartialEq for MeasuredProps { } /// What a body's measure reads of its env besides the room. -#[derive(PartialEq)] +#[derive(Clone, PartialEq)] struct EnvFacts { style: crate::style::EnvKey, words: u64, @@ -110,6 +113,25 @@ impl<'b> BodyHooks<'b> { } } + /// Whether the container fills a height its parent sizes from its content, in a room of finite height: it takes + /// its content height, at most that room. A body that scrolls along the height keeps to the room by scrolling. + pub(super) fn capped(&self, props: &ContainerProps, env: &Env, at: ShowAt) -> bool { + matches!((at, &props.mount), (ShowAt::Flow, Mount::Inline)) + && self.sizing(props) == Sizing::Fill + && env.content.1 + && self.room.y.is_finite() + && !scroll_of(props).is_some_and(|scroll| scroll.vertical_on()) + } + + /// Whether a capped container's content is taller than its room, as this pass's measure found it (the record + /// `content` its measuring run leaves then): it takes the room and lays its children out as given the height there, + /// so the children that fill share it. + pub(super) fn over_room(&self, props: &ContainerProps, env: &Env, at: ShowAt, ctx: &Context, id: Id) -> bool { + let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ctx)); + self.capped(props, env, at) + && layout_memory::measured(ctx, sub(id, "content")).is_some_and(|content| content.took.y > self.room.y + tolerance) + } + /// What the regions took together, padding included, from the records a measuring run left in this pass, when they /// serve a run offered `self.room`: on each axis the room equals the recorded one, or the container is not given /// that axis, took less than the recorded room (the room did not bound it) and fits in the room now. diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 5e1747369..ded03d9bc 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -546,9 +546,10 @@ pub struct ContainerProps { pub pad: Pad, /// How the size follows the content. pub sizing: Sizing, - /// The height the body offers its children in flow, in place of the flow's (unbounded in a scrolling body): a - /// child that fills the height is given it, any other child takes its content height. A host that shows content - /// of either kind at a definite room (a story in a gallery card) sets it. + /// The height the body offers its children in flow, in place of the flow's (unbounded in a scrolling body): the + /// most a child takes. Every child takes its content height, a child that fills or scrolls at most this height, + /// as a scrolling list is as tall as its rows until they outgrow the room. A host that shows content of either + /// kind at a definite room (a story in a gallery card) sets it. pub room_height: Option, /// How the body lays out its children. pub layout: BodyLayout, diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index ab9d15505..e9a330328 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -138,7 +138,8 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { previous: Option>, content: Vec2, room: Vec2, - /// A measuring run under a body sized from its content: the axes (x, y) the collection takes from its content. + /// The axes (x, y) the collection takes from its content under a body sized from its content: the height in every + /// run, the width in a measuring run (the real run shows a collection that fills across the column it is held in). from_content: (bool, bool), scrolls: bool, /// The axis the rows overflow along. diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 0d0c02770..8cc5e5209 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -169,7 +169,8 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { ShowAt::Flow => crate::layout::flow_room(ui), }; self.room = room; - self.from_content = if crate::runtime::measure::active(ui.ctx()) { Env::of(ui).content } else { (false, false) }; + let content = Env::of(ui).content; + self.from_content = (content.0 && crate::runtime::measure::active(ui.ctx()), content.1); self.header.measure(scx); let bounded = room.x.is_finite(); let mut widest = 0.0; diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index bb406839a..a86747069 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -112,10 +112,10 @@ pub(crate) use body::MOVE_BAND; pub use craft_behavior::ColumnKey; pub use craft_behavior::DropOperation; pub(crate) use run::measure_under; -pub(crate) use steps::keeping_ids; #[cfg(feature = "testing")] pub(crate) use steps::queue_reveal; pub(crate) use steps::{child_reveal, peek_reveal, queue_child_reveal, take_reveal}; +pub(crate) use steps::{draft, keeping_ids}; /// Adds the runtime to `ctx`: `runtime::install` with the overlay host's ghost-layer painter in the end hook. pub fn install(ctx: &egui::Context, spec: crate::runtime::InstallSpec) -> Result<(), crate::runtime::InstallError> { diff --git a/crates/ui-contract/src/contract/steps.rs b/crates/ui-contract/src/contract/steps.rs index 58b99bb2d..5f2aaf702 100644 --- a/crates/ui-contract/src/contract/steps.rs +++ b/crates/ui-contract/src/contract/steps.rs @@ -27,7 +27,7 @@ pub(crate) use apply::{ValueEdit, apply_values, rerun_after_edit}; pub(crate) use env::{env, resolved, variants}; pub(crate) use finish::{before_finish, inert_response, record_size, value_changed}; pub(super) use id::measuring; -pub(crate) use id::{id, keeping_ids}; +pub(crate) use id::{draft, id, keeping_ids}; pub(crate) use label::{activate_by_label, scrub_by_label}; pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx}; pub(crate) use paint::{paint_focus, paint_part_layers, paint_surface, surface_ink}; diff --git a/crates/ui-contract/src/contract/steps/id.rs b/crates/ui-contract/src/contract/steps/id.rs index 5b0508051..5685ad4f1 100644 --- a/crates/ui-contract/src/contract/steps/id.rs +++ b/crates/ui-contract/src/contract/steps/id.rs @@ -21,6 +21,16 @@ pub(in crate::contract) fn measuring(ctx: &Context, f: impl FnOnce() -> R) -> keeping_ids(ctx, || (crate::runtime::measure::run(ctx, f), true)) } +/// Runs the measuring run `run` as a draft (`layout_memory::draft`) whose `Auto` ordinals go with it: taken back, it leaves +/// the pass's records, transcripts, contributions and ordinals as it found them, so a run that replaces it gives every +/// component the id it gave. `keep` decides from the result; returns it and whether it was kept. +pub(crate) fn draft(ctx: &Context, run: impl FnOnce() -> R, keep: impl FnOnce(&R) -> bool) -> (R, bool) { + keeping_ids(ctx, || { + let (out, kept) = crate::runtime::layout_memory::draft(ctx, run, keep); + ((out, kept), !kept) + }) +} + /// Runs `f` and, when it returns `true` beside its result, leaves the `Auto` ordinals as it found them, so what runs /// next in the same pass gives every component the id `f`'s run gave it. pub(crate) fn keeping_ids(ctx: &Context, f: impl FnOnce() -> (R, bool)) -> R { diff --git a/crates/ui-contract/src/layout/column_group.rs b/crates/ui-contract/src/layout/column_group.rs index d2cf3e3f1..48c8651e4 100644 --- a/crates/ui-contract/src/layout/column_group.rs +++ b/crates/ui-contract/src/layout/column_group.rs @@ -41,27 +41,49 @@ impl layout_memory::Contribution for Reported { Report::Beyond(..) => None, } } + + fn undo(&self, ctx: &Context) -> layout_memory::TakeBack { + let (group, report) = (self.group, self.report.clone()); + let was = with_group(ctx, group, |widest, beyond| match &report { + Report::Width(column, _) => widest.get(column).copied(), + Report::Beyond(columns, _) => beyond.get(columns).copied(), + }); + Box::new(move |ctx| { + let Some(was) = was else { return }; + with_group(ctx, group, |widest, beyond| match (&report, was) { + (Report::Width(column, _), Some(width)) => drop(widest.insert(column.clone(), width)), + (Report::Width(column, _), None) => drop(widest.remove(column)), + (Report::Beyond(columns, _), Some(past)) => drop(beyond.insert(columns.clone(), past)), + (Report::Beyond(columns, _), None) => drop(beyond.remove(columns)), + }); + }) + } } -/// Adds `report` to the innermost open group `group`; `None` when that group is not open. -fn add(ctx: &Context, group: Id, report: Report) -> Option { +/// Runs `f` on the widths of the innermost open group `group`; `None` when that group is not open. +fn with_group(ctx: &Context, group: Id, f: impl FnOnce(&mut HashMap, &mut HashMap, f32>) -> R) -> Option { pass_state::with::(ctx, |open| { let (widest, beyond) = open.0.iter_mut().rev().find_map(|frame| match frame { Frame::Group { id, widest, beyond, .. } if *id == group => Some((widest, beyond)), _ => None, })?; - Some(match report { - Report::Width(column, content) => { - let widest = widest.entry(column).or_insert(0.0); - *widest = widest.max(content); - *widest - } - Report::Beyond(columns, past) => { - let widest = beyond.entry(columns).or_insert(0.0); - *widest = widest.max(past); - *widest - } - }) + Some(f(widest, beyond)) + }) +} + +/// Adds `report` to the innermost open group `group`; `None` when that group is not open. +fn add(ctx: &Context, group: Id, report: Report) -> Option { + with_group(ctx, group, |widest, beyond| match report { + Report::Width(column, content) => { + let widest = widest.entry(column).or_insert(0.0); + *widest = widest.max(content); + *widest + } + Report::Beyond(columns, past) => { + let widest = beyond.entry(columns).or_insert(0.0); + *widest = widest.max(past); + *widest + } }) } diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index 558b6bf1d..2303fbb97 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -275,6 +275,20 @@ impl layout_memory::Contribution for ControlMin { fn report(&self) -> Option<(Id, f32)> { Some((sub(self.container, "control_min"), self.width)) } + + fn undo(&self, ctx: &Context) -> layout_memory::TakeBack { + let container = self.container; + let label = move |scope: &&mut Scope| scope.container == container && matches!(scope.kind, Kind::Label(_)); + let was = pass_state::with::(ctx, |stack| stack.0.iter_mut().rev().find(label).map(|scope| scope.control_min)); + Box::new(move |ctx| { + let Some(was) = was else { return }; + pass_state::with::(ctx, |stack| { + if let Some(scope) = stack.0.iter_mut().rev().find(label) { + scope.control_min = was; + } + }); + }) + } } /// The narrowest width the first control of the open label scope of `container` has reported so far; 0 before any. diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 74f62effe..efaa8012a 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -9,6 +9,9 @@ //! the calls the transcript holds, at the measuring run's own proposal and room, and compares; a component added, //! removed or answering differently drops the kept transcripts of the bodies the real run is inside (up to a boundary) //! and asks for the frame's discard pass, so a change shows in its frame. +//! +//! A measuring run can run as a draft (`draft`): its caller sees its result before it hands anything forward for good, +//! and a draft taken back leaves the pass as it found it. use crate::runtime::egui::sizing; use crate::runtime::frame::{self, PerViewport}; @@ -81,8 +84,14 @@ pub(crate) trait Contribution: Send + Sync { /// What the contribution reports: its target and kind by id, and its value. A real run's contributions are /// compared with the transcript's by these. `None` for a report only a measuring run makes. fn report(&self) -> Option<(Id, f32)>; + + /// What takes the contribution back, read before it is made: a [`draft`] that is taken back runs it. + fn undo(&self, ctx: &Context) -> TakeBack; } +/// Restores what a contribution changed in its aggregator ([`Contribution::undo`]). +pub(crate) type TakeBack = Box; + /// 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. @@ -153,6 +162,31 @@ struct Kept { touched: u64, } +/// A measuring run whose hand-forwards can be taken back ([`draft`]), and what restores the pass to how it was before it. +struct Draft { + /// How many entries `measuring` had open when the draft began: the ones below are outside it. + floor: usize, + /// The innermost transcript outside the draft, by its place in `measuring`, and how many items it held then. + items: Option<(usize, usize)>, + /// What the run changed, in order; taken back in reverse. + undo: Vec, +} + +/// One change a draft made outside itself, with what was there before. +enum Undo { + /// The record under the id, before the draft's emit replaced it. + Record(Id, Option), + /// The body's kept and served transcripts, before the draft's run of the body replaced them. + Kept(Id, Option, Option>), + /// The draft added an alias to the body's kept transcript. + Alias(Id), + /// A component's entry in the transcript open at the place, before the draft added to it. + Leaf(usize, Id, Option), + /// An input the entry open at the place read, before the draft read it. + Input(usize, Id, Option), + Contribution(TakeBack), +} + impl Scope { fn boundary() -> Scope { Scope { body: None, boundary: true, served: None, fresh: None, visited: HashSet::new(), fills: HashSet::new(), reported: Vec::new() } @@ -170,7 +204,7 @@ enum Open { inputs: Inputs, }, Boundary, - /// A run that asks a question of content and leaves nothing behind (`probing`). + /// A run that asks a question of content and reads nothing the pass found outside it (`probing`). Probe, /// `inputs`: what the measure read outside its own room. Call { @@ -205,6 +239,8 @@ pub(crate) struct Entries { /// The kept calls a real run asks again, as the transcript, the component and the call's index, innermost last: /// `read_input` gives what they read. replaying: Vec<(Arc, Id, usize)>, + /// The drafts open, innermost last. + drafts: Vec, ask: bool, asked: Option, } @@ -244,11 +280,98 @@ impl Entries { } } - fn leaf(&mut self) -> Option<&mut HashMap> { - match self.transcript() { - Some(Open::Body { leaves, .. }) => Some(leaves), - _ => None, + /// Where the innermost open transcript sits in `measuring`. + fn transcript_at(&self) -> Option { + self.measuring.iter().rposition(|open| !matches!(open, Open::Call { .. })) + } + + /// The component entry `id` of the innermost open body's transcript, to add to: a draft that holds no such body + /// notes what it was. + fn leaf(&mut self, id: Id) -> Option<&mut Leaf> { + let at = self.transcript_at()?; + let outside = self.drafts.last().is_some_and(|draft| at < draft.floor); + let Open::Body { leaves, .. } = &mut self.measuring[at] else { return None }; + if outside && let Some(draft) = self.drafts.last_mut() { + draft.undo.push(Undo::Leaf(at, id, leaves.get(&id).cloned())); } + Some(leaves.entry(id).or_default()) + } + + /// Keeps a draft that ended: its changes stand, and an open draft around it takes them back with its own. The + /// outermost one finds the records it replaced from a kept transcript at the same room changed, as each emit + /// outside a draft does. + fn keep(&mut self, draft: Draft, frame: u64, pass: u64, tolerance: f32) { + if let Some(outer) = self.drafts.last_mut() { + let floor = outer.floor; + outer.undo.extend(draft.undo.into_iter().filter(|undo| match undo { + Undo::Leaf(at, ..) | Undo::Input(at, ..) => *at < floor, + _ => true, + })); + return; + } + let changed: Vec = draft + .undo + .iter() + .filter_map(|undo| match undo { + Undo::Record(id, Some(last)) => kept_differs(last, &self.measured.get(id)?.recorded, pass, tolerance), + _ => None, + }) + .collect(); + for from in changed { + self.changed(frame, Some(from)); + } + } + + /// Takes a draft that ended back: the records, kept transcripts and transcript entries are as before it. Returns + /// what takes its contributions back, in reverse order, to run outside the memory's lock. + fn take_back(&mut self, draft: Draft) -> Vec { + let mut later = Vec::new(); + for undo in draft.undo.into_iter().rev() { + match undo { + Undo::Record(id, last) => match last { + Some(found) => drop(self.measured.insert(id, found)), + None => drop(self.measured.remove(&id)), + }, + Undo::Kept(body, kept, served) => { + match kept { + Some(kept) => drop(self.kept.insert(body, kept)), + None => drop(self.kept.remove(&body)), + } + match served { + Some(served) => drop(self.served.insert(body, served)), + None => drop(self.served.remove(&body)), + } + } + Undo::Alias(body) => { + if let Some(kept) = self.kept.get_mut(&body) { + kept.aliases.pop(); + } + } + Undo::Leaf(at, id, leaf) => { + if let Some(Open::Body { leaves, .. }) = self.measuring.get_mut(at) { + match leaf { + Some(leaf) => drop(leaves.insert(id, leaf)), + None => drop(leaves.remove(&id)), + } + } + } + Undo::Input(at, key, value) => { + if let Some(Open::Body { inputs, .. } | Open::Call { inputs }) = self.measuring.get_mut(at) { + match value { + Some(value) => drop(inputs.insert(key, value)), + None => drop(inputs.remove(&key)), + } + } + } + Undo::Contribution(undo) => later.push(undo), + } + } + if let Some((at, len)) = draft.items + && let Some(Open::Body { items, .. }) = self.measuring.get_mut(at) + { + items.truncate(len); + } + later } /// Whether a probe is open (`probing`). @@ -374,9 +497,6 @@ fn emit(ctx: &Context, id: Id, mut recorded: Recorded) { let pass = ctx.cumulative_pass_nr(); let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ctx)); with(ctx, &moment, |memory| { - if memory.probing() { - return; - } // 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 @@ -390,27 +510,36 @@ fn emit(ctx: &Context, id: Id, mut recorded: Recorded) { .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 - && 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 {recorded:?}, its kept record said {was:?}"); - } + // A draft finds a change when it is kept, against the record it replaced. + if let Some(draft) = memory.drafts.last_mut() { + draft.undo.push(Undo::Record(id, last)); + } else if let Some(from) = last.and_then(|last| kept_differs(&last, &recorded, pass, tolerance)) { memory.changed(moment.frame, Some(from)); } memory.push(Item::Record(id, recorded)); }); } +/// The body whose kept transcript gave `last` to this pass, when a run of the pass found, at the same room and inputs, +/// something else (`now`): that transcript changed. +fn kept_differs(last: &Found, now: &Recorded, pass: u64, tolerance: f32) -> Option { + let Found { pass: at, recorded: was, kept: Some(from) } = last else { return None }; + let differs = match (was, now) { + (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, + }; + if *at != pass || !differs { + return None; + } + #[cfg(feature = "testing")] + if std::env::var_os("CRAFT_UI_TRACE_KEPT").is_some() { + eprintln!("layout memory: a run of this pass found {now:?}, the kept record of {from:?} said {was:?}"); + } + Some(*from) +} + /// How many bodies and measure calls a measuring run has open: an aggregator opened now hands [`read_input`] this /// depth, so only the bodies and calls opened inside it count what they read from it as an input. pub(crate) fn depth(ctx: &Context) -> usize { @@ -435,10 +564,14 @@ pub(crate) fn read_input(ctx: &Context, from: usize, key: Id, value: f32) -> f32 if let Some(read) = replayed { return *read; } - // A probe's content reads nothing on behalf of the runs outside it. - let from = memory.measuring.iter().rposition(|open| matches!(open, Open::Probe)).map_or(from, |at| from.max(at + 1)); - for open in memory.measuring.iter_mut().skip(from) { + let floor = memory.drafts.last().map_or(0, |draft| draft.floor); + for (at, open) in memory.measuring.iter_mut().enumerate().skip(from) { if let Open::Body { inputs, .. } | Open::Call { inputs } = open { + if at < floor + && let Some(draft) = memory.drafts.last_mut() + { + draft.undo.push(Undo::Input(at, key, inputs.get(&key).copied())); + } let read = inputs.entry(key).or_insert(value); *read = read.max(value); } @@ -482,13 +615,19 @@ fn fingerprint(inputs: &Inputs) -> u64 { /// real run inside a body a kept transcript serves keeps it to compare with the transcript's. pub(crate) fn contribute(ctx: &Context, contribution: Arc) { let moment = Moment::of(ctx); - if with(ctx, &moment, |memory| memory.probing()) { - return; - } - guard::emitting(|| contribution.apply(ctx)); let measuring = crate::runtime::measure::active(ctx); + let drafting = measuring && with(ctx, &moment, |memory| !memory.drafts.is_empty()); + let undo = drafting.then(|| guard::emitting(|| contribution.undo(ctx))); + guard::emitting(|| contribution.apply(ctx)); + #[cfg(feature = "testing")] + if measuring { + crate::runtime::measure::count_contribution(ctx, 1); + } with(ctx, &moment, |memory| { if measuring { + if let (Some(undo), Some(draft)) = (undo, memory.drafts.last_mut()) { + draft.undo.push(Undo::Contribution(undo)); + } memory.push(Item::Contribute(contribution)); } else if let (Some(scope), Some(report)) = (memory.checking(), contribution.report()) { scope.reported.push(report); @@ -496,6 +635,41 @@ pub(crate) fn contribute(ctx: &Context, contribution: Arc) { }); } +/// Runs the measuring run `run` as a draft: everything it hands forward (records, kept transcripts, what it adds to the +/// transcript open around it, contributions) can be taken back. `keep` decides from its result. Kept, the run stands as +/// if it had run plainly; taken back, the pass is as it was before the run, so a run that follows replaces it (a body +/// that fills measured at its content height, then laid out at its room) or none does (a run that only asks). Returns +/// the result and whether it was kept. +pub(crate) fn draft(ctx: &Context, run: impl FnOnce() -> R, keep: impl FnOnce(&R) -> bool) -> (R, bool) { + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| { + let floor = memory.measuring.len(); + let items = memory.transcript_at().and_then(|at| match &memory.measuring[at] { + Open::Body { items, .. } => Some((at, items.len())), + _ => None, + }); + memory.drafts.push(Draft { floor, items, undo: Vec::new() }); + }); + let out = run(); + let kept = keep(&out); + let pass = ctx.cumulative_pass_nr(); + let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ctx)); + let undo = with(ctx, &moment, |memory| { + let draft = memory.drafts.pop()?; + if kept { + memory.keep(draft, moment.frame, pass, tolerance); + return None; + } + Some(memory.take_back(draft)) + }); + for undo in undo.into_iter().flatten() { + guard::emitting(|| undo(ctx)); + #[cfg(feature = "testing")] + crate::runtime::measure::count_contribution(ctx, -1); + } + (out, kept) +} + /// Runs `f` as content whose emits no enclosing transcript takes, and whose real run no enclosing body checks: a /// collection's rows and its widest-row probe (measured every pass by the collection), a layer's content, a lazy /// child. `stops_changes`: a change the real run finds inside drops no kept transcript outside. Content whose extent @@ -524,13 +698,13 @@ pub(crate) fn boundary(ctx: &Context, stops_changes: bool, f: impl FnOnce() - } /// Runs `f`, a measuring run that asks a question of content (the least width of a row's body unit), as a probe: it -/// reads no record or kept transcript, so every body inside measures its content, and it leaves nothing behind (no -/// record, text, transcript, contribution or input of a run outside it). The runs of the pass outside it find what -/// they would without it. +/// reads no record or kept transcript, so every body inside measures its content, and it runs as a [`draft`] taken +/// back, so it leaves nothing behind (no record, text, transcript, contribution or input of a run outside it). The runs +/// of the pass outside it find what they would without it. pub(crate) fn probing(ctx: &Context, f: impl FnOnce() -> R) -> R { let moment = Moment::of(ctx); with(ctx, &moment, |memory| memory.measuring.push(Open::Probe)); - let out = f(); + let (out, _) = draft(ctx, f, |_| false); with(ctx, &moment, |memory| { if let Some(at) = memory.measuring.iter().rposition(|open| matches!(open, Open::Probe)) { memory.measuring.remove(at); @@ -548,8 +722,8 @@ pub(crate) fn leaf_call(ctx: &Context, id: Id, calls: &mut [Call], ask: impl FnM let moment = Moment::of(ctx); if !real(ctx) { with(ctx, &moment, |memory| { - if let Some(leaves) = memory.leaf() { - let kept = &mut leaves.entry(id).or_default().calls; + if let Some(leaf) = memory.leaf(id) { + let kept = &mut leaf.calls; for call in calls { if !kept.iter().any(|kept| kept.proposal == call.proposal && kept.room == call.room) { let inputs = std::mem::take(&mut call.inputs); @@ -613,10 +787,11 @@ pub(crate) fn leaf_fill(ctx: &Context, id: Id, body: Id, axis: Axis) { let measuring = !real(ctx); let same = with(ctx, &moment, |memory| { if measuring { - if let Some(Open::Body { id: open, leaves, .. }) = memory.transcript() + if let Some(Open::Body { id: open, .. }) = memory.transcript() && *open == body + && let Some(leaf) = memory.leaf(id) { - leaves.entry(id).or_default().fill = Some(axis); + leaf.fill = Some(axis); } return true; } @@ -682,13 +857,14 @@ pub(crate) fn end_measure(ctx: &Context, b with(ctx, &moment, |memory| { let Some(at) = memory.measuring.iter().rposition(|open| matches!(open, Open::Body { id, .. } if *id == body)) else { return }; let Open::Body { items, leaves, .. } = memory.measuring.remove(at) else { return }; - if memory.probing() { - return; - } let transcript = Arc::new(Transcript { key: Box::new(key), items, leaves, real: Mutex::new(None) }); - memory.served.remove(&body); - let moved = memory.kept.remove(&body).and_then(|last| last.moved); + let served = memory.served.remove(&body); + let last = memory.kept.remove(&body); + let moved = last.as_ref().and_then(|last| last.moved); memory.kept.insert(body, Kept { transcript: transcript.clone(), aliases: Vec::new(), valid: true, moved, touched: moment.frame }); + if let Some(draft) = memory.drafts.last_mut() { + draft.undo.push(Undo::Kept(body, last, served)); + } memory.push(Item::Body(body, transcript)); }); } @@ -705,6 +881,9 @@ pub(crate) fn kept_also_under(ctx: &Contex let known = kept.transcript.key.downcast_ref::() == Some(&key) || kept.aliases.iter().any(|alias| alias.downcast_ref::() == Some(&key)); if !known && kept.aliases.len() < 2 { kept.aliases.push(Box::new(key)); + if let Some(draft) = memory.drafts.last_mut() { + draft.undo.push(Undo::Alias(body)); + } } }); } @@ -914,6 +1093,7 @@ pub(crate) fn end_hook(ctx: &Context) { memory.measured.clear(); memory.served.clear(); memory.measuring.clear(); + memory.drafts.clear(); memory.scopes.clear(); memory.replaying.clear(); (wanted, ask) diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 98522a002..07f4b402c 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -26,6 +26,14 @@ struct BodyRuns { runs: Vec<(Id, u32)>, } +/// How many contributions the measuring runs of a pass made that stand, with the pass that counted them. +#[cfg(feature = "testing")] +#[derive(Default)] +struct Contributions { + pass: u64, + count: i64, +} + /// The runs of each component type, with the pass that counted them. #[cfg(feature = "testing")] #[derive(Default)] @@ -139,6 +147,25 @@ pub(crate) fn count_body(ctx: &Context, id: Id) { }); } +/// Counts a contribution a measuring run made in this pass (`delta` 1), or a draft took back (-1). +#[cfg(feature = "testing")] +pub(crate) fn count_contribution(ctx: &Context, delta: i64) { + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = Contributions { pass, count: 0 }; + } + log.count += delta; + }); +} + +/// How many contributions the measuring runs made that stand, in the last pass whose runs made any: a draft that was +/// taken back counts none. +#[cfg(feature = "testing")] +pub fn contributions(ctx: &Context) -> i64 { + store::with::(ctx, |log| log.count) +} + /// The bodies whose contents ran in a measuring run in the last pass, and how many runs each; empty when that pass /// ran none. #[cfg(feature = "testing")] diff --git a/crates/ui-contract/src/runtime/reads.rs b/crates/ui-contract/src/runtime/reads.rs index 565d758d7..de892c795 100644 --- a/crates/ui-contract/src/runtime/reads.rs +++ b/crates/ui-contract/src/runtime/reads.rs @@ -122,6 +122,11 @@ impl Contribution for MeasuredRead { fn report(&self) -> Option<(Id, f32)> { None } + + fn undo(&self, ctx: &Context) -> layout_memory::TakeBack { + let made = with(ctx, |reads| reads.reads.len()); + Box::new(move |ctx| with(ctx, |reads| reads.reads.truncate(made))) + } } /// The reads of a binding made so far in this pass, as an edit of it by one component sees them. diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 4a4f4eb32..46cb842d1 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -38,8 +38,8 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ - active as is_measuring, body_runs as measuring_runs, last_pass_body_runs as last_pass_measuring_runs, last_pass_runs, - least_runs as shrink_least_runs, run as measuring_run, take_effects, widest_runs, + active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_pass_body_runs as last_pass_measuring_runs, + last_pass_runs, least_runs as shrink_least_runs, run as measuring_run, take_effects, widest_runs, }; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; diff --git a/crates/ui-gallery/src/chrome/card.rs b/crates/ui-gallery/src/chrome/card.rs index afec48900..fcd2c9ca7 100644 --- a/crates/ui-gallery/src/chrome/card.rs +++ b/crates/ui-gallery/src/chrome/card.rs @@ -87,8 +87,8 @@ pub struct Card<'a> { pub layout: StoryLayout, /// The surface the stories sit on. pub surface: Surface, - /// The height a story that fills is given: the visible height of the view the cards scroll in, as the old - /// gallery's tiles gave it. + /// The most a story that fills takes, at its content height below that: the visible height of the view the cards + /// scroll in, as the old gallery's tiles gave it. pub room: f32, /// Whether the header has Open. pub open: bool, @@ -242,7 +242,7 @@ pub struct StoryBody { pub story: &'static StoryRegistration, /// The surface the story sits on. pub surface: Surface, - /// The height a story that fills is given. + /// The most a story that fills takes. pub room: f32, /// The values the body sets for its story. pub look: Look, @@ -376,7 +376,7 @@ fn close_at_start(state: &mut CardState) { struct Host<'a> { caption: Option<&'a str>, id: Id, - /// The height a story that fills is given. + /// The most a story that fills takes. room: f32, look: Look, surface: Surface, diff --git a/crates/ui-gallery/src/chrome/overview.rs b/crates/ui-gallery/src/chrome/overview.rs index 089f9419f..7948b03a0 100644 --- a/crates/ui-gallery/src/chrome/overview.rs +++ b/crates/ui-gallery/src/chrome/overview.rs @@ -93,7 +93,7 @@ impl Spec { } /// The card of this spec, with `stories` from [`Spec::card_stories`], `key` as its id scope and `room` as the - /// height a filling story gets. + /// most a filling story takes. pub fn card<'a>(&'a self, stories: &'a [CardStory<'a>], key: String, room: f32) -> Card<'a> { Card { key, @@ -159,7 +159,7 @@ pub(super) fn grid( let mut reported = Vec::new(); let columns = if one_column || ui.available_width() < 2.0 * CARD_MIN_WIDTH { 1 } else { 2 }; let generation = p.generation; - // A story that fills its room gets the view's height, as on the old gallery's tiles. + // A story that fills takes its content height, at most the view's, as on the old gallery's tiles. let room = ui.available_height(); Stack::new().fill().scroll(Scroll::vertical()).gap(Gap::CardRow).id_salt(scroll_id).show(ui, |ui, _| { reported.clear(); diff --git a/crates/ui-gallery/tests/it/overview.rs b/crates/ui-gallery/tests/it/overview.rs index 4f76849e4..cf6ae951c 100644 --- a/crates/ui-gallery/tests/it/overview.rs +++ b/crates/ui-gallery/tests/it/overview.rs @@ -311,3 +311,26 @@ fn a_card_shows_its_storys_readout_under_the_story_and_follows_it() { let (after, _) = readout(&fixture).expect("the readout stays"); assert!(after.starts_with("Last event: "), "the readout names the click's event: {after}"); } + +/// The height of the Overview card of the component listed as `name` in a window `height` tall. +fn card_height(name: &str, height: f32) -> f32 { + let mut gallery = gallery_filtered(level_of(name), name); + let mut fixture = Fixture::new(move |ui| gallery.ui(ui)); + fixture.room(Vec2::new(1400.0, height)).settle(); + let card = fixture + .by_role(Role::GROUP) + .into_iter() + .find(|group| fixture.tree().name_of(group.node) == Some(name)) + .unwrap_or_else(|| panic!("{name}'s card shows")); + card.rect.height() +} + +/// A card whose story fills and scrolls is as tall as the story's content while the content fits the room, as the old +/// gallery's tiles were: a taller window gives the card no empty space. Regression: a list or panel story took the +/// whole height of the view. +#[trial] +fn a_card_of_a_filling_story_is_as_tall_as_its_content() { + let (short, tall) = (card_height("LayersPanel", 900.0), card_height("LayersPanel", 1400.0)); + assert!(short < 900.0, "the card fits the window: {short}"); + assert!((tall - short).abs() < 1.0, "the card keeps its content's height in a taller window: {short} -> {tall}"); +} diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index 780d76dda..d3de37c1a 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -264,7 +264,7 @@ pub struct AppShell<'a, S> { window: WindowKey, bare: bool, embedded: bool, - /// An embedded shell as tall as its content, with the room a body that fills is given. + /// An embedded shell as tall as its content, with the most a body that fills takes. content_room: Option, /// The screen mode. Without a binding the shell keeps it, starting at `Standard`. #[prop] @@ -321,7 +321,7 @@ impl<'a, S> AppShell<'a, S> { } /// An embedded shell as wide as the room of the flow it is shown in and as tall as its body's content and its top - /// and bottom slots, from the measure its body keeps while its inputs hold; a body that fills is given `room`. + /// and bottom slots, from the measure its body keeps while its inputs hold; a body that fills takes at most `room`. /// Shown with [`show`](Self::show), it takes that room in the flow. pub fn content_height(self, room: f32) -> Self { AppShell { embedded: true, content_room: Some(room), ..self } diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index 894993820..9b2bb43bd 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -100,9 +100,9 @@ macro_rules! layout_component { self } - /// Offers the children `height` of room, also inside a scrolling body: a child that fills the height takes - /// it, any other child its content height, and the container takes what they took. For a host that shows - /// content of either kind at a definite room, such as a story preview. + /// Offers the children `height` of room, also inside a scrolling body: every child takes its content + /// height, a child that fills or scrolls at most `height`, and the container takes what they took. For a + /// host that shows content of either kind at a definite room, such as a story preview. pub fn room_height(mut self, height: f32) -> Self { self.props = self.props.room_height(height); self diff --git a/crates/ui-widgets/tests/it/layout/room_height.rs b/crates/ui-widgets/tests/it/layout/room_height.rs index e6144650a..e88d31c8b 100644 --- a/crates/ui-widgets/tests/it/layout/room_height.rs +++ b/crates/ui-widgets/tests/it/layout/room_height.rs @@ -1,43 +1,183 @@ -//! A content-sized host with a room height, inside a scrolling body, gives a child that fills that room in the -//! measuring run and in the real run, and a content child its content height. +//! A content-sized host with a room height, inside a scrolling body, offers its children that height as the most they +//! take: a child that fills takes its content height while the content fits, and a scrolling child whose content is +//! taller takes the room, in the measuring run and in the real run. A filling panel whose content outgrows the room +//! takes the room and shares it between its list and the bar under it. +use craft_behavior::{DisplayOrder, ItemSource}; use craft_ui::buttons::Button; -use craft_ui::contract::{Scroll, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _}; use craft_ui::layout_components::Stack; -use craft_ui::testing::{Fixture, trial}; -use egui::{Rect, Vec2}; +use craft_ui::list::{List, ListRow}; +use craft_ui::testing::{Fixture, forget_measurements, last_pass_measuring_runs, measured_contributions, trial}; +use craft_ui::value_drag::Slider; +use egui::{Rect, Ui, Vec2}; use std::cell::Cell; use std::rc::Rc; const TOLERANCE: f32 = 0.5; #[trial] -fn a_fill_child_takes_the_hosts_room_height_inside_a_scroll() { +fn a_room_height_is_the_most_a_filling_child_takes_inside_a_scroll() { const ROOM: Vec2 = Vec2::new(400.0, 300.0); - // The rects of the fill host, its fill child, the content host and its button, from the last real run. + // The rects of the short host, its fill child, the tall host and its scrolling child, from the last real run. let seen = Rc::new(Cell::new([Rect::NOTHING; 4])); let out = Rc::clone(&seen); let mut fixture = Fixture::new(move |ui| { let room = ui.available_height() / 2.0; Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { - let filled = Stack::new() + let short = Stack::new() .fill_width() .room_height(room) .show(ui, |ui, _| Stack::new().fill().show(ui, |ui, _| Button::new("Inside").show(ui)).output.rect); - let content = Stack::new().fill_width().room_height(room).show(ui, |ui, _| Button::new("Content").show(ui).response.rect); + let tall = Stack::new().fill_width().room_height(room).show(ui, |ui, _| { + Stack::new() + .fill() + .scroll(Scroll::vertical()) + .show(ui, |ui, _| { + for row in 0..40 { + Button::new(format!("Row {row}")).show(ui); + } + }) + .output + .rect + }); if !ui.is_sizing_pass() - && let (Some(fill), Some(button)) = (filled.inner, content.inner) + && let (Some(fill), Some(list)) = (short.inner, tall.inner) { - out.set([filled.output.rect, fill, content.output.rect, button]); + out.set([short.output.rect, fill, tall.output.rect, list]); } }); }); fixture.room(ROOM).settle(); - let [host, fill, content, button] = seen.get(); - let dump = format!("host {host:?}, fill {fill:?}, content {content:?}, button {button:?}"); - assert!(fill.height().is_finite() && fill.height() > 0.0, "the fill child has a finite room: {dump}"); - assert!((fill.height() - host.height()).abs() <= TOLERANCE, "the host is as tall as its fill child: {dump}"); - assert!(fill.height() < ROOM.y, "the fill child takes the room height, not the scroll's unbounded room: {dump}"); - assert!(content.height() < host.height(), "a content child takes its content height: {dump}"); - assert!(content.contains_rect(button.shrink(TOLERANCE)), "the content host holds its child: {dump}"); + let [short, fill, tall, list] = seen.get(); + let dump = format!("short {short:?}, fill {fill:?}, tall {tall:?}, list {list:?}"); + assert!(fill.height() > 0.0, "the fill child shows: {dump}"); + assert!((fill.height() - short.height()).abs() <= TOLERANCE, "the host is as tall as its fill child: {dump}"); + assert!(list.height().is_finite() && list.height() < ROOM.y, "the scrolling child stops at the room, not the scroll's unbounded room: {dump}"); + assert!(fill.height() < list.height(), "a fill child whose content fits takes its content height, less than the room: {dump}"); + assert!((tall.height() - list.height()).abs() <= TOLERANCE, "the tall host is as tall as its scrolling child: {dump}"); +} + +/// How a filling panel holds the bar under its list, and what the list is. +#[derive(Clone, Copy)] +enum Bar { + /// The bar is the panel's footer region. + Footer, + /// The bar is the list's sibling in the panel's body. + Sibling, + /// The bar is the panel's footer region, under a list collection. + CollectionFooter, +} + +/// The rows of a list collection. +struct Rows(usize); + +impl DisplayOrder for Rows { + fn len(&self) -> usize { + self.0 + } + + fn key(&self, at: usize) -> usize { + at + } +} + +impl ItemSource for Rows {} + +/// A host with a room height holding a panel that fills: a scrolling list of `rows` and a bar holding a bound, labelled +/// slider. Returns the rects of the host, the list and the bar from the real run. +fn panel(ui: &mut Ui, room: f32, rows: usize, bar: Bar, value: &mut f64) -> Option<[Rect; 3]> { + let list = |ui: &mut Ui| { + if let Bar::CollectionFooter = bar { + return List::new("Rows").show_items(ui, &Rows(rows), &mut |key, _| ListRow::new(format!("Row {key}"))).response.rect; + } + Stack::new() + .fill() + .scroll(Scroll::vertical()) + .show(ui, |ui, _| { + for row in 0..rows { + Button::new(format!("Row {row}")).show(ui); + } + }) + .output + .rect + }; + let host = Stack::new().fill_width().room_height(room).show(ui, |ui, _| { + let mut bar_rect = Rect::NOTHING; + let shown = match bar { + Bar::Footer | Bar::CollectionFooter => Stack::new() + .fill() + .footer(|ui, _| bar_rect = Slider::new(Bind::bound(&mut *value), 0.0..=100.0).label("Opacity").show(ui).response.rect) + .show(ui, |ui, _| list(ui)), + Bar::Sibling => Stack::new().fill().show(ui, |ui, _| { + let list = list(ui); + bar_rect = Slider::new(Bind::bound(&mut *value), 0.0..=100.0).label("Opacity").show(ui).response.rect; + list + }), + }; + shown.inner.map(|list| (list, bar_rect)) + }); + let (list, bar) = host.inner.flatten()?; + (!ui.is_sizing_pass()).then_some([host.output.rect, list, bar]) +} + +/// A fixture showing [`panel`] at a room height of a third of the window, and the rects of its last real run. +fn panel_fixture(rows: usize, bar: Bar) -> (Fixture, Rc>) { + let seen = Rc::new(Cell::new([Rect::NOTHING; 3])); + let out = Rc::clone(&seen); + let mut value = 40.0_f64; + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_height() / 3.0; + Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { + if let Some(rects) = panel(ui, room, rows, bar, &mut value) { + out.set(rects); + } + }); + }); + fixture.room(Vec2::new(400.0, 600.0)).settle(); + (fixture, seen) +} + +/// Regression: a filling panel in a room height whose list outgrew the room took the list's whole content height, so the +/// bar under the list sat over its last rows; and a list collection under a panel sized from its content took the whole +/// room in the real run, over the footer. The list takes what the bar leaves, whether the panel fits its room or takes it. +#[trial] +fn a_filling_panel_keeps_the_bar_under_its_list() { + for (rows, bar) in [(40, Bar::Footer), (40, Bar::Sibling), (40, Bar::CollectionFooter), (3, Bar::CollectionFooter)] { + let (_, seen) = panel_fixture(rows, bar); + let [host, list, bar] = seen.get(); + let dump = format!("host {host:?}, list {list:?}, bar {bar:?}"); + assert!(host.height() <= 200.0 + TOLERANCE, "the host stops at its room height: {dump}"); + assert!(bar.top() >= list.bottom() - TOLERANCE, "the bar lies under the list, not over its rows: {dump}"); + assert!(host.contains_rect(bar.shrink(TOLERANCE)), "the host holds the bar: {dump}"); + } +} + +/// A filling panel laid out at its room because its content is taller runs no measuring run in a settled frame: its +/// kept measurement holds the layout at the room. +#[trial] +fn a_settled_filling_panel_taller_than_its_room_runs_no_measuring_run() { + for bar in [Bar::Footer, Bar::Sibling] { + let (mut fixture, _) = panel_fixture(40, bar); + fixture.idle(1); + let runs = last_pass_measuring_runs(fixture.ctx()); + assert!(runs.is_empty(), "a settled pass measured {} bodies: {runs:?}", runs.len()); + } +} + +/// A filling panel taller than its room is measured at its content height and then laid out at the room: what the first +/// run handed forward is taken back, so the pass gets each contribution (the slider's least width for its label, its +/// read of the bound value) once, as from the same panel when it fits. +#[trial] +fn a_filling_panel_taller_than_its_room_hands_each_contribution_forward_once() { + let made = |rows: usize| { + let (mut fixture, seen) = panel_fixture(rows, Bar::Footer); + forget_measurements(fixture.ctx()); + fixture.frame(Vec::new()); + (measured_contributions(fixture.ctx()), seen.get()[0].height()) + }; + let ((fits, short), (over, tall)) = (made(2), made(40)); + assert!(short < tall && tall <= 200.0 + TOLERANCE, "the short panel fits its room and the long one fills it: {short}, {tall}"); + assert!(fits > 0, "the panel's measuring run hands contributions forward"); + assert_eq!(over, fits, "the panel taller than its room hands forward as many contributions as one that fits"); } diff --git a/docs/craft-framework.md b/docs/craft-framework.md index 85501e800..a4ea76aff 100644 --- a/docs/craft-framework.md +++ b/docs/craft-framework.md @@ -536,6 +536,8 @@ This section points to the component index. Examples and every state of each com A content-sized column (a `Stack::new()`, a menu or popover body) holds the children that fill: they never set the column's width, and they are shown across the width it settles on. A leaf declares that it fills with `fills()`; a container declares it with `Sizing`. A host that shows arbitrary components (the gallery, a dialog body) offers them fill width with `fill_width()`, and a story that fills both axes takes its room from `testing::stage`, and a canvas story as tall as its content (a text being edited) from `testing::stage_fitting`. +Along a height its parent sizes from its content, a container that fills takes its content height, at most the room it is offered. Content taller than that room takes the room, and the children that fill share it, so a list scrolls above the bar under it. Inside a scrolling body the room is unbounded; a host offers a finite one with `room_height` (a gallery card offers the view's height). + ### 6.2 Index [components-index.md](components-index.md) lists every registered component and pattern of the UI library crates with its shape, module and purpose. It is generated from the component registry (`cl cargo run -p craft-ui-gallery --bin components-index`), and the facade's `components_index` trial fails when the file is out of date. [contract-api.md](contract-api.md) lists the public items of the shared modules (`contract`, `runtime`, `style`, `primitives`, `layout`, `layout_components`, `testing`) and of `craft-behavior`.