diff --git a/crates/ui-contract/src/contract/collection/props.rs b/crates/ui-contract/src/contract/collection/props.rs index 081ae575b..3c464e0b4 100644 --- a/crates/ui-contract/src/contract/collection/props.rs +++ b/crates/ui-contract/src/contract/collection/props.rs @@ -595,26 +595,27 @@ impl CollectionProps { } } -/// What an item reads of its place in the collection; the item step joins it to the item's flags at step 12. +/// What an item reads of its place in the collection; the item step joins it to the item's flags at step 12. The +/// fields marked "Measured" are the ones an auto row's measure reads (the row-hook contract on `ItemCx`). #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct RowState { - /// The row is selected. + /// The row is selected. Measured. pub selected: bool, - /// The row holds the lead. + /// The row holds the lead. Measured. pub lead: bool, /// A drag would drop on the row. pub drop_target: bool, /// The row is being dragged. pub dragging: bool, - /// The row's name is being edited. + /// The row's name is being edited. Measured. pub renaming: bool, /// The app marks the row. pub emphasized: bool, - /// The collection's current item (`CollectionProps::current`). + /// The collection's current item (`CollectionProps::current`). Measured. pub current: bool, - /// An odd row of a striped list. + /// An odd row of a striped list. Measured. pub striped: bool, - /// A tree row whose children show. + /// A tree row whose children show. Measured. pub open: bool, /// The pointer is over the row and a press there would reach it. pub hovered: bool, @@ -627,11 +628,11 @@ pub struct RowState { /// button shown. pub menu_open: bool, /// `Some(steps)` for a sub-row of a row above (`ItemSource::sub_row`): compact, its toggles `steps` indent steps - /// into its content. + /// into its content. Measured. pub sub_row: Option, - /// The next row is a sub-row, which continues this row: no divider between them. + /// The next row is a sub-row, which continues this row: no divider between them. Measured. pub continued: bool, - /// The row is the collection's last: dividers fall between rows, so none under it. + /// The row is the collection's last: dividers fall between rows, so none under it. Measured. pub last: bool, /// The activation key (Enter) activated the row this pass: a row with controls of its own may move focus into one. pub activated_by_key: bool, diff --git a/crates/ui-contract/src/contract/cx/item.rs b/crates/ui-contract/src/contract/cx/item.rs index 3d4ccfe7a..c36fb5460 100644 --- a/crates/ui-contract/src/contract/cx/item.rs +++ b/crates/ui-contract/src/contract/cx/item.rs @@ -17,6 +17,16 @@ pub struct ItemOpener { } /// What the item closure reads for one item: a view over the pipeline's memory stage keyed by the item. +/// +/// The row-hook contract. The collection measures an auto row (auto height or auto widths) at step 5, before it +/// places its rows, from the item this closure and `Collection::dress` make with the row state known before the pass +/// senses input: the `RowState` fields marked "measured" as step 4 read them, the depth and the set position, under +/// the collection's env. The size of an auto row depends only on those. It must not depend on app values the body +/// adds at step 13, the surface, focus, or the pointer and gesture state (`hovered`, `pointer_over`, `pressed`, +/// `dragging`, `drop_target`, `menu_open`, `activated_by_key`): only the build that shows the row has them. A row +/// whose measured state this pass's input changes (a click that selects it, a press that starts its rename) is +/// measured again when it is built; a size other than the one the pass placed it by makes the pass run again, so +/// the frame shows the row at its new size. #[non_exhaustive] pub struct ItemCx<'a, 'r, K> { /// The item's key. diff --git a/crates/ui-contract/src/contract/items.rs b/crates/ui-contract/src/contract/items.rs index d2ce1b11e..35820e864 100644 --- a/crates/ui-contract/src/contract/items.rs +++ b/crates/ui-contract/src/contract/items.rs @@ -181,6 +181,10 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { /// The bound column layout as the read step found it; `None` while the header keeps its own memory. column_layout_at_read: Option, lead: Lead, + /// The lead row and the renaming row as step 4 read them: a row's measure at step 5 reads them + /// (`known_row`). + lead_at_read: Option, + renaming_at_read: Option, renaming: Renaming, ended_rename: bool, /// The editor of the rename that ended still held focus, so focus goes back to the collection. @@ -193,8 +197,6 @@ pub(super) struct ItemsHooks<'s, 'r, C: Collection> { page_reveal: Option, /// The row this pass scrolls into view, placed before the rows are built (`place_reveal`). revealing: Option, - /// The rows `place_reveal` built and measured this pass: the build places them by that measure. - measured_for_reveal: Vec, /// The row the collection's own press is held on this pass, and where on it. pressed: Option<(usize, crate::contract::collection::RowPressed)>, /// The rows above and below the edge-press band declared this pass. @@ -258,7 +260,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { drags: Drags::default(), page_reveal: None, revealing: None, - measured_for_reveal: Vec::new(), + lead_at_read: None, + renaming_at_read: None, pressed: None, edge: None, } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 8512b47b0..7f0c8efd0 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -15,13 +15,13 @@ use crate::contract::run::{Measuring, ShapeHooks, ShowAt}; use crate::contract::steps::ShapeKind; use crate::contract::{Bind, Collection, Cx, Internal, ItemCx, ItemOutput as _, PartsCx, Props, Show as _, Sizing}; use crate::primitives::{HiddenContent, ScrollBar, SurfaceSlot}; -use crate::runtime::access::{self, Role, SetPosition}; +use crate::runtime::access::{self, Role}; use crate::runtime::egui::{alloc, areas, child, response}; use crate::runtime::env::WheelScope; use crate::runtime::env::{AppValues, ArenaId, Env, ItemFacts, ThemeScope}; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::{focus, keys, layout_memory, lazy, overlay, wheel}; -use crate::style::{ComponentStyle as _, StyleCx, SurfaceKind, UiTokens, scroll_bar_look, surface_style}; +use crate::style::{ComponentStyle as _, SurfaceKind, UiTokens, scroll_bar_look, surface_style}; use craft_behavior::{ Axis, CancelReason, EditEvent, Intent, ItemLayout, Mixed, Proposal, ScrollPos, ScrollSpan, SelectionModel, Sense, WheelRoom, WheelTaker, }; @@ -128,6 +128,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { self.lead.key = self.selection.lead().filter(|key| self.index_of(key).is_some()).cloned(); } self.renaming = stage.session::>(sub(id, "rename")).clone(); + (self.lead_at_read, self.renaming_at_read) = (self.lead.key.clone(), self.renaming.key.clone()); let scrolled = match comp.scroll() { Some(bind) => match bind.get() { Some(Mixed::Same(pos)) => Scrolled { y: pos.y, x: pos.x, anchor: None }, @@ -164,102 +165,13 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { fn measured_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Vec2 { let id = cx.core.id; self.record_largest(comp, at, id); - self.extent(comp, at.ui, at.at, id, at.scx) + self.items_extent(comp, at, id) } fn pass_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, _style: &C::Style, _shown: Option>>) -> Vec2 { let id = at.resolved.id; self.record_largest(comp, at, id); - self.extent(comp, at.ui, at.at, id, at.scx) - } - - fn extent(&mut self, comp: &C, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { - let room = match at { - ShowAt::Rect(rect) => rect.size(), - ShowAt::Flow => crate::layout::flow_room(ui), - }; - self.room = room; - self.indent_step = scx.control().icon; - let env = Env::of(ui); - let room = Self::inner_room(comp, scx.tokens, room); - // Where the enclosing body does not give the width, the collection takes its width from its content, whether - // it fills or fills the width, as a container does. Held in a content-sized column it measures so, and shows - // across the width the column settles on. - let held = env.content_column || crate::layout::in_grid_content_column(ui); - self.from_content = (!env.gives_width() && (crate::runtime::measure::active(ui.ctx()) || !held), env.content.1); - self.header.measure(scx); - self.header.read_content(ui.ctx(), id); - let bounded = room.x.is_finite(); - let item = comp.measures_items().then(|| layout_memory::measured(ui.ctx(), sub(id, "largest")).map(|measured| measured.took)).flatten(); - // Under a body that does not give the width, the measuring run lays the rows out at the width the collection - // asks for, so the height it reports is the one it has at that width (a grid's rows at its columns). - let from_content = self.from_content.0 && !self.content_sized(comp); - let asked = (from_content && !self.source.is_empty()).then(|| self.width_from_content(comp, ui, id, room, item, scx)); - let width = match (bounded, self.content_sized(comp)) { - (true, false) => asked.unwrap_or(room.x), - // No rows: the empty state has no ideal width, so it takes the room, or none where the room is unbounded. - (_, _) if self.source.is_empty() => { - if bounded { - room.x - } else { - 0.0 - } - } - // An unbounded room (a horizontally scrolling body) takes the widest row, as a content-sized collection does. - (_, _) => { - let floor = env.get::().0; - let widest = layout_memory::measured(ui.ctx(), sub(id, "largest")).map_or(0.0, |measured| measured.took.x); - // Columns side by side at their own widths: a `Content` column takes its widest cell, not the share of - // the widest row it would get. - let columns = if self.header.has_columns() { self.header.content_width() } else { 0.0 }; - widest.max(columns).max(comp.ideal_width(item, scx)).max(floor).min(room.x) - } - }; - let previous = self.layout.take().or_else(|| self.previous.take()).map(|held| Arc::try_unwrap(held).unwrap_or_else(|held| (*held).clone())); - let mut layout = comp.item_layout_from(previous, self.source, width, item, scx); - if self.header.has_columns() { - layout.set_columns(&self.header.columns(width)); - } - let ctx = ui.ctx(); - rows::measured_heights(ctx, id, |height| layout.measured(&|at| height(rows::measured_id(id, &self.source.key(at))))); - if layout.auto_widths() { - rows::measured_widths(ctx, id, |width| { - for at in 0..self.source.len() { - if let Some((ideal, min)) = width(rows::measured_width_id(id, &self.source.key(at))) { - layout.set_width(at, ideal, min); - } - } - }); - } - let content = layout.content_size(); - self.content = Vec2::new(content.x as f32, content.y as f32); - let props = comp.items(); - let row = props.row_height.of(scx); - let floor = rows_height(&layout, self.source.len(), props.min_rows, row); - let cap = props.max_rows.map(|rows| rows_height(&layout, self.source.len(), rows, row).max(floor)); - self.columns = layout.column_count() as u32; - self.layout = Some(Arc::new(layout)); - let empty = if self.source.is_empty() { comp.empty_height(width, ui, scx) } else { 0.0 }; - let rows = self.content.y.max(empty).max(floor); - let height = cap.map_or(rows, |cap| rows.min(cap)) + self.header.height; - if !(self.scrolls && room.y.is_finite()) { - let wide = if from_content { asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) } else { self.content.x }; - return Vec2::new(wide, height); - } - // A scrolling collection in a bounded room: `Content` takes its rows up to the room, `Fill` the room. - let wide = if self.content_sized(comp) { - self.content.x - } else if from_content { - asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) - } else { - 0.0 - }; - match comp.props(Internal::new()).sizing { - // Under a body sized from its content along the height, the rows take up to the room, as a content-sized - // collection's do: the body has no room of its own to hand it. - Sizing::Fill => Vec2::new(wide, if self.from_content.1 || self.capped { height.min(room.y) } else { 0.0 }), - Sizing::Content | Sizing::FillWidth => Vec2::new(wide, height.min(room.y)), - } + self.items_extent(comp, at, id) } fn pad(&self, comp: &C, tokens: &UiTokens) -> f32 { @@ -437,22 +349,12 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } let rtl = env.direction.is_rtl(); let node = matches!(C::ROLE, Role::Node(_)); - let (child_size, child_glyphs) = (comp.props(Internal::new()).child_size, comp.props(Internal::new()).child_glyphs); // The rows sit on the surface the collection paints, else on the one the collection sits on. let own = surface.or_else(|| cx.style.surface().and_then(|look| look.kind_in(&cx.core.state))); - let base_env = env.derive(|scoped| { - scoped.extend_values(values); - scoped.arena = Some(ArenaId::new(id)); - scoped.size = child_size.unwrap_or(cx.core.resolved.size); - if let Some(role) = child_glyphs { - scoped.glyphs = role; - } - scoped.surface = SurfaceKind::under(own, scoped.surface); - // The rows lay out their own content: no line or first line of the body around reaches them. - scoped.row_line = None; - scoped.first_line = None; - }); - self.place_reveal(comp, ui, (id, cx.core.env, &base_env), &mut layout, rect); + let base_env = Self::rows_env(comp, env, id, cx.core.resolved.size, own).derive(|scoped| scoped.extend_values(values)); + let known = self.known(comp, false); + let known_at_read = self.known(comp, true); + let revealed = self.place_reveal(comp, ui, (id, cx.core.env, &base_env), (&mut layout, &known), rect); let offset = ScrollPos { x: self.offset_x, y: self.offset }; Arc::make_mut(&mut layout).set_view(rect.size(), offset); if self.scrolls { @@ -486,12 +388,22 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let lead = self.lead.key.clone(); let mut lead_child = None; let striped = comp.items().striped; - let current: Option = comp.items().current.as_deref().and_then(|key| key.downcast_ref::()).cloned(); let mut stripe: Option<(usize, usize)> = None; let transform = comp.props(Internal::new()).transform; let (parent, clip) = (ui.layer_id(), rect.intersect(ui.clip_rect())); let forward = areas::Forward { root: id, sense: response::to_egui(cx.core.root_sense), rect: cx.core.rect.intersect(ui.clip_rect()) }; - let placed = self.selection.placed(self.source); + let placed = known.placed.clone(); + let tolerance = craft_behavior::layout_memory::measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); + // What this pass measured of the rows it builds, before any of them is built: (width and height, widths). + let fresh: Vec<(Option, Option)> = rows::measured_this_pass(&ctx, id, |fresh| { + order + .iter() + .map(|&at| { + let key = self.source.key(at); + (fresh(rows::measured_id(id, &key)), fresh(rows::measured_width_id(id, &key))) + }) + .collect() + }); let mut row_groups = Vec::with_capacity(order.len()); let mut shown_rows: Vec> = Vec::with_capacity(order.len()); // A section row the component declares as its own `section_part` reports its own node; any other one is the @@ -522,7 +434,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { (members_ui, installed) }); let mut members = Vec::new(); - for at in order.into_iter() { + for (place, at) in order.into_iter().enumerate() { if self.source.section_stop(at) { continue; } @@ -531,45 +443,31 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let row_group = rows::row_group(item_id); row_groups.push(row_group); let mut row = self.screen(&layout, rect, at, offset, rtl); + let odd = striped && { + let run = self.stripe_run(stripe, at); + stripe = Some((at, run)); + run.is_multiple_of(2) && !self.source.is_section(at) + }; + let (known_state, mut flags) = self.known_row(at, &known, odd); + // A row step 5 measured whose measured state this pass's input changed since is measured again. + let restated = !revealed.contains(&at) && self.known_row(at, &known_at_read, odd).0 != known_state; let state = RowState { - selected: placed.holds_row(at), - lead: lead.as_ref() == Some(&key), - renaming: self.renaming.key.as_ref() == Some(&key), - striped: striped && { - let run = self.stripe_run(stripe, at); - stripe = Some((at, run)); - run.is_multiple_of(2) && !self.source.is_section(at) - }, dragging: self.drags.grabbed.as_ref() == Some(&key), drop_target: matches!(&self.drags.pending, Some(PendingDrop::Drop(DropAt::Onto(over))) if *over == key), - current: current.as_ref() == Some(&key), - open: self.source.has_children(at) && self.source.open(at), hovered: hover_at.is_some_and(|pos| row.contains(pos)), pointer_over: over_at.is_some_and(|pos| row.contains(pos)), pressed: self.pressed.as_ref().filter(|(held, _)| *held == at).map(|(_, pressed)| pressed.clone()), menu_open: self.drags.menu.as_ref() == Some(&key) && menu_open, - sub_row: self.source.sub_row(at), - continued: at + 1 < len && self.source.sub_row(at + 1).is_some(), - last: at + 1 == len, activated_by_key: self.keyed_activation.as_ref() == Some(&key), - ..RowState::default() + ..known_state }; - let mut flags = crate::style::Flags::empty(); - flags.set(crate::style::Flags::SELECTED, state.selected); let child = if state.lead { rows::child_focus(&ctx, row_group) } else { None }; lead_child = lead_child.or(child); // A list that never takes key focus (a popup list: the host forwards its keys) shows its lead always. flags.set(crate::style::Flags::LEAD, state.lead && (focused || child.is_some() || !comp.items().focus_on_press)); - flags.set(crate::style::Flags::EXPANDED, state.open); flags.set(crate::style::Flags::DRAGGING, state.dragging); flags.set(crate::style::Flags::DROP_TARGET, state.drop_target); - flags.set(crate::style::Flags::CURRENT, state.current); - let mut position = SetPosition::new(at - self.source.section_stops_before(at)) - .of(len - self.source.section_stops_before(len)) - .columns(columns.len()); - if tree { - position = position.level(self.source.depth(at) + 1); - } + let position = self.row_position(at, columns.len(), tree); let mut cells = Vec::new(); layout.cells(at, offset, &mut cells); for (_, cell) in &mut cells { @@ -601,6 +499,8 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { memory: &mut *cx.core.memory, }; icx.memory.claim(icx.id); + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_build(&ctx, item_id); let item = (self.item)(&key, &mut icx); let mut item = comp.dress(item, &state); let tip = icx.tip.take(); @@ -640,11 +540,29 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { }; // A row is a run or a member, so one of the two is there. if let Some((measure_ui, _)) = row_ui.as_ref().or(members_ui.as_ref()) { - if layout.is_auto(at) && !self.measured_for_reveal.contains(&at) { + // A row this pass measured is placed by that measure. A row it did not measure (one the reveal's + // scroll or a kept lead brings in) is measured here. A restated row is measured again with its new + // state; a size other than the one the pass placed by asks for the frame's discard pass, so the + // rerun places it from step 5. + let (measured_size, measured_widths) = fresh[place]; + if layout.auto_widths() && (measured_widths.is_none() || restated) { + let widths = Vec2::new(item.measure_in(measure_ui, Proposal::Ideal).x, item.measure_in(measure_ui, Proposal::Min).x); + rows::record_measure(&ctx, id, rows::measured_width_id(id, &key), widths); + if measured_widths.is_some_and(|before| (before - widths).abs().max_elem() > tolerance) { + layout_memory::ask_discard(&ctx); + } + Arc::make_mut(&mut layout).set_width(at, widths.x, widths.y); + row = self.screen(&layout, rect, at, offset, rtl); + } + let measured_size = measured_size.filter(|size| (size.x - row.width()).abs() <= tolerance); + if layout.is_auto(at) && (measured_size.is_none() || restated) { let measured = item.measure_in(measure_ui, Proposal::Width(row.width())).y; #[cfg(feature = "testing")] crate::runtime::measure::count_row_measure(&ctx, rows::measured_id(id, &key)); rows::record_measure(&ctx, id, rows::measured_id(id, &key), Vec2::new(row.width(), measured)); + if measured_size.is_some_and(|before| (before.y - measured).abs() > tolerance) { + layout_memory::ask_discard(&ctx); + } if measured != row.height() { Arc::make_mut(&mut layout).set_height(at, measured); row = self.screen(&layout, rect, at, offset, rtl); @@ -656,13 +574,6 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { fit_widest = fit_widest.max(*width); } } - if layout.auto_widths() { - let ideal = item.measure_in(measure_ui, Proposal::Ideal).x; - let min = item.measure_in(measure_ui, Proposal::Min).x; - rows::record_measure(&ctx, id, rows::measured_width_id(id, &key), Vec2::new(ideal, min)); - Arc::make_mut(&mut layout).set_width(at, ideal, min); - row = self.screen(&layout, rect, at, offset, rtl); - } } shown_rows.push(ShownRow::new(key.clone(), row, shown_cells.clone())); let Some((mut row_ui, installed)) = row_ui else { @@ -947,10 +858,105 @@ impl ItemsHooks<'_, '_, C> { /// The height of the first `rows` rows of `layout` over `len` items: the rows it lays out, and the row height `row` for /// each one it does not have. -fn rows_height(layout: &impl ItemLayout, len: usize, rows: u16, row: f32) -> f32 { +pub(super) fn rows_height(layout: &impl ItemLayout, len: usize, rows: u16, row: f32) -> f32 { let rows = usize::from(rows); let laid = rows.min(len); let top = if len == 0 { 0.0 } else { layout.rect(0, ScrollPos::default()).min.y }; let built = if laid == 0 { 0.0 } else { layout.rect(laid - 1, ScrollPos::default()).max.y - top }; built + (rows - laid) as f32 * row } + +impl ItemsHooks<'_, '_, C> { + /// Step 5 in both runs: what the rows take in the room `measuring` gives. The auto rows in view are measured + /// first (`measure_ahead`), so the collection takes its size, and places its rows, by this pass's measure. + fn items_extent(&mut self, comp: &C, measuring: &Measuring<'_, '_>, id: Id) -> Vec2 { + let (ui, scx) = (measuring.ui, measuring.scx); + let room = match measuring.at { + ShowAt::Rect(rect) => rect.size(), + ShowAt::Flow => crate::layout::flow_room(ui), + }; + self.room = room; + self.indent_step = scx.control().icon; + let env = Env::of(ui); + let room = Self::inner_room(comp, scx.tokens, room); + // Where the enclosing body does not give the width, the collection takes its width from its content, whether + // it fills or fills the width, as a container does. Held in a content-sized column it measures so, and shows + // across the width the column settles on. + let held = env.content_column || crate::layout::in_grid_content_column(ui); + self.from_content = (!env.gives_width() && (crate::runtime::measure::active(ui.ctx()) || !held), env.content.1); + self.header.measure(scx); + self.header.read_content(ui.ctx(), id); + let bounded = room.x.is_finite(); + let item = comp.measures_items().then(|| layout_memory::measured(ui.ctx(), sub(id, "largest")).map(|measured| measured.took)).flatten(); + // Under a body that does not give the width, the measuring run lays the rows out at the width the collection + // asks for, so the height it reports is the one it has at that width (a grid's rows at its columns). + let from_content = self.from_content.0 && !self.content_sized(comp); + let asked = (from_content && !self.source.is_empty()).then(|| self.width_from_content(comp, ui, id, room, item, scx)); + let width = match (bounded, self.content_sized(comp)) { + (true, false) => asked.unwrap_or(room.x), + // No rows: the empty state has no ideal width, so it takes the room, or none where the room is unbounded. + (_, _) if self.source.is_empty() => { + if bounded { + room.x + } else { + 0.0 + } + } + // An unbounded room (a horizontally scrolling body) takes the widest row, as a content-sized collection does. + (_, _) => { + let floor = env.get::().0; + let widest = layout_memory::measured(ui.ctx(), sub(id, "largest")).map_or(0.0, |measured| measured.took.x); + // Columns side by side at their own widths: a `Content` column takes its widest cell, not the share of + // the widest row it would get. + let columns = if self.header.has_columns() { self.header.content_width() } else { 0.0 }; + widest.max(columns).max(comp.ideal_width(item, scx)).max(floor).min(room.x) + } + }; + let previous = self.layout.take().or_else(|| self.previous.take()).map(|held| Arc::try_unwrap(held).unwrap_or_else(|held| (*held).clone())); + let mut layout = comp.item_layout_from(previous, self.source, width, item, scx); + if self.header.has_columns() { + layout.set_columns(&self.header.columns(width)); + } + let ctx = ui.ctx(); + rows::measured_heights(ctx, id, |height| layout.measured(&|at| height(rows::measured_id(id, &self.source.key(at))))); + if layout.auto_widths() { + rows::measured_widths(ctx, id, |width| { + for at in 0..self.source.len() { + if let Some((ideal, min)) = width(rows::measured_width_id(id, &self.source.key(at))) { + layout.set_width(at, ideal, min); + } + } + }); + } + self.measure_ahead(comp, measuring, id, &mut layout, (width, room)); + let content = layout.content_size(); + self.content = Vec2::new(content.x as f32, content.y as f32); + let props = comp.items(); + let row = props.row_height.of(scx); + let floor = rows_height(&layout, self.source.len(), props.min_rows, row); + let cap = props.max_rows.map(|rows| rows_height(&layout, self.source.len(), rows, row).max(floor)); + self.columns = layout.column_count() as u32; + self.layout = Some(Arc::new(layout)); + let empty = if self.source.is_empty() { comp.empty_height(width, ui, scx) } else { 0.0 }; + let rows = self.content.y.max(empty).max(floor); + let height = cap.map_or(rows, |cap| rows.min(cap)) + self.header.height; + if !(self.scrolls && room.y.is_finite()) { + let wide = if from_content { asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) } else { self.content.x }; + return Vec2::new(wide, height); + } + // A scrolling collection in a bounded room: `Content` takes its rows up to the room, `Fill` the room. + let wide = if self.content_sized(comp) { + self.content.x + } else if from_content { + asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) + } else { + 0.0 + }; + match comp.props(Internal::new()).sizing { + // Under a body sized from its content along the height, the rows take up to the room, as a content-sized + // collection's do: the body has no room of its own to hand it. + Sizing::Fill => Vec2::new(wide, if self.from_content.1 || self.capped { height.min(room.y) } else { 0.0 }), + Sizing::Content | Sizing::FillWidth => Vec2::new(wide, height.min(room.y)), + } + } +} diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index 3fefcf765..9adabb333 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -8,12 +8,14 @@ use crate::contract::collection::RowState; use crate::contract::run::{Measuring, ShowAt}; use crate::contract::{Collection, Internal, ItemCx, Props, Show as _, Sizing}; use crate::runtime::access::SetPosition; +use crate::runtime::env::ArenaId; use crate::runtime::env::{Env, EnvView, ItemFacts}; use crate::runtime::layout_memory; use crate::runtime::memory::{MemoryStage, sub}; +use crate::style::{Flags, SurfaceKind}; use crate::style::{StyleCx, UiTokens}; -use craft_behavior::Proposal; use craft_behavior::layout_memory::measure_tolerance; +use craft_behavior::{ItemLayout as _, Proposal, ScrollPos, SelectionModel as _}; use egui::{Id, Pos2, Rect, Ui, Vec2}; impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { @@ -138,8 +140,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { if self.source.section_stop(at) { continue; } - let row = RowMeasure { at, rect: Rect::ZERO, cells: cells.clone(), proposal: Proposal::Ideal }; - let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row); + let row = RowMeasure::new(at, Rect::ZERO, cells.clone()); + let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row, |measure| measure(Proposal::Ideal)); largest = largest.max(size); for (column, width) in cells { match widest.iter_mut().find(|(held, _)| *held == column) { @@ -151,31 +153,32 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { (largest, widest) } - /// Builds the item of `row.at` as the collection `id` builds it, with the default row state, under `installed` - /// (`view` is what the item builder sees), and measures it at `row.proposal` without allocating: its size and the - /// widths its column cells reported. Item memory goes to `memory`. - pub(super) fn measure_row( + /// Builds the item of `row.at` as the collection `id` builds it, with the row state `row.state` and flags + /// `row.flags`, under `installed` (`view` is what the item builder sees), and hands `measure` a measure of it that + /// does not allocate: its size at a proposal and the widths its column cells reported. The item is built once + /// however many proposals `measure` asks. Item memory goes to `memory`. + pub(super) fn measure_row( &mut self, comp: &C, ui: &Ui, (id, view, installed): (Id, EnvView<'_>, &Env), memory: &mut MemoryStage, row: RowMeasure, - ) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>) { + measure: impl FnOnce(&mut dyn FnMut(Proposal) -> (Vec2, Vec<(craft_behavior::ColumnKey, f32)>)) -> R, + ) -> R { let ctx = ui.ctx().clone(); - let RowMeasure { at, rect, cells, proposal } = row; + let RowMeasure { at, rect, cells, state, flags, tree } = row; let len = self.source.len(); let key = self.source.key(at); let item_id = sub(id, ("key", key_hash(&key))); - let position = - SetPosition::new(at - self.source.section_stops_before(at)).of(len - self.source.section_stops_before(len)).columns(cells.len()); + let position = self.row_position(at, cells.len(), tree); let columns: Vec = cells.iter().map(|(key, _)| key.clone()).collect(); let column_count = cells.len(); let mut icx = ItemCx { key: &key, at, rect, - row: RowState::default(), + row: state.clone(), depth: self.source.depth(at), set: position, row_index: at, @@ -190,11 +193,13 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { item: item_id, memory, }; + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_build(&ctx, item_id); let item = (self.item)(&key, &mut icx); - let mut item = Props::id(comp.dress(item, &RowState::default()), item_id); + let mut item = Props::id(comp.dress(item, &state), item_id); let facts = ItemFacts { item: item_id, - flags: crate::style::Flags::empty(), + flags, position, columns, toggles: self.header.toggle_columns().map(|(key, _)| key).collect(), @@ -211,18 +216,196 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { scoped.item_facts = Some(std::sync::Arc::new(facts)); }), ); - let measured = crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, proposal)); + let measured = measure(&mut |proposal| crate::runtime::measure::cell_widths(&ctx, || item.measure_in(ui, proposal))); Env::restore(&ctx, env); measured } + + /// Measures the auto rows in the view the collection takes that this pass has not measured, before step 5 sizes + /// the collection from its layout: their ideal and minimum widths in a layout of auto widths, then their heights at + /// their widths. Each measure is recorded (`rows::record_measure`) and set in `layout`, so this pass places every + /// row in view by its measure, and the other runs of the pass take it without measuring again. The view is the + /// one step 5 sizes: `width` wide, as high as the rows (capped by `max_rows`), and no higher than `room` less the + /// header when the rows scroll in a bounded room, at the offset step 4 read. It repeats while measured rows bring + /// other unmeasured rows into view; each row is measured at most once. + pub(super) fn measure_ahead(&mut self, comp: &C, measuring: &Measuring<'_, '_>, id: Id, layout: &mut C::ItemLayout, (width, room): (f32, Vec2)) { + if self.source.is_empty() { + return; + } + let ctx = measuring.ui.ctx().clone(); + let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); + let props = comp.items(); + let (row, max_rows, striped) = (props.row_height.of(measuring.scx), props.max_rows, props.striped); + let tree = matches!(layout.nav(), craft_behavior::NavShape::Tree); + let known = self.known(comp, true); + let env = Self::rows_env(comp, measuring.env, id, measuring.resolved.size, comp.props(Internal::new()).surface); + let widths = layout.auto_widths(); + let mut memory = None; + // How many times each row was measured here: its widths once, its height again only at a width the later rows' + // widths moved it to. + let mut done: Vec<(usize, u8)> = Vec::new(); + loop { + let content = layout.content_size().y as f32; + let mut high = max_rows.map_or(content, |rows| content.min(super::hooks::rows_height(&*layout, self.source.len(), rows, row))); + if self.scrolls && room.y.is_finite() { + high = high.min((room.y - self.header.height).max(0.0)); + } + let mut in_view = Vec::new(); + layout.visible(ScrollPos { x: self.offset_x, y: self.offset.max(0.0) }, Vec2::new(width, high), &mut in_view); + in_view.sort_unstable(); + let source = self.source; + // The rows of the view this pass has not measured: (row, its widths, its height). + let todo: Vec<(usize, bool, bool)> = rows::measured_this_pass(&ctx, id, |fresh| { + in_view + .into_iter() + .filter(|&at| layout.is_auto(at) && !source.section_stop(at) && done.iter().all(|&(held, times)| held != at || times < 2)) + .filter_map(|at| { + let key = source.key(at); + let wide = widths && fresh(rows::measured_width_id(id, &key)).is_none(); + let row_width = layout.rect(at, ScrollPos::default()).width(); + let high = fresh(rows::measured_id(id, &key)).is_none_or(|size| (size.x - row_width).abs() > tolerance); + (wide || high).then_some((at, wide, high)) + }) + .collect() + }); + if todo.is_empty() { + return; + } + let memory = memory.get_or_insert_with(|| MemoryStage::open_peek(&ctx, id)); + let mut stripe: Option<(usize, usize)> = None; + for (at, wide, high) in todo { + match done.iter_mut().find(|(held, _)| *held == at) { + Some((_, times)) => *times += 1, + None => done.push((at, 1)), + } + let odd = striped && { + let run = self.stripe_run(stripe, at); + stripe = Some((at, run)); + run.is_multiple_of(2) && !self.source.is_section(at) + }; + let (state, flags) = self.known_row(at, &known, odd); + let mut cells = Vec::new(); + layout.cells(at, ScrollPos::default(), &mut cells); + let row_measure = RowMeasure { at, rect: layout.rect(at, ScrollPos::default()), cells, state, flags, tree }; + let key = self.source.key(at); + let (width_id, height_id) = (rows::measured_width_id(id, &key), rows::measured_id(id, &key)); + let installed = (id, env.view(), &env); + crate::contract::steps::measuring(&ctx, || { + self.measure_row(comp, measuring.ui, installed, memory, row_measure, |measure| { + // A row of auto widths takes its ideal width unless the fit over every row's widths shrinks it: + // its height is measured there, and again only where the fit settles on another width. + let mut row_width = layout.rect(at, ScrollPos::default()).width(); + if wide { + let (ideal, min) = (measure(Proposal::Ideal).0.x, measure(Proposal::Min).0.x); + rows::record_measure(&ctx, id, width_id, Vec2::new(ideal, min)); + layout.set_width(at, ideal, min); + row_width = ideal; + } + if high || wide { + let height = measure(Proposal::Width(row_width)).0.y; + #[cfg(feature = "testing")] + crate::runtime::measure::count_row_measure(&ctx, height_id); + rows::record_measure(&ctx, id, height_id, Vec2::new(row_width, height)); + layout.set_height(at, height); + } + }); + }); + } + } + } + + /// The place of the row `at` in the collection's set, among `columns` columns, with its level in a tree. + pub(super) fn row_position(&self, at: usize, columns: usize, tree: bool) -> SetPosition { + let len = self.source.len(); + let position = SetPosition::new(at - self.source.section_stops_before(at)).of(len - self.source.section_stops_before(len)).columns(columns); + if tree { position.level(self.source.depth(at) + 1) } else { position } + } + + /// The env the rows lay out under, from the collection's env `env`: the collection's arena, the child size (else + /// the collection's `size`), the child glyph role, and the surface the rows sit on (`own`, else the one the + /// collection sits on). The rows lay out their own content: no line or first line of the body around reaches them. + /// The content step adds the app values its body gives (the row-hook contract on `ItemCx`). + pub(super) fn rows_env(comp: &C, env: &Env, id: Id, size: craft_theme::ControlSize, own: Option) -> Env { + let (child_size, child_glyphs) = (comp.props(Internal::new()).child_size, comp.props(Internal::new()).child_glyphs); + env.derive(|scoped| { + scoped.arena = Some(ArenaId::new(id)); + scoped.size = child_size.unwrap_or(size); + if let Some(role) = child_glyphs { + scoped.glyphs = role; + } + scoped.surface = SurfaceKind::under(own, scoped.surface); + scoped.row_line = None; + scoped.first_line = None; + }) + } + + /// The state of the row `at` its measure reads, from `known` (the row-hook contract on `ItemCx`): selected, lead, + /// renaming, current, open, striped (`striped`, which the caller runs along the rows), and its place among + /// sub-rows and the last row; with the `SELECTED`, `EXPANDED` and `CURRENT` flags. The content step adds the + /// pointer, gesture and focus state. + pub(super) fn known_row(&self, at: usize, known: &Known, striped: bool) -> (RowState, Flags) { + let key = self.source.key(at); + let len = self.source.len(); + let state = RowState { + selected: known.placed.holds_row(at), + lead: known.lead.as_ref() == Some(&key), + renaming: known.renaming.as_ref() == Some(&key), + striped, + current: known.current.as_ref() == Some(&key), + open: self.source.has_children(at) && self.source.open(at), + sub_row: self.source.sub_row(at), + continued: at + 1 < len && self.source.sub_row(at + 1).is_some(), + last: at + 1 == len, + ..RowState::default() + }; + let mut flags = Flags::empty(); + flags.set(Flags::SELECTED, state.selected); + flags.set(Flags::EXPANDED, state.open); + flags.set(Flags::CURRENT, state.current); + (state, flags) + } + + /// The facts `known_row` reads: the selection, lead and renaming row as step 4 read them (`at_read`), or as the + /// pass leaves them. + pub(super) fn known(&self, comp: &C, at_read: bool) -> Known { + let current = comp.items().current.as_deref().and_then(|key| key.downcast_ref::()).cloned(); + if at_read { + Known { + placed: self.selection_at_read.placed(self.source), + lead: self.lead_at_read.clone(), + renaming: self.renaming_at_read.clone(), + current, + } + } else { + Known { placed: self.selection.placed(self.source), lead: self.lead.key.clone(), renaming: self.renaming.key.clone(), current } + } + } } -/// A row to build and measure (`measure_row`): its position, rect and column cells, and the proposal it is measured at. +/// What the state of a row known before the pass senses input comes from (`ItemsHooks::known_row`). +pub(super) struct Known { + pub(super) placed: craft_behavior::PlacedSelection, + pub(super) lead: Option, + pub(super) renaming: Option, + pub(super) current: Option, +} + +/// A row to build and measure (`measure_row`): its position, rect and column cells, its state and flags, and whether +/// the collection is a tree. pub(super) struct RowMeasure { pub(super) at: usize, pub(super) rect: Rect, pub(super) cells: Vec<(craft_behavior::ColumnKey, Rect)>, - pub(super) proposal: Proposal, + pub(super) state: RowState, + pub(super) flags: Flags, + pub(super) tree: bool, +} + +impl RowMeasure { + /// The row `at` at `rect` with `cells`, in the default state. + pub(super) fn new(at: usize, rect: Rect, cells: Vec<(craft_behavior::ColumnKey, Rect)>) -> Self { + RowMeasure { at, rect, cells, state: RowState::default(), flags: Flags::empty(), tree: false } + } } /// The inputs a kept measure of the items serves under. diff --git a/crates/ui-contract/src/contract/items/reveal.rs b/crates/ui-contract/src/contract/items/reveal.rs index 94be7096e..27059aa53 100644 --- a/crates/ui-contract/src/contract/items/reveal.rs +++ b/crates/ui-contract/src/contract/items/reveal.rs @@ -1,6 +1,6 @@ //! Bringing a row into view: a requested reveal and the scroll that does it. -use super::measure::RowMeasure; +use super::measure::{Known, RowMeasure}; use super::{ItemsHooks, rows}; use crate::contract::Collection; use crate::contract::collection::LeadSource; @@ -37,17 +37,20 @@ impl ItemsHooks<'_, '_, C> { /// for the first time takes its measured height when built and moves the rows after it, so the auto rows that /// share the view with the revealed row, up to it, and have no kept height are built and measured first, under the /// rows' env `installed`, until the scroll that shows the row places it by measured heights only. The build takes - /// those heights (`measured_for_reveal`) and does not measure the rows again. + /// those heights (they are this pass's measure) and does not measure the rows again. The rows are measured with + /// the state `known` the pass leaves them in; returns them. pub(super) fn place_reveal( &mut self, comp: &C, ui: &Ui, (id, view_env, installed): (Id, EnvView<'_>, &Env), - layout: &mut Arc, + (layout, known): (&mut Arc, &Known), view: Rect, - ) { - let Some(at) = self.revealing.take().filter(|&at| layout.shown(at)) else { return }; + ) -> Vec { + let mut measured = Vec::new(); + let Some(at) = self.revealing.take().filter(|&at| layout.shown(at)) else { return measured }; let ctx = ui.ctx().clone(); + let (striped, tree) = (comp.items().striped, matches!(layout.nav(), craft_behavior::NavShape::Tree)); loop { self.aim_reveal(layout, at, view.height()); let mut in_view = Vec::new(); @@ -58,29 +61,32 @@ impl ItemsHooks<'_, '_, C> { .into_iter() .chain([at]) .filter(|&row| row <= at && layout.is_auto(row) && !source.section_stop(row)) - .filter(|row| !self.measured_for_reveal.contains(row) && height(rows::measured_id(id, &source.key(*row))).is_none()) + .filter(|row| !measured.contains(row) && height(rows::measured_id(id, &source.key(*row))).is_none()) .collect() }); if unmeasured.is_empty() { - return; + return measured; } let mut memory = MemoryStage::open_peek(&ctx, id); for row in unmeasured { - if self.measured_for_reveal.contains(&row) { + if measured.contains(&row) { continue; } let rect = layout.rect(row, ScrollPos::default()); let mut cells = Vec::new(); layout.cells(row, ScrollPos::default(), &mut cells); - let measure = RowMeasure { at: row, rect, cells, proposal: Proposal::Width(rect.width()) }; - let (size, _) = - crate::contract::steps::measuring(&ctx, || self.measure_row(comp, ui, (id, view_env, installed), &mut memory, measure)); - let measured = rows::measured_id(id, &self.source.key(row)); + let odd = striped && self.stripe_run(None, row).is_multiple_of(2) && !self.source.is_section(row); + let (state, flags) = self.known_row(row, known, odd); + let measure = RowMeasure { at: row, rect, cells, state, flags, tree }; + let (size, _) = crate::contract::steps::measuring(&ctx, || { + self.measure_row(comp, ui, (id, view_env, installed), &mut memory, measure, |measure| measure(Proposal::Width(rect.width()))) + }); + let height_id = rows::measured_id(id, &self.source.key(row)); #[cfg(feature = "testing")] - crate::runtime::measure::count_row_measure(&ctx, measured); - rows::record_measure(&ctx, id, measured, Vec2::new(rect.width(), size.y)); + crate::runtime::measure::count_row_measure(&ctx, height_id); + rows::record_measure(&ctx, id, height_id, Vec2::new(rect.width(), size.y)); Arc::make_mut(layout).set_height(row, size.y); - self.measured_for_reveal.push(row); + measured.push(row); } let content = layout.content_size(); self.content = Vec2::new(content.x as f32, content.y as f32); diff --git a/crates/ui-contract/src/contract/items/rows.rs b/crates/ui-contract/src/contract/items/rows.rs index b8cc620d7..bcde9f9a2 100644 --- a/crates/ui-contract/src/contract/items/rows.rs +++ b/crates/ui-contract/src/contract/items/rows.rs @@ -46,7 +46,14 @@ pub(super) fn measured_id(collection: Id, key: &K) -> Id { /// Runs `f` with a reader of the heights the auto rows of the collection `collection` had in the last pass that built /// them: the rows the pass does not build, out of view, are placed by them (`runtime::lazy`). pub(super) fn measured_heights(ctx: &Context, collection: Id, f: impl FnOnce(&dyn Fn(Id) -> Option) -> R) -> R { - lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|size| size.y))) + lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|(size, _)| size.y))) +} + +/// Runs `f` with a reader of what this pass measured of the rows of the collection `collection`, by the ids +/// `measured_id` and `measured_width_id` give: the row's width and height, or its ideal and minimum widths; `None` for +/// a row this pass has not measured. A row measured this pass is not measured again in it. +pub(super) fn measured_this_pass(ctx: &Context, collection: Id, f: impl FnOnce(&dyn Fn(Id) -> Option) -> R) -> R { + lazy::reading(ctx, collection, |read| f(&|id| read(id).and_then(|(size, now)| now.then_some(size)))) } /// The id an auto-width item's measured widths (ideal, then minimum) are kept under. @@ -57,11 +64,11 @@ pub(super) fn measured_width_id(collection: Id, key: &K) -> /// Runs `f` with a reader of the `(ideal, min)` widths the auto-width items of the collection `collection` had in the /// last pass that built them. pub(super) fn measured_widths(ctx: &Context, collection: Id, f: impl FnOnce(&dyn Fn(Id) -> Option<(f32, f32)>) -> R) -> R { - lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|size| (size.x, size.y)))) + lazy::reading(ctx, collection, |read| f(&|id| read(id).map(|(size, _)| (size.x, size.y)))) } -/// Records the size an auto row of the collection `collection` measured this pass; the row is placed by it in the same -/// pass. +/// Records the size an auto row of the collection `collection` measured this pass (its width and height, or its ideal +/// and minimum widths); the row is placed by it in the same pass. pub(super) fn record_measure(ctx: &Context, collection: Id, id: Id, size: Vec2) { lazy::remember(ctx, collection, id, size); } diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 8da13460b..69cdfd9c4 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -647,7 +647,8 @@ pub trait Collection: Component + HasProps + Meta { None } - /// Adjusts the item the closure built for a row, from the row's state. + /// Adjusts the item the closure built for a row, from the row's state. An auto row's measure reads the item this + /// makes, under the row-hook contract on `ItemCx`. fn dress<'r>(&self, item: Self::Item<'r>, _row: &RowState) -> Self::Item<'r> { item } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index fd0ce3a8d..57bf75607 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -148,6 +148,8 @@ struct Entry { measured: Option, /// Whether this pass replays the memoized view's last run, under the pass number that decided it. replays: Option<(u64, bool)>, + /// The pass a collection row's extent was last measured in (`remember`). + measured_in: Option, /// The last frame that read or wrote the entry. touched: u64, } @@ -606,23 +608,29 @@ pub(crate) fn note_edit(ctx: &Context, key: BindKey) { }); } -/// Records the extent of a row of the collection `owner` that was built this pass. The collection places the rows it -/// does not build by it (its item layout answers for rows it never built). +/// Records the extent of a row of the collection `owner` that was measured this pass. The collection places the rows +/// it does not build by it (its item layout answers for rows it never built), and every run of the pass that reaches +/// the row takes it without measuring the row again. pub(crate) fn remember(ctx: &Context, owner: Id, id: Id, size: Vec2) { - shown(ctx, Some(owner), id, false, Measured { size, key: Key::None, room: Rect::NOTHING }, None); + with(ctx, |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.measured_in = Some(pass_nr); + }); } -/// Runs `f` with a reader of the extents the rows of the collection `owner` had in the last pass that built them, for -/// a collection that reads many entries at once. -pub(crate) fn reading(ctx: &Context, owner: Id, f: impl FnOnce(&dyn Fn(Id) -> Option) -> R) -> R { - with(ctx, |store, _, frame| { +/// Runs `f` with a reader of the extents the rows of the collection `owner` had in the last pass that measured them, +/// each with whether that pass is this one, for a collection that reads many entries at once. +pub(crate) fn reading(ctx: &Context, owner: Id, f: impl FnOnce(&dyn Fn(Id) -> Option<(Vec2, bool)>) -> R) -> R { + with(ctx, |store, pass_nr, frame| { store.reached.insert(owner, frame); let store = std::cell::RefCell::new(store); f(&|id| { let mut store = store.borrow_mut(); let entry = store.entries.get_mut(&id)?; entry.touched = frame; - entry.sizes[1].or(entry.sizes[0]).map(|measured| measured.size) + let size = entry.sizes[1].or(entry.sizes[0]).map(|measured| measured.size)?; + Some((size, entry.measured_in == Some(pass_nr))) }) }) } diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index 3e1ef8eff..4c5c6481d 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -84,6 +84,14 @@ struct RowMeasures { rows: Vec<(Id, u32)>, } +/// The collection rows whose item was built, by item id, with the pass that counted them. +#[cfg(feature = "testing")] +#[derive(Default)] +struct RowBuilds { + pass: u64, + rows: Vec<(Id, u32)>, +} + /// The rows that asked their body units for their least widths, with the pass that counted them. #[cfg(feature = "testing")] #[derive(Default)] @@ -304,6 +312,31 @@ pub fn row_measures(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) } +/// Counts a build of the item `id` of a collection row in this pass: for a measure, or to show it. +#[cfg(feature = "testing")] +pub(crate) fn count_row_build(ctx: &Context, id: Id) { + if uncounted(ctx) { + return; + } + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |log| { + if log.pass != pass { + *log = RowBuilds { pass, rows: Vec::new() }; + } + match log.rows.iter_mut().find(|(row, _)| *row == id) { + Some((_, count)) => *count += 1, + None => log.rows.push((id, 1)), + } + }); +} + +/// The collection rows whose item was built in the last pass, by item id, and how many times each. +#[cfg(feature = "testing")] +pub fn row_builds(ctx: &Context) -> Vec<(Id, u32)> { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |log| if log.pass == last { log.rows.clone() } else { Vec::new() }) +} + /// Counts a sweep of the row `id` that asks its body units for their least widths in this pass. #[cfg(feature = "testing")] pub(crate) fn count_least(ctx: &Context, id: Id) { diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index b922addb6..ad6c05733 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -44,7 +44,7 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ MemoRun, active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_frame_memo_runs, last_pass_body_runs as last_pass_measuring_runs, last_pass_measure_asks, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, - last_pass_text_layouts, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, + last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, 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-widgets/tests/it/list.rs b/crates/ui-widgets/tests/it/list.rs index aa5f3199f..ce24fb682 100644 --- a/crates/ui-widgets/tests/it/list.rs +++ b/crates/ui-widgets/tests/it/list.rs @@ -1113,3 +1113,57 @@ fn a_row_dragged_to_the_edge_scrolls_the_list_and_rests_without_frames() { assert!(!fixture.repaint_requested(), "a drag held over the middle rows asks for no frame"); fixture.release_at(Pos2::new(grab.x, list.center().y)); } + +/// Auto rows place by their measure in the first frame. In a column sized from its content along the height, where +/// each pass runs the list's measuring run and its real run, the first frame runs once, measures each row once, builds each row at most +/// twice, and places the rows and the list where the settled list has them. A click that selects a row and a rename +/// request change a state the row's size reads after the pass measured it: the frame shows the row, and the list +/// around it, at the new size. +#[trial] +fn auto_rows_are_measured_once_per_pass_and_a_restated_row_takes_its_new_size_in_the_same_frame() { + use craft_ui::contract::{ShowContainer as _, Sizing}; + use craft_ui::layout_components::Stack; + use craft_ui::list::ThumbSize; + use craft_ui::testing::pointer::{moved, press, release}; + let mut fixture = Fixture::new(move |ui| { + Stack::new().sizing(Sizing::FillWidth).show(ui, |ui, _| { + let keys = [0_usize, 1, 2]; + let source = keyed(&keys, |key: &usize| *key).with_text(|key| std::borrow::Cow::Borrowed(NAMES[*key])); + List::new("Artboards").id(list_id()).rename(true).show_items(ui, &source, &mut |key, icx| { + let size = if icx.row.selected || icx.row.renaming { ThumbSize::Large } else { ThumbSize::Medium }; + ListRow::new(NAMES[*key]).thumb(size, |_, _| {}) + }); + }); + }); + fixture.room(Vec2::new(300.0, 400.0)); + let list = |fixture: &Fixture| fixture.by_label("Artboards").expect("the list's node").rect; + let row = |fixture: &Fixture, at: usize| fixture.by_label(NAMES[at]).expect("the row's node").rect; + fixture.idle(1); + assert_eq!(fixture.passes(), 1, "the first frame runs once"); + let runs = craft_ui::testing::last_pass_runs(fixture.ctx()); + assert!(runs.iter().any(|(name, count)| name.contains("::List<") && *count >= 2), "the list has a measuring run and a real run: {runs:?}"); + let measures = craft_ui::testing::row_measures(fixture.ctx()); + assert!(measures.len() == NAMES.len() && measures.iter().all(|(_, count)| *count == 1), "each row is measured once: {measures:?}"); + let builds = craft_ui::testing::row_builds(fixture.ctx()); + assert!(builds.len() == NAMES.len() && builds.iter().all(|(_, count)| *count <= 2), "each row is built at most twice: {builds:?}"); + let first = (list(&fixture), [row(&fixture, 0), row(&fixture, 1), row(&fixture, 2)]); + fixture.idle(3); + let settled = (list(&fixture), [row(&fixture, 0), row(&fixture, 1), row(&fixture, 2)]); + assert_eq!(first, settled, "the first frame places the rows and the list as the settled list does"); + + let at = settled.1[1].center(); + fixture.frame(vec![moved(at)]); + fixture.frame(vec![press(at), release(at)]); + let clicked = (list(&fixture), row(&fixture, 1)); + assert!(clicked.1.height() > settled.1[1].height(), "the selected row takes its taller size in the frame of the click"); + fixture.idle(2); + assert_eq!(clicked, (list(&fixture), row(&fixture, 1)), "the frame of the click shows the list and the row at their settled sizes"); + + let below = row(&fixture, 1).top(); + request_rename(fixture.ctx(), list_id(), &0_usize); + fixture.idle(1); + let renamed = (list(&fixture), row(&fixture, 1).top()); + assert!(renamed.1 > below, "the renaming row takes its taller size in the frame the rename starts"); + fixture.idle(2); + assert_eq!(renamed, (list(&fixture), row(&fixture, 1).top()), "the frame the rename starts shows the list and the rows settled"); +} diff --git a/crates/ui-widgets/tests/it/tabs.rs b/crates/ui-widgets/tests/it/tabs.rs index ac554bc9d..f417c8735 100644 --- a/crates/ui-widgets/tests/it/tabs.rs +++ b/crates/ui-widgets/tests/it/tabs.rs @@ -364,3 +364,25 @@ fn panel_tabs_keep_the_shown_tab_whole_and_overflow_from_the_end() { } assert!(fewer < PANELS.len(), "the narrowest room overflows"); } + +/// A strip places its tabs by their measure in its first frame: the frame runs once, measures each tab once, and the +/// strip and every tab have the rects they have once the strip settles. +#[trial] +fn a_tab_strip_takes_its_measured_extents_in_its_first_frame() { + let mut fixture = Fixture::new(|ui| { + let keys = [0_usize, 1, 2]; + let source = keyed(&keys, |key: &usize| *key); + let _ = TabStrip::new("Documents").shown(0).show_items(ui, &source, &mut |key, _| Tab::new(TITLES[*key])); + }); + let rects = |fixture: &Fixture| { + let strip = fixture.by_label("Documents").expect("the strip's node").rect; + (strip, TITLES.map(|title| tab_rect(fixture.tree(), title))) + }; + fixture.idle(1); + assert_eq!(fixture.passes(), 1, "the first frame runs once"); + let measures = craft_ui::testing::row_measures(fixture.ctx()); + assert!(measures.len() == TITLES.len() && measures.iter().all(|(_, count)| *count == 1), "each tab is measured once: {measures:?}"); + let first = rects(&fixture); + fixture.idle(3); + assert_eq!(first, rects(&fixture), "the first frame places the strip and its tabs as the settled strip does"); +}