From afd18d148d0be00f4ad5d5f9d08dd3a15df63886 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sun, 29 Nov 2026 10:45:53 -0800 Subject: [PATCH] ui-contract: a labeled row runs no second pass on its first appearance A label lines up with its control's first baseline, which the control records only after it has run. On a row's first appearance the label had no recorded baseline, so it was placed at the control's top and the frame ran a discard pass to move it down. Every frame that showed a new labeled row, such as a form gaining a field, ran twice. The label step now notes the last baseline recorded for each control size. A row with no baseline of its own places its label by that one, and its control's baseline is compared with it when it records: a control whose text sits elsewhere still asks for the discard pass. A memoized view that replays its rows keeps the noted baseline. --- .../ui-contract/src/contract/label/place.rs | 5 +- crates/ui-contract/src/contract/label/step.rs | 4 +- crates/ui-contract/src/layout/label.rs | 51 +++++--- crates/ui-contract/src/layout/mod.rs | 1 + .../ui-contract/src/runtime/access/scope.rs | 10 +- .../ui-contract/src/runtime/layout_memory.rs | 64 +++++++++- crates/ui-widgets/tests/it/label/baseline.rs | 110 ++++++++++++++++++ 7 files changed, 223 insertions(+), 22 deletions(-) diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index 7b972ba76d..801737cb75 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -27,7 +27,7 @@ pub(crate) struct Placed { /// The `After` placement: the control's cell first, then the gap, then the label. A leaf control (a box, circle or /// track has no text baseline) and its label are centred on each other across the row. For a field's control, as in /// `LabelColumn::place`, the one with the lower baseline moves down so the two baselines line up, using the baseline -/// `record_control_baseline` stored last pass. +/// `record_control_baseline` stored last pass (`control_baseline`). fn place_after(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flow, gap: f32, label: Vec2, label_baseline: f32, first_line: f32) -> Placed { let rtl = flow.is_rtl(); let (control_cell, rest) = flow.take_start(input.control_min.min(flow.rect().width())); @@ -41,7 +41,7 @@ fn place_after(ctx: &egui::Context, input: &LabelIn<'_>, flow: Flow, gap: f32, l let control = control_cell.translate(Vec2::new(0.0, (line - control_cell.height()) / 2.0)); return Placed { label, control, trailing: Rect::NOTHING, caption: 0.0 }; } - let control_baseline = crate::layout::control_baseline(ctx, input.scope, label, label_baseline); + let control_baseline = crate::layout::control_baseline(ctx, input.scope, input.size, label, label_baseline); let drop = control_baseline.map_or(0.0, |control| control - label_baseline); let (label_drop, control_drop) = (drop.max(0.0), (-drop).max(0.0)); let label_size = Vec2::new(label_width, label.y); @@ -193,6 +193,7 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let placed = crate::layout::place_label( kids, input.scope, + input.size, &LabelColumn::new(column, if stacks { f32::INFINITY } else { 0.0 }, gap), flow, natural.min(Vec2::new(column, natural.y)), diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index b34598318c..4c926618d3 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -299,7 +299,7 @@ fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: let Decided { placed, leaf, .. } = decided; let Some(DecidedLeaf { leaf, mut kids, installed, reset }) = leaf else { scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING).shown(false))); - scope::place_controls(&ctx, input.scope, placed.control.top()); + scope::place_controls(&ctx, input.scope, placed.control.top(), input.size); return placed; }; let slot = if reset.is_some() && input.side.reset_dot { env.tokens.size.handle.sm } else { 0.0 }; @@ -326,7 +326,7 @@ fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: .activated(shown.activated && !linked) .linked(shown.activated && linked); scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(label)); - scope::place_controls(&ctx, input.scope, placed.control.top()); + scope::place_controls(&ctx, input.scope, placed.control.top(), input.size); if input.claims { scope::offer_claim(&ctx, unslotted.rect()); } diff --git a/crates/ui-contract/src/layout/label.rs b/crates/ui-contract/src/layout/label.rs index 2c8f743d41..94dfd9e2d0 100644 --- a/crates/ui-contract/src/layout/label.rs +++ b/crates/ui-contract/src/layout/label.rs @@ -3,26 +3,49 @@ use crate::runtime::layout_memory; use crate::runtime::memory::sub; use craft_behavior::{Flow, LabelColumn, LabelPlacement}; +use craft_theme::ControlSize; use egui::{Id, Ui, Vec2}; -/// Places a label of `label` size with baseline `label_baseline` and the control of the row `id` in `flow`'s -/// rect. The label's baseline follows the control baseline `record_control_baseline` stored last pass; on the -/// first appearance the tops align and the missing entry asks for one discard pass. -pub fn place_label(ui: &Ui, id: Id, column: &LabelColumn, flow: Flow, label: Vec2, label_baseline: f32) -> LabelPlacement { - let control_baseline = control_baseline(ui.ctx(), id, label, label_baseline); +/// Places a label of `label` size with baseline `label_baseline` and the control of `size` of the row `id` in `flow`'s +/// rect. The label's baseline follows the control baseline `record_control_baseline` stored last pass. On the row's +/// first appearance it follows the baseline the last control of `size` stored, and a control whose baseline differs +/// from that asks for one discard pass; where none is stored the tops align and the missing entry asks for one. +pub fn place_label(ui: &Ui, id: Id, size: ControlSize, column: &LabelColumn, flow: Flow, label: Vec2, label_baseline: f32) -> LabelPlacement { + let control_baseline = control_baseline(ui.ctx(), id, size, label, label_baseline); column.place(flow, label, label_baseline, control_baseline) } -/// Stores the distance from the top of the control of the row `id` to its first baseline, for the next -/// pass's `place_label`. -pub fn record_control_baseline(ui: &Ui, id: Id, baseline: f32) { - layout_memory::record(ui.ctx(), sub(id, "baseline"), Vec2::new(0.0, baseline)); +/// Stores the distance from the top of the control of `size` of the row `id` to its first baseline, for the next +/// pass's `place_label`, and for the first appearance of later rows with a control of `size`. +pub fn record_control_baseline(ui: &Ui, id: Id, size: ControlSize, baseline: f32) { + record_baseline(ui.ctx(), id, Some(size), baseline); } -/// The control's first baseline from its top, as `record_control_baseline` stored it last pass. A control that paints -/// no text stored its centre line instead; the label's baseline then sits where its text is centred on that line. -pub fn control_baseline(ctx: &egui::Context, id: Id, label: Vec2, label_baseline: f32) -> Option { - layout_memory::read(ctx, sub(id, "baseline")) +/// `record_control_baseline` for the control of the row `id`; `size`: the control's size, when the row's label step +/// knows it. +pub(crate) fn record_baseline(ctx: &egui::Context, id: Id, size: Option, baseline: f32) { + layout_memory::record(ctx, sub(id, "baseline"), Vec2::new(0.0, baseline)); + if let Some(size) = size { + layout_memory::note_typical(ctx, baseline_kind(size), Vec2::new(0.0, baseline)); + } +} + +/// The first baseline of the control of `size` of the row `id`, from its top, as `record_control_baseline` stored it +/// last pass. A control that paints no text stored its center line instead; the label's baseline then sits where its +/// text is centered on that line. A row that stored neither (on its first appearance) takes the baseline the last +/// control of `size` stored before this pass, and its own baseline is compared with that one when it records. +pub fn control_baseline(ctx: &egui::Context, id: Id, size: ControlSize, label: Vec2, label_baseline: f32) -> Option { + let own = layout_memory::read(ctx, sub(id, "baseline")) .map(|size| size.y) - .or_else(|| layout_memory::read(ctx, sub(id, "centre")).map(|size| size.y + label_baseline - label.y / 2.0)) + .or_else(|| layout_memory::read(ctx, sub(id, "centre")).map(|size| size.y + label_baseline - label.y / 2.0)); + own.or_else(|| { + let typical = layout_memory::typical(ctx, baseline_kind(size))?; + layout_memory::assume(ctx, sub(id, "baseline"), typical); + Some(typical.y) + }) +} + +/// The key the baselines of the controls of `size` are noted under. +fn baseline_kind(size: ControlSize) -> Id { + crate::runtime::memory::unique(("label control baseline", size)) } diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 56f35ae858..7912e0af94 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -14,6 +14,7 @@ pub use column_group::ambient_width; #[doc(hidden)] pub use column_group::report_beyond; pub(crate) use column_group::{Columns, GLYPHS, LABELS, Reached, ambient_room, note_beside}; +pub(crate) use label::record_baseline; pub use label::{control_baseline, place_label, record_control_baseline}; pub use slot::measure_slot; diff --git a/crates/ui-contract/src/runtime/access/scope.rs b/crates/ui-contract/src/runtime/access/scope.rs index f1409fc0f9..8e798bbed5 100644 --- a/crates/ui-contract/src/runtime/access/scope.rs +++ b/crates/ui-contract/src/runtime/access/scope.rs @@ -155,6 +155,8 @@ struct Scope { /// The screen y of the top of the rect the label step placed the controls in; the recorded baseline and centre /// are stored measured from it. control_top: f32, + /// The size of the controls the label step placed: the recorded baseline is also noted for rows of that size. + control_size: Option, /// The screen y of the bottom of the first control that reported its line: the label's line is that control's. first_bottom: Option, /// The screen y of the first baseline of the first control on the first line. @@ -247,6 +249,7 @@ pub(crate) fn begin(ctx: &Context, container: Id, owner: Id, kind: Kind) { nodes: Vec::new(), open: Vec::new(), control_top: 0.0, + control_size: None, first_bottom: None, baseline: None, centre: None, @@ -338,11 +341,12 @@ fn report_unnamed(ctx: &Context, unnamed: Option) { /// Sets the screen y of the top of the rect the label step of `container` placed its controls in. The label lines up /// with a baseline measured from there: a control that sits lower in that rect (a short piece a row centres beside a -/// taller one) reports a baseline further down. -pub(crate) fn place_controls(ctx: &Context, container: Id, top: f32) { +/// taller one) reports a baseline further down. `size` is the size of the controls. +pub(crate) fn place_controls(ctx: &Context, container: Id, top: f32, size: craft_theme::ControlSize) { pass_state::with::(ctx, |stack| { if let Some(scope) = stack.0.iter_mut().rev().find(|scope| scope.container == container && matches!(scope.kind, Kind::Label(_))) { scope.control_top = top; + scope.control_size = Some(size); } }); } @@ -703,7 +707,7 @@ pub(crate) fn finish(ctx: &Context, container: Id, merged: Option) { crate::runtime::focus::request(ctx, only.inner_stop.unwrap_or(crate::runtime::focus::FocusTarget::Id(only.id))); } if let Some(baseline) = scope.baseline { - layout_memory::record(ctx, sub(scope.container, "baseline"), Vec2::new(0.0, baseline - scope.control_top)); + crate::layout::record_baseline(ctx, scope.container, scope.control_size, baseline - scope.control_top); } if let (None, Some(centre)) = (scope.baseline, scope.centre) { layout_memory::record(ctx, sub(scope.container, "centre"), Vec2::new(0.0, centre - scope.control_top)); diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 51a98f0558..6021e1279a 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -232,9 +232,21 @@ struct Scope { reported: Vec<(Id, f32)>, } +/// The size the last block of a kind recorded (`note_typical`): what a pass reads, and what this pass's real runs +/// recorded for the passes after it. +#[derive(Clone, Copy, Debug, Default)] +struct Typical { + now: Option, + next: Option, + /// The last frame that recorded it. + touched: u64, +} + #[derive(Default)] pub(crate) struct Entries { entries: IdMap, + /// By kind, the size the blocks of that kind recorded last (`typical`). + typical: IdMap, measured: IdMap, kept: IdMap, /// The bodies whose records a kept transcript gave in this pass, with that transcript. @@ -494,6 +506,47 @@ pub(crate) fn record(ctx: &Context, id: Id, real: Vec2) { }); } +/// The size a block of `kind` recorded last ([`note_typical`]) before this pass. Every run of a pass reads the same +/// value: what a real run notes in this pass serves from the next pass on. +pub(crate) fn typical(ctx: &Context, kind: Id) -> Option { + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| memory.typical.get(&kind).and_then(|typical| typical.now)) +} + +/// Notes `size` as what a block of `kind` recorded, for the passes after this one ([`typical`]). A measuring run notes +/// nothing. A replay of the run keeps the note ([`keep`]). +pub(crate) fn note_typical(ctx: &Context, kind: Id, size: Vec2) { + if !real(ctx) { + return; + } + crate::runtime::replay::note_layout_keep(ctx, kind); + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| { + let typical = memory.typical.entry(kind).or_default(); + typical.next = Some(size); + typical.touched = moment.frame; + }); +} + +/// This pass placed the block `id` by `size`, which it took from elsewhere (a block of the same kind, [`typical`]), +/// where the entry under `id` holds no size yet: [`record`] compares the real size with `size`, as it compares a size +/// from the last pass, so a first appearance that measures what the placement assumed asks no discard pass. It +/// changes nothing when the entry holds a size, when this pass did not read the entry, or in a measuring run. +pub(crate) fn assume(ctx: &Context, id: Id, size: Vec2) { + if !real(ctx) { + return; + } + let moment = Moment::of(ctx); + with(ctx, &moment, |memory| { + if let Some(entry) = memory.entries.get_mut(&id) + && entry.value.is_none() + && entry.used.is_some_and(|(pass, read)| pass == moment.pass && read.is_none()) + { + entry.used = Some((moment.pass, Some(size))); + } + }); +} + /// Whether this pass is a real run's: no measuring run is open and egui does not run a sizing pass. fn real(ctx: &Context) -> bool { !crate::runtime::measure::active(ctx) @@ -1248,7 +1301,7 @@ pub(crate) fn discard_pending(ctx: &Context) -> bool { with(ctx, &moment, |memory| memory.ask && memory.asked != Some(moment.frame)) && sizing::discardable(ctx) } -/// Keeps the entries and kept transcripts of `ids` through this frame, for a replayed run that kept them +/// Keeps the entries, typical sizes and kept transcripts of `ids` through this frame, for a replayed run that kept them /// (`replay::note_layout_keep`): the replay does not reach them, and an entry no pass touched in a frame is dropped. pub(crate) fn keep(ctx: &Context, ids: &[Id]) { if ids.is_empty() { @@ -1260,6 +1313,9 @@ pub(crate) fn keep(ctx: &Context, ids: &[Id]) { if let Some(entry) = memory.entries.get_mut(id) { entry.touched = moment.frame; } + if let Some(typical) = memory.typical.get_mut(id) { + typical.touched = moment.frame; + } if let Some(kept) = memory.kept.get_mut(id) { kept.touched = moment.frame; } @@ -1278,6 +1334,12 @@ pub(crate) fn end_hook(ctx: &Context) { memory.asked = Some(moment.frame); } memory.entries.retain(|_, entry| entry.touched + 1 >= moment.frame); + memory.typical.retain(|_, typical| typical.touched + 1 >= moment.frame); + for typical in memory.typical.values_mut() { + if let Some(next) = typical.next.take() { + typical.now = Some(next); + } + } memory.kept.retain(|_, kept| kept.touched + 1 >= moment.frame); memory.measured.clear(); memory.served.clear(); diff --git a/crates/ui-widgets/tests/it/label/baseline.rs b/crates/ui-widgets/tests/it/label/baseline.rs index 1b1aa213a4..516f5dbca3 100644 --- a/crates/ui-widgets/tests/it/label/baseline.rs +++ b/crates/ui-widgets/tests/it/label/baseline.rs @@ -126,3 +126,113 @@ fn a_bar_number_field_sets_its_digits_and_unit_on_the_line_of_a_select() { assert!((digits - face).abs() < 0.5, "the digits sit on the select's baseline: digits {digits}, select {face}"); assert!((unit - face).abs() < 0.5, "the unit sits on the select's baseline: unit {unit}, select {face}"); } + +/// The painted baseline of the number field whose value is `value`. +fn value_baseline(fixture: &Fixture, value: f64) -> f32 { + let texts = fixture.texts(); + let run = texts.iter().find(|run| run.text.trim().parse::() == Ok(value)).unwrap_or_else(|| panic!("{value} is painted: {texts:?}")); + run.baseline +} + +/// A parameter form of `rows` fields, each a number field, except the rows `dial_from` and after, whose control is a +/// tall dial with the number field beside it (its text sits lower in the row). Row `at` is labeled "Row {at}" and +/// shows the value `at + 1`. +fn growing_form(rows: std::rc::Rc>) -> Fixture { + Fixture::new(move |ui| { + let (count, dial_from) = rows.get(); + FieldGroup::new("Parameters").show(ui, |ui, _| { + for at in 0..count { + let value = (at + 1) as f64; + Field::new(format!("Row {at}")).id_salt(("row", at)).show(ui, |ui, _| { + if at < dial_from { + NumberField::new("Value", Bind::given(Some(value))).id_salt(("value", at)).show(ui); + } else { + Row::new().id_salt(("pieces", at)).show(ui, |ui, _| { + AngleDial::new(Bind::given(45.0)).label("Angle").id_salt(("dial", at)).show(ui); + NumberField::new("Value", Bind::given(Some(value))).id_salt(("value", at)).show(ui); + }); + } + }); + } + }); + }) +} + +/// A labeled row that appears beside rows whose controls are of its size lines up its label with the baseline those +/// controls recorded, in the frame's one pass. Guards against the first appearance placing the label at the control's +/// top and asking the frame's discard pass to move it down. +#[trial] +fn a_new_labeled_row_lines_up_in_its_first_pass() { + let rows = std::rc::Rc::new(std::cell::Cell::new((2, usize::MAX))); + let mut fixture = growing_form(rows.clone()); + fixture.settle(); + // The form's content changed in the last frame, so this frame measures the form again and only the new row is new. + rows.set((3, usize::MAX)); + fixture.frame(Vec::new()); + rows.set((4, usize::MAX)); + let passes = fixture.frame(Vec::new()).passes(); + assert_eq!(passes, 1, "the frame that shows the new row runs one pass"); + let (label, value) = (baseline_of(&fixture, "Row 3"), value_baseline(&fixture, 4.0)); + assert!((label - value).abs() <= 0.5, "the new row's label lines up with its value: label {label}, value {value}"); +} + +/// The settled rows of `replayed_rows_keep_their_baseline_for_a_new_row`. +#[derive(craft_ui::contract::MemoProps)] +struct SettledRows {} + +fn settled_rows(_: &mut SettledRows, ui: &mut Ui) { + FieldGroup::new("Settled").show(ui, |ui, _| { + for at in 0..2 { + Field::new(format!("Settled {at}")).id_salt(("settled", at)).show(ui, |ui, _| { + NumberField::new("Value", Bind::given(Some(10.0 + at as f64))).id_salt(("settled value", at)).show(ui); + }); + } + }); +} + +/// Rows a memoized view replays in place of running keep the baseline they recorded for rows of their size: a labeled +/// row that appears after several replayed frames still lines up in its frame's one pass. +#[trial] +fn replayed_rows_keep_their_baseline_for_a_new_row() { + use craft_ui::contract::MemoView; + use craft_ui::testing::{MemoRun, last_frame_memo_runs}; + let shows = std::rc::Rc::new(std::cell::Cell::new(false)); + let shown = shows.clone(); + let mut fixture = Fixture::new(move |ui| { + MemoView::new("settled rows", SettledRows {}, settled_rows).show(ui); + if shown.get() { + FieldGroup::new("Added").show(ui, |ui, _| { + Field::new("Added row").id_salt("added").show(ui, |ui, _| { + NumberField::new("Value", Bind::given(Some(7.0))).id_salt("added value").show(ui); + }); + }); + } + }); + fixture.settle(); + for _ in 0..4 { + fixture.frame(Vec::new()); + let ran = last_frame_memo_runs(fixture.ctx()).iter().filter(|(_, _, run)| *run == MemoRun::Ran).count(); + assert_eq!(ran, 0, "the settled rows replay"); + } + shows.set(true); + let passes = fixture.frame(Vec::new()).passes(); + assert_eq!(passes, 1, "the frame that shows the new row runs one pass"); + let (label, value) = (baseline_of(&fixture, "Added row"), value_baseline(&fixture, 7.0)); + assert!((label - value).abs() <= 0.5, "the new row's label lines up with its value: label {label}, value {value}"); +} + +/// A labeled row that appears with a control whose text sits elsewhere than the other controls of its size (a number +/// beside a tall dial) still lines up its label with that text: the frame runs its discard pass and the label moves. +#[trial] +fn a_new_labeled_row_whose_control_differs_lines_up_after_one_discard() { + let rows = std::rc::Rc::new(std::cell::Cell::new((2, usize::MAX))); + let mut fixture = growing_form(rows.clone()); + fixture.settle(); + rows.set((3, usize::MAX)); + fixture.frame(Vec::new()); + rows.set((4, 3)); + let passes = fixture.frame(Vec::new()).passes(); + assert_eq!(passes, 2, "the frame runs the discard pass the differing baseline asks"); + let (label, value) = (baseline_of(&fixture, "Row 3"), value_baseline(&fixture, 4.0)); + assert!((label - value).abs() <= SLACK, "the new row's label lines up with the number beside the dial: label {label}, value {value}"); +}