From 5f0331fbff4b64f0507bb448a9fab043b4b87585 Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 12 Nov 2026 15:01:38 +0000 Subject: [PATCH] Row line: a one-line child sits on the row's line, a taller one at its top A child placed on an unwrapped row's line reports how far below its top the centre of its first line lies: half a control's height, a row body's line, or a container's first child's first line (its header's, else its body's), which its measuring run records. A child whose first line lies at half its height is one line (a control, a row of one-line children, a field with its label beside its control) and sits with its centre on the row's line, so a side-labelled field holding smaller controls centres them. A child of more than one line (a column, a field with its label above or a help line below) sits at the row's top, as does one with no line of its own (a collection whose rows run along Y), so columns beside each other share their tops. The row's line is the lowest centre of its one-line children, or of the line it shares with its container's inline regions; the row records the line's centre and its height, and takes that height in its measuring run. Replaces the line/block split, where every container sat at the row's top. --- crates/ui-contract/src/contract/body.rs | 4 + crates/ui-contract/src/contract/body/hooks.rs | 37 ++- crates/ui-contract/src/contract/body/size.rs | 2 +- .../ui-contract/src/contract/items/hooks.rs | 8 +- crates/ui-contract/src/contract/run.rs | 21 +- crates/ui-contract/src/contract/run/typed.rs | 4 +- crates/ui-contract/src/layout/body.rs | 224 ++++++++++++++---- crates/ui-contract/src/layout/mod.rs | 4 +- crates/ui-contract/src/runtime/env.rs | 26 +- .../ui-contract/src/runtime/layout_memory.rs | 2 + crates/ui-contract/src/runtime/pass_state.rs | 2 + crates/ui-widgets/tests/it/layout/mod.rs | 1 + crates/ui-widgets/tests/it/layout/row_line.rs | 120 ++++++++++ 13 files changed, 390 insertions(+), 65 deletions(-) create mode 100644 crates/ui-widgets/tests/it/layout/row_line.rs diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 632dfc4ae..768307947 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -111,6 +111,9 @@ pub(super) struct BodyHooks<'b> { footer_size: Option, end_size: Option, controls_size: Option, + /// How far below the container's top the centre of its first line lies, as its measuring run found it: the first + /// line of its header, else of its body. `None` for a container whose first child has no line of its own. + first_line: Option, /// How far the rows of a content-sized `Through` body reached past the group's columns in this measuring run, and /// whether the body is a row, for the container to hand on once its measure is known. reached: Option<(crate::layout::Reached, bool)>, @@ -192,6 +195,7 @@ impl<'b> BodyHooks<'b> { footer_size: None, end_size: None, controls_size: None, + first_line: None, reached: None, settle: None, unsettled: None, diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 42c59ece8..514f26be9 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -501,8 +501,10 @@ impl ShapeHooks for BodyHooks<'_> { self.sizing(comp.props(Internal::new())) == Sizing::FillWidth } - fn on_line(&self, comp: &C) -> bool { - matches!(comp.props(Internal::new()).layout, layout::BodyLayout::Row { wrap: false, .. }) + /// The first line this pass's measuring run found: its header's first child's, else its body's + /// (`layout::FirstLines`). + fn first_line(&self, _comp: &C, ctx: &Context, id: Id, _height: f32) -> Option { + layout_memory::measured(ctx, sub(id, "first")).map(|found| found.took.y) } fn member(&self, comp: &C) -> bool { @@ -666,6 +668,12 @@ impl ShapeHooks for BodyHooks<'_> { let mut gate = self.gate; let mut close: Option = None; let field_message = if props.label.is_some() { scope::last_message(&ctx, id) } else { None }; + // A measuring run finds the container's first line: the first child its header or body places in flow reports + // it (`layout::FirstLines`). + let (first_header, first_body) = (sub(id, "first_header"), sub(id, "first_body")); + if !real { + layout::open_first_lines(&ctx, &[first_header, first_body]); + } // B1 header if props.header.is_some() { let header_parts = Self::header_parts(comp, ui, env, cx); @@ -677,7 +685,9 @@ impl ShapeHooks for BodyHooks<'_> { .with_owner(owner); let trailing = props.header.is_some_and(|header| header.trailing); let inset = props.header.map_or(0.0, |header| pad_of(&env.tokens, header.inset)); - close = close.or(self.header_region(comp, ui, &mut bcx, &frame, regions.header, (trailing, inset, header_parts))); + let header_env = (!real).then(|| region_env.derive_local(|scoped| scoped.first_line = Some(first_header))); + let header_frame = RegionFrame { env: header_env.as_ref().unwrap_or(®ion_env), ..frame }; + close = close.or(self.header_region(comp, ui, &mut bcx, &header_frame, regions.header, (trailing, inset, header_parts))); for stop in after_header { crate::runtime::focus::register_stop(&ctx, stop); } @@ -766,6 +776,8 @@ impl ShapeHooks for BodyHooks<'_> { (body_rect, label_rect, caption) = (placed.control, placed.label, placed.caption); label_input = Some(input); } + // Where the body runs; a measuring run may move it once the control reported its minimum width. + let ran_top = body_rect.min.y; let label_extra = label_extra_of(regions.body, body_rect, label_rect, rtl); // The body's control shows an inside label in its slot, in the measuring run and the real run alike. let inside = props.label.as_ref().and_then(|side| label::inside(env.view(), side, cx.core.resolved.enabled)); @@ -777,6 +789,8 @@ impl ShapeHooks for BodyHooks<'_> { self.scope_body(scoped, &props, id, BodyScope { room, real, sizing, content_column, scroll, label_width, beside: regions.beside }); scoped.inside_label = inside; scoped.cell_fills = cell_fills; + // A scrolling body shows its first child wherever the view is: the container has no first line there. + scoped.first_line = (!real && scroll.is_none()).then_some(first_body); }); // B3 body, if open, under the body env; the gate is read after the header changed it. if is_open { @@ -995,6 +1009,9 @@ impl ShapeHooks for BodyHooks<'_> { scope::discard(&ctx, id); } } + if !real { + self.first_line = first_line_found(&ctx, (first_header, first_body), rect.min.y, body_rect.min.y - ran_top); + } // B4 footer: under the control column of a label-scoped container, which starts where the label step put // the control. if props.footer.is_some() { @@ -1152,6 +1169,17 @@ impl ShapeHooks for BodyHooks<'_> { } } +/// How far below the container's top `top` the centre of its first line lies, from what the first children placed in +/// its header and body reported (`targets`): the header's first line, else the body's, moved by `moved` with the body +/// after its run. `None` when the first child there has no line of its own, or nothing was placed. +fn first_line_found(ctx: &Context, (header, body): (Id, Id), top: f32, moved: f32) -> Option { + let (header, body) = (layout::close_first_line(ctx, header), layout::close_first_line(ctx, body)); + match header { + Some(found) => found.map(|y| y - top), + None => body.flatten().map(|y| y + moved - top), + } +} + 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. @@ -1222,6 +1250,9 @@ impl BodyHooks<'_> { } 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)); + if let Some(first) = self.first_line { + record(sub(id, "first"), Vec2::new(0.0, first)); + } 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); diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index fd2d460b9..5746f8c46 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -52,7 +52,7 @@ pub(crate) struct EnvFacts { given_column: bool, unbounded: (bool, bool), row_room: Option, - row_line: Option, + row_line: Option, offered: Option, measure: Option, grid: Option, diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 5b878af67..304d5b146 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -42,8 +42,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { true } - fn on_line(&self, comp: &C) -> bool { - comp.items().overflow == Axis::X + /// A collection whose rows run along X is one line; one whose rows run along Y has no line of its own. + fn first_line(&self, comp: &C, _ctx: &Context, _id: Id, height: f32) -> Option { + (comp.items().overflow == Axis::X).then_some(height / 2.0) } /// A collection that keeps focus on press senses the press without taking focus. @@ -420,6 +421,9 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { 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 offset = ScrollPos { x: self.offset_x, y: self.offset }; diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index f17c8256c..95d185735 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -137,10 +137,11 @@ pub(crate) trait ShapeHooks { comp.fills() == Some(craft_behavior::Axis::X) } - /// Whether the root is a line itself, which sits at the centre of a `Row`'s line, rather than a block or column, - /// which sits at its top. A leaf is a control on the line. - fn on_line(&self, _comp: &C) -> bool { - true + /// How far below the root's top the centre of its first line lies, at `height` tall: a root whose first line lies + /// at half its height is one line, which sits with its centre on a `Row`'s line; any other root sits at the + /// line's top. A leaf is one control on the line. + fn first_line(&self, _comp: &C, _ctx: &Context, _id: Id, height: f32) -> Option { + Some(height / 2.0) } /// Whether the root is one member of a bar's line, shown whole or not at all: a leaf is; a body is when it has a @@ -304,7 +305,7 @@ impl ShapeHooks for LeafHooks { // never sets that size. Across an unwrapped row's line it is shown across the line the row settled on in its // measuring run, where the child measured at its own size. let env = Env::of(ui); - let (content, line) = (env.content, env.row_line); + let (content, line) = (env.content, env.row_line.and_then(|line| line.height)); let fill = |measured: f32, offered: f32, content: bool, along: craft_behavior::Axis| { if content { return match (along, line) { @@ -562,7 +563,7 @@ pub(crate) trait ErasedPass<'a> { fn focus(&self) -> Option; fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2; fn fills_width(&self) -> bool; - fn on_line(&self) -> bool; + fn first_line(&self, ctx: &Context, id: Id, height: f32) -> Option; fn member(&self) -> bool; fn fills_width_only(&self) -> bool; fn arena(&self) -> bool; @@ -790,9 +791,10 @@ fn sense_root(ui: &Ui, member: Option, spec: RootS /// Step 6: the rect the root takes in `ui`, and whether it is a fill-width root held at its measured width. fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Vec2, inert: bool, rtl: bool) -> (Rect, bool) { + let (ctx, id) = (ui.ctx().clone(), p.resolved.id); + let first = |height: f32| p.p.first_line(&ctx, id, height); // In a content-sized column a fill-width child takes its measured width in the flow and shows across the width // the column settles on, so it never sets that width. - let line = p.p.on_line(); let held = !inert && matches!(at, ShowAt::Flow) && ((env.content_column && p.p.fills_width()) || (crate::layout::in_grid_content_column(ui) && p.p.fills_width_only())); @@ -803,12 +805,13 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve .then(|| crate::layout::flow_room(ui).x) .filter(|width| width.is_finite()) .unwrap_or(0.0); - let flowed = steps::place(ui, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, line }); + let flowed = steps::place(ui, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y) }); let across = Vec2::new(size.x.max(flowed.width()).max(column), flowed.height()); if rtl { Rect::from_min_size(Pos2::new(flowed.max.x - across.x, flowed.min.y), across) } else { Rect::from_min_size(flowed.min, across) } } else { let fill = p.p.fills_width() && !p.p.fills_width_only(); - steps::place(ui, at, if inert { Vec2::ZERO } else { size }, InFlow { fill, line }) + let size = if inert { Vec2::ZERO } else { size }; + steps::place(ui, at, size, InFlow { fill, first: first(size.y) }) }; (rect, held) } diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index c9038eb39..6dde04669 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -386,8 +386,8 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { self.hooks.fills_width(self.comp) } - fn on_line(&self) -> bool { - self.hooks.on_line(self.comp) + fn first_line(&self, ctx: &Context, id: Id, height: f32) -> Option { + self.hooks.first_line(self.comp, ctx, id, height) } fn member(&self) -> bool { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index ccd131ba3..00c966165 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -3,7 +3,7 @@ use crate::contract::InBar; use crate::runtime::egui::{alloc, child}; -use crate::runtime::env::{Env, Shrink}; +use crate::runtime::env::{Env, RowLine, Shrink}; use crate::runtime::layout_memory; use crate::runtime::measure; use crate::runtime::memory::sub; @@ -93,6 +93,65 @@ pub(crate) struct Cursors(HashMap); #[derive(Default)] pub(crate) struct FillCounts(HashMap); +/// What the first child a measuring sweep placed in flow in each open target reported (`Scoped::first_line`): the y +/// of its first line's centre, or `None` for a child with no line of its own. A container's measuring sweep opens and +/// closes its header's and body's targets; a body's sweep starts its own target afresh. +#[derive(Default)] +pub(crate) struct FirstLines(HashMap>); + +/// What the children of each unwrapped `Row` body took in the sweep of a measuring run running now, by body id. +#[derive(Default)] +pub(crate) struct RowLines(HashMap); + +/// What the children of a row took about its line. +#[derive(Clone, Copy, Default)] +pub(crate) struct LineTook { + /// The lowest centre among the one-line children, from their tops. + centre: Option, + /// How far the one-line children reach below their centre, at most. + below: f32, + /// The height of the tallest child of more than one line, or with no line of its own. + block: f32, +} + +impl LineTook { + fn add(&mut self, first: Option, height: f32) { + match first { + Some(first) => { + self.centre = Some(self.centre.map_or(first, |centre| centre.max(first))); + self.below = self.below.max(height - first); + } + None => self.block = self.block.max(height), + } + } + + /// The height of the row once every child sits on the line. + fn height(self) -> f32 { + self.centre.map_or(0.0, |centre| centre + self.below).max(self.block) + } +} + +/// Opens the first-line targets `targets` of a container's measuring sweep (`Scoped::first_line`). +pub(crate) fn open_first_lines(ctx: &egui::Context, targets: &[Id]) { + pass_state::with::(ctx, |lines| { + for target in targets { + lines.0.remove(target); + } + }); +} + +/// Closes `target`: what the first child placed in flow there reported, `None` when nothing was. +pub(crate) fn close_first_line(ctx: &egui::Context, target: Id) -> Option> { + pass_state::with::(ctx, |lines| lines.0.remove(&target)) +} + +/// Reports a child's first line `at` to `target`, unless an earlier child of the sweep did. +fn report_first_line(ctx: &egui::Context, target: Id, at: Option) { + pass_state::with::(ctx, |lines| { + lines.0.entry(target).or_insert(at); + }); +} + /// How a child that fills the main axis of the body it sits in sizes along it. pub(crate) enum MainFill { /// The body is being measured: the child takes no room along the axis and is counted. @@ -549,37 +608,69 @@ impl Spread { pub(crate) struct InFlow { /// Whether the child fills its cell's height in a `Grid` (declares `Sizing::Fill`). pub fill: bool, - /// Whether the child is a line itself: a control, a `Row` body that does not wrap, or a collection whose rows run - /// along X. Anything else is a block or a column. - pub line: bool, + /// How far below the child's top the centre of its first line lies: half a control's height, a container's + /// first child's first line, a `Row` body's line. `None` for a child with no line of its own: a collection whose + /// rows run along Y, or a container whose first child is one. The child is one line when that centre lies at + /// half its height (`one_line`). + pub first: Option, } -impl InFlow { - /// A control on the line that does not fill its cell. - pub const LINE: InFlow = InFlow { fill: false, line: true }; +/// How far a one-line child's first-line centre may lie from half its height: half a pixel at the scales the box runs. +const ONE_LINE_SLACK: f32 = 0.5; + +/// The centre of the line of a child `height` tall whose first line's centre lies `first` below its top, when the +/// child is one line: a control, a row of one-line children, a container around one line (a field with its label +/// beside its control). A child of more than one line (a column, a field with its label above or a help line below) +/// has its first line above its middle. +fn one_line(first: Option, height: f32) -> Option { + first.filter(|first| (2.0 * first - height).abs() <= ONE_LINE_SLACK) } /// The rect a child of measured `size` takes in flow in `ui`: the next cell of the `Grid` or spread `Row` body that -/// encloses it directly, else the next allocation of `ui`'s layout. A direct child of an unwrapped `Row` takes the -/// row's line: a line sits at its vertical centre, a block or column at its top. In a `Grid` cell a child that -/// `fill`s takes the cell's whole height from the cell's top, so the cards of one row share their top and bottom -/// edges; any other child sits at the vertical centre of its cell. +/// encloses it directly, else the next allocation of `ui`'s layout. A direct child of an unwrapped `Row` that is one +/// line sits with its centre on the row's line; a child of more than one line (a column, a field with a help line) +/// sits at the row's top. In a `Grid` cell a child that `fill`s takes the +/// cell's whole height from the cell's top, so the cards of one row share their top and bottom edges; any other child +/// sits at the vertical centre of its cell. #[doc(hidden)] pub fn place_in_flow(ui: &mut Ui, size: Vec2) -> Rect { - place_in_cell(ui, size, InFlow::LINE) + place_in_cell(ui, size, InFlow { fill: false, first: Some(size.y / 2.0) }) } -/// `place_in_flow` for a child that is `child`. +/// `place_in_flow` for a child that is `child`. In a measuring run the child reports its line to the row around it +/// and its first line to the container whose header or body it starts. pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let env = Env::of(ui); - let slot = Vec2::new(size.x, env.row_line.map_or(size.y, |line| line.max(size.y))); + let (line, target) = (env.row_line, env.first_line); + let child = InFlow { first: one_line(child.first, size.y), ..child }; + let above = line.and_then(|line| line.centre).zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); + let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y))); let (rect, in_cell) = take_in(ui, env.grid, slot); - if child.fill && in_cell { - return rect; + let placed = if child.fill && in_cell { + rect + } else { + let (above, below) = match line { + Some(_) => (above, (rect.height() - above - size.y).max(0.0)), + None => { + let spare = (rect.height() - size.y).max(0.0); + (spare / 2.0, spare / 2.0) + } + }; + Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) + }; + if measure::active(ui.ctx()) { + if let Some(line) = line { + pass_state::with::(ui.ctx(), |rows| { + if let Some(took) = rows.0.get_mut(&line.body) { + took.add(child.first, size.y); + } + }); + } + if let Some(target) = target { + report_first_line(ui.ctx(), target, child.first.map(|first| placed.min.y + first)); + } } - let spare = (rect.height() - size.y).max(0.0); - let (above, below) = if env.row_line.is_some() && !child.line { (0.0, spare) } else { (spare / 2.0, spare / 2.0) }; - Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) + placed } /// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the @@ -799,24 +890,62 @@ fn this_pass(ctx: &egui::Context, sizing: bool, id: Id) -> Option { if sizing { None } else { layout_memory::measured(ctx, id).map(|found| found.took) } } -/// The line of the unwrapped `Row` body `id`: the height of its tallest child in this pass's measuring run. -fn row_line(ctx: &egui::Context, sizing: bool, id: Id) -> Option { - this_pass(ctx, sizing, sub(id, "line")).map(|took| took.y).filter(|line| *line > 0.0) +/// The line of the unwrapped `Row` body `id` in this pass's measuring run, with the line it shares already in it: how +/// far below its top the line's centre lies, and the row's height once its children sit on it. +fn row_line(ctx: &egui::Context, sizing: bool, id: Id) -> Option<(f32, f32)> { + this_pass(ctx, sizing, sub(id, "line")).map(|took| (took.x, took.y)).filter(|(_, height)| *height > 0.0) } -/// The line an unwrapped `Row` sets its children on: its own, or the line it shares with its container's regions -/// when that is taller. -fn on_line(own: Option, shared: Option) -> Option { - match (own, shared) { - (Some(own), Some(shared)) => Some(own.max(shared)), - (own, shared) => own.or(shared), +/// The line the unwrapped `Row` body `body` sets its children on: its own (`centre`, `height`), or the line `shared` +/// high it shares with its container's inline header or end region, centred, when that centre is lower. +fn on_line(body: Id, own: Option<(f32, f32)>, shared: Option) -> RowLine { + let (centre, height) = match (own, shared) { + (Some((centre, height)), Some(shared)) => { + let line = centre.max(shared / 2.0); + (Some(line), Some((height + line - centre).max(shared))) + } + (Some((centre, height)), None) => (Some(centre), Some(height)), + (None, Some(shared)) => (Some(shared / 2.0), Some(shared)), + (None, None) => (None, None), + }; + RowLine { body, centre, height } +} + +/// Starts a sweep of a body's children in a measuring run: the body's first-line `target` and, for the unwrapped +/// `Row` body `row`, its line start afresh. +fn open_sweep(ctx: &egui::Context, target: Option, row: Option) { + if let Some(target) = target { + open_first_lines(ctx, &[target]); + } + if let Some(row) = row { + pass_state::with::(ctx, |rows| rows.0.insert(row, LineTook::default())); } } -/// Records the line of the unwrapped `Row` body `id` from what its children took in `ui`, the block they ran in; a -/// real run records nothing. The last sweep of a measuring run gives the line. -fn record_line(ui: &Ui, sizing: bool, id: Id) { - found(ui.ctx(), sizing, sub(id, "line"), Vec2::ZERO, Vec2::new(0.0, ui.min_rect().height())); +/// Records the line of the unwrapped `Row` body `id` from what its children took in `ui`, the block they ran in, +/// with the line `shared` it shares with its container's regions; a real run records nothing. The last sweep of a +/// measuring run gives the line. The block takes the row's height once its children sit on the line, and the row +/// reports its line to the target its body reports a first line to. +fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option) { + if !sizing { + return; + } + let ctx = ui.ctx().clone(); + let took = pass_state::with::(&ctx, |rows| rows.0.remove(&id)).unwrap_or_default(); + let own = (took.height() > 0.0).then(|| (took.centre.unwrap_or(0.0), took.height())); + let line = on_line(id, own, shared); + // What a child took without reporting its line still counts toward the row's height. + let height = line.height.unwrap_or(0.0).max(ui.min_rect().height()); + let centre = line.centre.unwrap_or(0.0); + found(&ctx, sizing, sub(id, "line"), Vec2::ZERO, if height > 0.0 { Vec2::new(centre, height) } else { Vec2::ZERO }); + if height <= 0.0 { + return; + } + let top = ui.max_rect().top(); + alloc::reach_down_to(ui, top + height); + if let Some(target) = Env::of(ui).first_line { + report_first_line(&ctx, target, took.centre.map(|_| top + centre)); + } } /// Records what a measuring run found under `id`; a real run records nothing. @@ -852,6 +981,13 @@ pub(crate) fn run_body_measured( let rtl = env.direction.is_rtl(); let ctx = ui.ctx().clone(); let sizing = measure::active(&ctx); + // Each sweep of a measuring run finds the body's first line and an unwrapped row's line afresh. + let target = env.first_line.filter(|_| sizing); + let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id); + let mut body = |ui: &mut Ui| { + open_sweep(&ctx, target, row); + body(ui) + }; match layout { BodyLayout::Stack => { // Each leaf shows at most the stack's room, never below its least. @@ -866,17 +1002,18 @@ pub(crate) fn run_body_measured( let flow = Flow::new(ui.available_rect_before_wrap(), rtl); let spread = Spread::new(flow, gap.x, this_pass(&ctx, sizing, id)); pass_state::with::(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(spread))); - let line = on_line(row_line(&ctx, sizing, id), shared); + let line = on_line(id, row_line(&ctx, sizing, id), shared); let installed = Env::install_for( ui, env.derive_local(|scoped| { scoped.grid = Some(id); - scoped.row_line = line; + scoped.row_line = Some(line); + scoped.first_line = None; }), ); let inner = body(ui); Env::restore(&ctx, installed); - record_line(ui, sizing, id); + record_line(ui, sizing, id, shared); inner }); let measured = match pass_state::with::(&ctx, |cursors| cursors.0.remove(&id)) { @@ -890,18 +1027,19 @@ pub(crate) fn run_body_measured( } BodyLayout::Row { wrap: false, align: RowAlign::Start } => { let room = ui.available_rect_before_wrap(); - let line = on_line(row_line(&ctx, sizing, id), shared); + let line = on_line(id, row_line(&ctx, sizing, id), shared); let inner = run_sharing(ui, env, id, Axis::X, child::row_layout(rtl, false), |ui| { let installed = Env::install_for( ui, Env::of(ui).derive_local(|scoped| { scoped.row_room = Some(room.width()); - scoped.row_line = line; + scoped.row_line = Some(line); + scoped.first_line = None; }), ); let inner = run_shrinking(ui, id, &mut body); Env::restore(&ctx, installed); - record_line(ui, sizing, id); + record_line(ui, sizing, id, shared); inner }); (inner, None) @@ -922,20 +1060,24 @@ pub(crate) fn run_body_measured( }) } }; - // A wrapped row has a line per wrap, so its children stay on the top of each. - let line = if *wrap { None } else { on_line(row_line(&ctx, sizing, id), shared) }; + // A wrapped row has a line per wrap, so its children stay on the top of each, and its first child gives its + // first line. + let line = (!*wrap).then(|| on_line(id, row_line(&ctx, sizing, id), shared)); let (inner, took) = child::block(ui, rect, child::row_layout(rtl, *wrap), |ui| { let installed = Env::install_for( ui, env.derive_local(|scoped| { scoped.row_room = Some(room.width()); scoped.row_line = line; + if line.is_some() { + scoped.first_line = None; + } }), ); let inner = if *wrap { body(ui) } else { run_shrinking(ui, id, &mut body) }; Env::restore(&ctx, installed); if !*wrap { - record_line(ui, sizing, id); + record_line(ui, sizing, id, shared); } inner }); diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 75c2eebe4..359df6137 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -22,6 +22,6 @@ pub(crate) use crate::runtime::env::Shrink; #[doc(hidden)] pub use body::place_in_flow; pub(crate) use body::{ - InFlow, MainFill, counting_fills, fill_share, flow_fill_room, flow_region, flow_room, in_grid_content_column, leaf_fill_room, main_fill, - place_in_cell, report_least, report_shrink, row_alone_room, run_body, run_body_measured, shrink_cap, take_in_flow, + InFlow, MainFill, close_first_line, counting_fills, fill_share, flow_fill_room, flow_region, flow_room, in_grid_content_column, leaf_fill_room, + main_fill, open_first_lines, place_in_cell, report_least, report_shrink, row_alone_room, run_body, run_body_measured, shrink_cap, take_in_flow, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index a0423d9ae..b4efe1c00 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -116,11 +116,11 @@ pub struct Scoped { /// The width a `Row` body was offered this pass, before its `End` or `Center` lead narrowed the block: the room /// its direct children share. Only the row's own children read it. pub(crate) row_room: Option, - /// The line of an unwrapped `Row` body: the height of its tallest child in this pass's measuring run, or the line - /// the body shares with its container's inline header or end region when that is taller. Its direct children - /// placed in flow that are lines sit at the line's vertical centre, blocks and columns at its top. `None` while a - /// row that shares no line is measured. - pub(crate) row_line: Option, + /// The line of the unwrapped `Row` body whose direct children the scope places in flow (`RowLine`). + pub(crate) row_line: Option, + /// Where the first child the scope places in flow reports its first line: a container's header or body + /// (`layout::FirstLines`). `None` in the children of a `Row` body, which reports its line itself. + pub(crate) first_line: Option, /// The `Stack` or `Row` body that encloses the scope and the axis it runs along, when a child that fills that /// axis shares the room its siblings leave (set only where the body is given the axis). pub(crate) fill_body: Option<(Id, craft_behavior::Axis)>, @@ -236,6 +236,20 @@ pub(crate) enum Shrink { Fit, } +/// The line of an unwrapped `Row` body, as its direct children placed in flow see it: a child of one line sits with +/// its centre on the line's centre, and a child of more than one line, or with no line of its own, at its top. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct RowLine { + /// The row body, which the children of a measuring run report their lines to. + pub(crate) body: Id, + /// How far below the row's top the line's centre lies: the lowest centre among its one-line children in this + /// pass's measuring run, or that of the line the body shares with its container's inline header or end region + /// when lower. `None` while a row that shares no line is measured. + pub(crate) centre: Option, + /// The row's height once its children sit on the line, at least the shared line's. `None` with `centre`. + pub(crate) height: Option, +} + /// What a collection records for one of its items in a pass: the row flags the item folds into its state (step 12) /// and its place in the set (step 16). The collection owns the record; a component reads it from its env. #[derive(Clone, Debug)] @@ -323,6 +337,7 @@ impl Scoped { self.content = (false, false); self.row_room = None; self.row_line = None; + self.first_line = None; self.fill_body = None; self.fill_share = None; self.shrink = None; @@ -443,6 +458,7 @@ impl Env { content: (false, false), row_room: None, row_line: None, + first_line: None, fill_body: None, fill_share: None, shrink: None, diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 0bac70771..304d01730 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1128,6 +1128,8 @@ pub(crate) mod guard { ("layout::column_group::Open", "column groups: frames the run opens and closes; reports go through contribute"), ("access::scope::Stack", "label and merge scopes: opened and closed by the run; control minimums go through contribute"), ("layout::body::FillCounts", "fill counts: opened and closed by the body's own measuring sweep"), + ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), + ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), ("layout::body::Cursors", "grid and spread cursors: opened and closed by the body's own run"), ("layout::body::ShrinkReports", "shrink reports: opened and closed by the row's own first sweep; the widths go through emit_record"), ("layout::body::LeastReports", "least reports: opened and closed by the row's own least sweep; the widths go through emit_record"), diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index cb8eb44c0..1812a2c3e 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -92,6 +92,8 @@ pass_state! { least_reports: crate::layout::body::LeastReports, bar_rules: crate::contract::BarRules, fill_counts: crate::layout::body::FillCounts, + first_lines: crate::layout::body::FirstLines, + row_lines: crate::layout::body::RowLines, cursors: crate::layout::body::Cursors, column_groups: crate::layout::column_group::Open, popups: crate::contract::overlay::popups::Popups, diff --git a/crates/ui-widgets/tests/it/layout/mod.rs b/crates/ui-widgets/tests/it/layout/mod.rs index 25087a6fc..43a0f4099 100644 --- a/crates/ui-widgets/tests/it/layout/mod.rs +++ b/crates/ui-widgets/tests/it/layout/mod.rs @@ -5,6 +5,7 @@ mod fonts; mod grid_least; mod nested; mod room_height; +mod row_line; mod row_room; mod rtl_scroll; mod scroll_region; diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs new file mode 100644 index 000000000..538ff2eff --- /dev/null +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -0,0 +1,120 @@ +//! The row line: a child of an unwrapped row that is one line sits with its centre on the row's line; a child of more +//! than one line (a column, a field with its label above or a help line below) sits at the row's top. + +use craft_theme::ControlSize; +use craft_ui::buttons::Button; +use craft_ui::contract::{FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::display::Text; +use craft_ui::form::{Field, Help}; +use craft_ui::layout_components::{Row, Stack}; +use craft_ui::runtime::env::Label; +use craft_ui::testing::{Fixture, last_pass_measuring_runs, trial}; +use egui::Rect; + +/// Half a pixel at the scales the box runs. +const ROUNDING: f32 = 0.5; + +fn settled(content: impl FnMut(&mut egui::Ui) + 'static) -> Fixture { + let mut fixture = Fixture::new(content); + fixture.settle(); + fixture.idle(3); + fixture +} + +/// The rect of the control named by any of `names` (a field's control takes the field's label as its name). +fn control(fixture: &Fixture, names: &[&str]) -> Rect { + names.iter().find_map(|name| fixture.by_label(name)).unwrap_or_else(|| panic!("none of {names:?}")).rect +} + +fn text(fixture: &Fixture, text: &str) -> Rect { + fixture.texts().iter().find(|painted| painted.text == text).unwrap_or_else(|| panic!("no {text} painted")).rect +} + +/// A side-labelled field holding a row of small buttons beside one holding a standard button (the Layers panel's +/// Lock and Fill): the controls share a centre line. A settled frame runs no measuring run. +#[trial] +fn fields_of_different_heights_in_a_row_share_a_centre_line() { + let fixture = settled(|ui| { + Row::new().show(ui, |ui, _| { + Field::new("Lock").sizing(Sizing::Content).show(ui, |ui, _| { + Row::new().show(ui, |ui, _| { + Button::new("A").size(ControlSize::Sm).show(ui); + Button::new("B").size(ControlSize::Sm).show(ui); + }); + }); + Field::new("Fill").sizing(Sizing::Content).show(ui, |ui, _| { + Button::new("Go").show(ui); + }); + }); + }); + let (small, standard) = (control(&fixture, &["A"]), control(&fixture, &["Go", "Fill"])); + assert!(small.height() < standard.height(), "the small button {small:?} is shorter than {standard:?}"); + // A button's text sits at its centre. + let (small, standard) = (text(&fixture, "A"), text(&fixture, "Go")); + assert!((small.center().y - standard.center().y).abs() <= ROUNDING, "small {small:?}, standard {standard:?}"); + assert!(last_pass_measuring_runs(fixture.ctx()).is_empty(), "a settled frame measured"); +} + +/// A field showing a help line is two lines and sits at the row's top, beside a one-line field as tall as its control +/// and label: the controls share a centre line and the help hangs below. +#[trial] +fn a_help_line_hangs_below_its_control_on_the_row_line() { + let fixture = settled(|ui| { + Row::new().show(ui, |ui, _| { + Field::new("Width").help(Help::Text(Label::from("At least 1 px"))).sizing(Sizing::Content).show(ui, |ui, _| { + Button::new("W").show(ui); + }); + Field::new("Height").sizing(Sizing::Content).show(ui, |ui, _| { + Button::new("H").show(ui); + }); + }); + }); + let (width, height) = (text(&fixture, "W"), text(&fixture, "H")); + assert!((width.center().y - height.center().y).abs() <= ROUNDING, "with help {width:?}, without {height:?}"); + assert!(text(&fixture, "At least 1 px").top() > width.bottom(), "the help line sits under its control"); +} + +/// Columns of more than one line share the row's top (a style list beside a page), and the one-line children (a +/// column of one text, a button) share the line. +#[trial] +fn columns_sit_at_the_rows_top_and_lines_on_the_line() { + let fixture = settled(|ui| { + Row::new().show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + Text::new("Short").show(ui); + }); + Stack::new().show(ui, |ui, _| { + Text::new("A").show(ui); + Text::new("B").show(ui); + }); + Stack::new().show(ui, |ui, _| { + for line in ["One", "Two", "Three", "Four"] { + Text::new(line).show(ui); + } + }); + Button::new("Go").show(ui); + }); + }); + let (two, four) = (text(&fixture, "A"), text(&fixture, "One")); + assert!((two.top() - four.top()).abs() <= ROUNDING, "two-line column at {}, four-line column at {}", two.top(), four.top()); + let (short, button) = (text(&fixture, "Short"), text(&fixture, "Go")); + assert!((short.center().y - button.center().y).abs() <= ROUNDING, "one-line column {short:?}, button {button:?}"); + assert!(four.top() <= control(&fixture, &["Go"]).top() + ROUNDING, "the four-line column starts below the button's top"); +} + +/// A field labelled above its control is two lines and sits at the row's top, so a button beside it sits level with +/// the label, not the control. +#[trial] +fn a_field_labelled_above_sits_at_the_rows_top() { + let fixture = settled(|ui| { + Row::new().show(ui, |ui, _| { + Field::new("Caption").layout(FieldLayout::Above).sizing(Sizing::Content).show(ui, |ui, _| { + Button::new("X").show(ui); + }); + Button::new("Y").show(ui); + }); + }); + let (caption, control, button) = (text(&fixture, "Caption"), text(&fixture, "X"), text(&fixture, "Y")); + assert!(caption.bottom() < control.top(), "the label sits above its control"); + assert!(button.center().y < control.top(), "the button {button:?} sits level with the label, above the control {control:?}"); +}