diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index 9d3e51de5..b9c1e5bfd 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -231,14 +231,19 @@ impl GridCursor { pub fn fill_room(&self) -> Vec2 { let mut room = self.room(); if self.in_content_column() { - room.x = self.widths.get(self.next % self.columns.len().max(1)).copied().unwrap_or(0.0); + room.x = self.widths.get(self.column()).copied().unwrap_or(0.0); } room } /// Whether the next child goes in a `Content` column. pub fn in_content_column(&self) -> bool { - matches!(self.columns.get(self.next % self.columns.len().max(1)), Some(ColumnWidth::Content)) + matches!(self.columns.get(self.column()), Some(ColumnWidth::Content)) + } + + /// The column the next child goes in. + pub fn column(&self) -> usize { + self.next % self.columns.len().max(1) } /// The cell last placed measured `size` after all: its column and row record that, and a `Content` column offers diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index c61c822b6..848203587 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -1273,12 +1273,25 @@ fn measured(t: &mut dyn Erased, input: &MeasureIn<'_>, style: &dyn StyleView, re (steps::measure(style, input, content, extent, resolved), inputs) } -/// The pipeline: steps 1 to 17 for one component, whatever its type and shape. +/// The pipeline: steps 1 to 17 for one component, whatever its type and shape. A component that takes a cell of a +/// `Grid` runs under the column group of its cell's column (`ColumnGroup::cell`). +pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { + let cell = (matches!(at, ShowAt::Flow) && t.in_flow()).then(|| crate::layout::grid_cell(ui)).flatten(); + match cell { + Some((grid, column, sized)) => { + let ctx = ui.ctx().clone(); + crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || run_steps(t, ui, at, tip)); + } + None => run_steps(t, ui, at, tip), + } +} + +/// Steps 1 to 17 of `run`. #[expect( clippy::cognitive_complexity, reason = "steps 1 to 17 in their fixed order; each step is already its own function and the rest is the order" )] -pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option>) { +fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option>) { let ctx = ui.ctx().clone(); let facts = t.facts(); crate::runtime::measure::count_run(&ctx, facts.name); diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 465c02679..6540d6f42 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -1,6 +1,7 @@ //! `BodyLayout` and the layout of a body: the physical egui layout, the measured placement of `Row` End and //! Center and of each row child on the row's line, and the cursors of `Grid` and of a `Row` that spreads its children. +use super::column_group::{ColumnGroup, Columns}; use crate::contract::InBar; use crate::runtime::egui::{alloc, child}; use crate::runtime::env::{ColumnSweep, Env, RowLine, Shrink}; @@ -744,6 +745,14 @@ impl Cursor { fn in_content_column(&self) -> bool { matches!(self, Cursor::Grid(grid) if grid.in_content_column()) } + + /// The grid column the next child goes in; `None` for a spread row. + fn grid_column(&self) -> Option { + match self { + Cursor::Grid(grid) => Some(grid.column()), + Cursor::Spread(_) => None, + } + } } /// The cursor of a `SpaceBetween` row: each child in flow takes the next place along the row, and the room the @@ -1049,6 +1058,16 @@ pub(crate) fn in_grid_content_column(ui: &Ui) -> bool { .is_some_and(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).is_some_and(Cursor::in_content_column))) } +/// The cell the next child shown in flow in `ui` takes, when the body that encloses `ui` directly is a `Grid`: the +/// grid's body, the cell's column and whether the column is a `Content` one. +pub(crate) fn grid_cell(ui: &Ui) -> Option<(Id, usize, bool)> { + let grid = Env::of(ui).grid?; + pass_state::with::(ui.ctx(), |cursors| { + let cursor = cursors.0.get(&grid)?; + Some((grid, cursor.grid_column()?, cursor.in_content_column())) + }) +} + fn column_id(grid: Id, index: usize) -> Id { sub(grid, ("column", index)) } @@ -1075,7 +1094,8 @@ fn measured_tracks(ctx: &egui::Context, sizing: bool, grid: Id, columns: usize) /// The one column a grid lays its cells in, one under another, when its columns do not fit beside each other. const STACKED: &[ColumnWidth] = &[ColumnWidth::fill(1.0)]; -/// Runs `body`, the cells of the `Grid` body `id` over `columns`, in `ui`. +/// Runs `body`, the cells of the `Grid` body `id` over `columns`, in `ui`. Each column is a column group +/// (`ColumnGroup::grid`): the labels beside the controls of one column share a width. /// /// A measuring run sweeps the cells once, each `Content` column in the room the other columns leave at their least /// (`GridCursor::each_alone`). When the columns do not fit beside each other (`GridCursor::short`), it sweeps them again @@ -1088,14 +1108,16 @@ fn run_grid(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec let ctx = ui.ctx().clone(); let rtl = env.direction.is_rtl(); let layout = child::column_layout(rtl); - // One sweep of the cells in `ui` with the cursor `make` gives the flow of `ui`'s layout; returns what the cursor - // measured. - let mut sweep = |ui: &mut Ui, scoped: &Env, make: &dyn Fn(Flow) -> GridCursor| { + // One sweep of the cells in `ui` over `columns`, with the cursor `make` given the flow of `ui`'s layout and the + // column groups opened at `seed`; returns what the cursor measured, and from a measuring sweep the groups' widths + // when they have to settle (`ColumnGroup::grid`). + let mut sweep = |ui: &mut Ui, scoped: &Env, seed: Option>, columns: &[ColumnWidth], make: &dyn Fn(Flow) -> GridCursor| { let top = ui.available_rect_before_wrap().top(); let cursor = make(Flow::new(ui.available_rect_before_wrap(), rtl)); + let count = columns.len(); pass_state::with::(&ctx, |cursors| cursors.0.insert(id, Cursor::Grid(cursor))); let installed = Env::install_for(ui, scoped.derive_local(|scoped| scoped.grid = Some(id))); - let inner = body(ui); + let (inner, unsettled) = ColumnGroup::grid(ui, id, count, seed, &mut body); Env::restore(&ctx, installed); let cursor = match pass_state::with::(&ctx, |cursors| cursors.0.remove(&id)) { Some(Cursor::Grid(cursor)) => Some(cursor), @@ -1107,13 +1129,13 @@ fn run_grid(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec // down as the rows this pass measured, whichever pass it is. let rows = measured.rows.iter().sum::() + gap.y * measured.rows.len().saturating_sub(1) as f32; alloc::reach_down_to(ui, top + rows); - (inner, measured, short) + (inner, measured, short, unsettled) }; if !measure::active(&ctx) { let stacked = this_pass(&ctx, false, sub(id, "stacked")).is_some_and(|stacked| stacked.x > 0.0); let columns = if stacked { STACKED } else { columns }; let last = measured_tracks(&ctx, false, id, columns.len()); - return child::block(ui, None, layout, |ui| sweep(ui, env, &|flow| GridCursor::new(flow, columns, gap, &last)).0).0; + return child::block(ui, None, layout, |ui| sweep(ui, env, None, columns, &|flow| GridCursor::new(flow, columns, gap, &last)).0).0; } // A measuring run under a body sized from its content gives each fill column the width its cells take, as a // content column: the room it would share is not the body's to claim. @@ -1123,11 +1145,30 @@ fn run_grid(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec false => GridCursor::new(flow, columns, gap, last), }; let none = GridMeasure::default(); - let (inner, measured, rect, short) = crate::contract::keeping_ids(&ctx, || { - let mut first = ui.new_child(egui::UiBuilder::new().layout(layout)); - let (inner, measured, short) = sweep(&mut first, env, &|flow| cursor(columns, &none, flow).each_alone()); - ((inner, measured, first.min_rect(), short), short) - }); + // The first sweep, each column alone. When a cell read a label column narrower than its group settled on, the + // sweep is taken back and runs once more with the groups opened at the widths it found. + let mut alone = |ui: &mut Ui, seed: Option>| { + let seeded = seed.is_some(); + crate::contract::keeping_ids(&ctx, || { + let (out, kept) = layout_memory::draft( + &ctx, + || { + let mut first = ui.new_child(egui::UiBuilder::new().layout(layout)); + let (inner, measured, short, unsettled) = + sweep(&mut first, env, seed, columns, &|flow| cursor(columns, &none, flow).each_alone()); + (inner, measured, first.min_rect(), short, unsettled) + }, + |out| seeded || out.4.is_none(), + ); + let restore = !kept || out.3; + (out, restore) + }) + }; + let mut first = alone(ui, None); + if let Some(widths) = first.4.take() { + first = alone(ui, Some(widths)); + } + let (inner, measured, rect, short, _) = first; let record = |measured: &GridMeasure, least: &[f32], stacked: bool, room: Vec2| { for (i, width) in measured.columns.iter().enumerate() { found(&ctx, true, column_id(id, i), room, Vec2::new(*width, 0.0)); @@ -1155,7 +1196,7 @@ fn run_grid(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec let least = crate::contract::keeping_ids(&ctx, || { let least = layout_memory::probing(&ctx, || { let mut least = ui.new_child(egui::UiBuilder::new().layout(layout)); - sweep(&mut least, &probe, &|flow| GridCursor::unbounded(flow, columns, gap)).1.columns + sweep(&mut least, &probe, None, columns, &|flow| GridCursor::unbounded(flow, columns, gap)).1.columns }); (least, true) }); @@ -1172,7 +1213,7 @@ fn run_grid(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec true => (STACKED, GridMeasure::default()), false => (columns, GridMeasure::default().with_least(least.clone())), }; - let (inner, measured, _) = child::block(ui, None, layout, |ui| sweep(ui, env, &|flow| cursor(columns, &last, flow))).0; + let (inner, measured, ..) = child::block(ui, None, layout, |ui| sweep(ui, env, None, columns, &|flow| cursor(columns, &last, flow))).0; record(&measured, &last.least, stacked, ui.available_rect_before_wrap().size()); inner } diff --git a/crates/ui-contract/src/layout/column_group.rs b/crates/ui-contract/src/layout/column_group.rs index 80f0d1929..c9caf30e3 100644 --- a/crates/ui-contract/src/layout/column_group.rs +++ b/crates/ui-contract/src/layout/column_group.rs @@ -1,4 +1,4 @@ -//! `ColumnGroup`: rows that are not one `Grid` share the widest label per column key. +//! `ColumnGroup`: rows share the widest label per column key: the rows of a scope, or the cells of one `Grid` column. use crate::runtime::layout_memory; use crate::runtime::memory::sub; @@ -129,6 +129,10 @@ enum Frame { Field, /// No group: rows inside read none, whatever group is open outside. Barrier, + /// A component in a cell of a grid: its rows read and report the group `group` of the cell's column, open further + /// out (`ColumnGroup::grid`). `sized`: the cell shows at the width it measures (a `Content` column), as a `sized` + /// `Through` frame's body does. + Cell { group: Id, sized: bool }, } /// Whether `column` is one the label step puts labels in. @@ -137,8 +141,9 @@ fn labels(column: &ColumnKey) -> bool { } impl Open { - /// The group a row in the innermost open frame reads `columns` from, and the frame its reaches past them go to; - /// `None` when no group is open, a barrier is, or a field's body is and `columns` holds a label column. + /// The group a row in the innermost open frame reads `columns` from (a grid cell's: its column's), and the frame + /// its reaches past them go to; `None` when no group is open, a barrier is, or a field's body is and `columns` + /// holds a label column. fn innermost(&self, columns: &[ColumnKey]) -> Option<(Id, Id)> { let mut frame = None; for open in self.0.iter().rev() { @@ -147,6 +152,7 @@ impl Open { Frame::Through { id, .. } => { frame.get_or_insert(*id); } + Frame::Cell { group, .. } => return Some((*group, frame.unwrap_or(*group))), Frame::Field if columns.iter().any(labels) => return None, Frame::Field => {} Frame::Barrier => return None, @@ -180,6 +186,32 @@ impl Reached { pub(crate) struct Scoped { pub(crate) extent: Option, pub(crate) unsettled: Option, + /// The group's widest width per column. + widths: Columns, +} + +/// The group of column `column` of the `Grid` body `grid`. +fn column_group(grid: Id, column: usize) -> Id { + sub(grid, ("labels", column)) +} + +/// Closes `frame`, a group a measuring run opened: records its widest width per column for the rows of the real run, +/// and returns what its rows found. Any other frame found nothing. +fn close(ctx: &Context, frame: Frame) -> Scoped { + let Frame::Group { id, widest, beyond, early, .. } = frame else { return Scoped::default() }; + let mut widths = HashMap::new(); + for (column, width) in widest { + // A row whose record a later sweep reused reports nothing there, so the widest of the pass stands. + let width = column_width(ctx, id, &column).map_or(width, |found| found.max(width)); + layout_memory::emit_record(ctx, sub(id, &column), layout_memory::Measured::new(Vec2::ZERO, Vec2::new(width, 0.0))); + widths.insert(column, width); + } + let extent = beyond + .iter() + .filter_map(|(columns, past)| columns.iter().map(|column| widths.get(column).copied()).sum::>().map(|sum| sum + past)) + .reduce(f32::max); + let early = early.iter().any(|(column, read)| widths.get(column).is_some_and(|width| width > read)); + Scoped { extent, unsettled: early.then(|| widths.clone()), widths } } /// The widest content per column key of one scope, measured through the same `LayoutMemory` rule as a `Grid` @@ -218,25 +250,64 @@ impl ColumnGroup { }); let mut group = ColumnGroup { id, ctx: ctx.clone() }; let result = rows(ui, &mut group); - let Some(Frame::Group { id, widest, beyond, early, .. }) = pass_state::with::(&ctx, |open| open.0.pop()) else { - return (result, Scoped::default()); - }; + let frame = pass_state::with::(&ctx, |open| open.0.pop()); + match frame { + Some(frame) if crate::runtime::measure::active(&ctx) => (result, close(&ctx, frame)), + _ => (result, Scoped::default()), + } + } + + /// Runs `cells`, the cells of the `Grid` body `grid` over `count` columns, with a group per column: the rows of a + /// cell read the group of the cell's column (`cell`), so the labels of one column share a width and its controls + /// start at one place. Code of the body outside a cell reads none. Each group opens at its `seed` widths. A + /// measuring run returns the groups' widths when a cell that shows at its measured width read a column narrower + /// than its group's final one: that cell's measure is wrong at these widths, and the caller runs the cells again + /// seeded with them. + pub(crate) fn grid( + ui: &mut Ui, + grid: Id, + count: usize, + seed: Option>, + cells: impl FnOnce(&mut Ui) -> R, + ) -> (R, Option>) { + let ctx = ui.ctx().clone(); + let depth = layout_memory::depth(&ctx); + let mut seed = seed.unwrap_or_default().into_iter(); + pass_state::with::(&ctx, |open| { + for column in 0..count { + let widest = seed.next().unwrap_or_default(); + open.0.push(Frame::Group { + id: column_group(grid, column), + widest, + beyond: HashMap::new(), + early: HashMap::new(), + room: None, + depth, + }); + } + open.0.push(Frame::Barrier); + }); + let result = cells(ui); + let groups = pass_state::with::(&ctx, |open| { + open.0.pop(); + let at = open.0.len().saturating_sub(count); + open.0.split_off(at) + }); if !crate::runtime::measure::active(&ctx) { - return (result, Scoped::default()); + return (result, None); } - let mut widths = HashMap::new(); - for (column, width) in widest { - // A row whose record a later sweep reused reports nothing there, so the widest of the pass stands. - let width = column_width(&ctx, id, &column).map_or(width, |found| found.max(width)); - layout_memory::emit_record(&ctx, sub(id, &column), layout_memory::Measured::new(Vec2::ZERO, Vec2::new(width, 0.0))); - widths.insert(column, width); - } - let extent = beyond - .iter() - .filter_map(|(columns, past)| columns.iter().map(|column| widths.get(column).copied()).sum::>().map(|sum| sum + past)) - .reduce(f32::max); - let early = early.iter().any(|(column, read)| widths.get(column).is_some_and(|width| width > read)); - (result, Scoped { extent, unsettled: early.then_some(widths) }) + let scoped: Vec = groups.into_iter().map(|frame| close(&ctx, frame)).collect(); + let unsettled = scoped.iter().any(|scoped| scoped.unsettled.is_some()); + (result, unsettled.then(|| scoped.into_iter().map(|scoped| scoped.widths).collect())) + } + + /// Runs `show`, a component shown in a cell of column `column` of the `Grid` body `grid`: its rows read the group + /// of that column (`grid`). `sized`: the cell shows at the width it measures. + pub(crate) fn cell(ctx: &Context, grid: Id, column: usize, sized: bool, show: impl FnOnce() -> R) -> R { + pass_state::with::(ctx, |open| open.0.push(Frame::Cell { group: column_group(grid, column), sized })); + let result = show(); + pass_state::with::(ctx, |open| open.0.pop()); + result } /// Runs `rows` with no group open: a labelled row inside reads no column, whatever group is open outside. The @@ -319,7 +390,7 @@ pub fn ambient_width(ctx: &Context, column: &ColumnKey, content: f32) -> Option< let mut sized = !labels(column); for frame in open.0.iter_mut().rev() { match frame { - Frame::Through { sized: through, .. } => sized |= *through, + Frame::Through { sized: through, .. } | Frame::Cell { sized: through, .. } => sized |= *through, Frame::Group { id, early, .. } if *id == group => { if sized { let read = early.entry(column.clone()).or_insert(width); diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index c897d6efb..3fcecd983 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,7 +24,7 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, in_grid_content_column, leaf_fill_room, - members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, - take_in_flow, view_room, + InFlow, close_first_line, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, grid_cell, in_grid_content_column, + leaf_fill_room, members_line, open_first_lines, place_in_cell, report_held, report_least, report_shrink, row_alone_room, run_body_measured, + shares_y, shrink_cap, take_in_flow, view_room, }; diff --git a/crates/ui-widgets/tests/it/layout/grid_labels.rs b/crates/ui-widgets/tests/it/layout/grid_labels.rs new file mode 100644 index 000000000..c16f2e331 --- /dev/null +++ b/crates/ui-widgets/tests/it/layout/grid_labels.rs @@ -0,0 +1,42 @@ +//! The glyph labels beside the fields of one grid column share a width. + +use craft_behavior::ColumnWidth; +use craft_ui::contract::{Bind, GlyphLabel, LabelKind, Show as _, ShowContainer as _, SideLabel}; +use craft_ui::form::Field; +use craft_ui::layout_components::Grid; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::NumberField; +use egui::Rect; +use std::cell::RefCell; +use std::rc::Rc; + +/// A column sized by its cells, then one that fills the rest. +static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::fill(1.0)]; + +/// The fields of each column of a grid start at one x, whatever the width of the glyph beside each: "I" and "W" +/// share the column's widest glyph. The narrow glyph comes first in the sized column, so its cell measures before the +/// column's widest glyph is known, and the column still holds both fields. Guards against a grid whose cells read no +/// shared label column, which set each field right after its own glyph. +#[trial] +fn the_fields_of_a_grid_column_share_a_left_edge() { + let rects: Rc>> = Rc::default(); + let seen = rects.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut seen = seen.borrow_mut(); + seen.clear(); + Grid::new(&COLUMNS).show(ui, |ui, _| { + for (i, glyph) in ["I", "W", "W", "I"].into_iter().enumerate() { + let side = SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(glyph))); + Field::new(format!("Field {i}")).side(side).show(ui, |ui, _| { + seen.push(NumberField::new(format!("Value {i}"), Bind::given(Some(10.0))).show(ui).response.rect); + }); + } + }); + }); + fixture.settle(); + let rects = rects.borrow(); + let [first, second, third, fourth] = rects[..] else { panic!("four fields show: {rects:?}") }; + assert!((first.left() - third.left()).abs() <= 0.5, "the sized column's fields share a left edge: {first:?}, {third:?}"); + assert!((second.left() - fourth.left()).abs() <= 0.5, "the filling column's fields share a left edge: {second:?}, {fourth:?}"); + assert!(first.right() <= second.left() && third.right() <= fourth.left(), "the sized column holds its fields: {rects:?}"); +} diff --git a/crates/ui-widgets/tests/it/layout/mod.rs b/crates/ui-widgets/tests/it/layout/mod.rs index ae6d0fd0c..ff427c664 100644 --- a/crates/ui-widgets/tests/it/layout/mod.rs +++ b/crates/ui-widgets/tests/it/layout/mod.rs @@ -2,6 +2,7 @@ mod cross_fill; mod fill_column; mod fill_share; mod fonts; +mod grid_labels; mod grid_least; mod nested; mod room_height;