From 30a47c5527b168e2ac7e5f1e34ea9883f7920ffd Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 09:14:19 +0100 Subject: [PATCH 01/22] Cache repeated text layouts per context --- crates/ui-contract/src/primitives/text.rs | 266 +++++++++++++++++- .../ui-contract/src/runtime/layout_memory.rs | 1 + 2 files changed, 264 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index bee717e76..e9565cd45 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -1,6 +1,7 @@ //! `TextRun`, the one description of UI text for measure, layout and paint, and `TextLayout`, its laid-out form. use crate::fonts::StackFacts; +use crate::runtime::egui::memory; use crate::runtime::egui::text_layout; pub use crate::style::Span; use crate::style::text_measure::{paragraph_job, span_format}; @@ -9,6 +10,8 @@ use craft_i18n::Direction; use egui::text::{LayoutJob, TextWrapping}; use egui::{Color32, Context, Galley}; use std::borrow::Cow; +use std::collections::{HashMap, VecDeque}; +use std::hash::{Hash, Hasher}; use std::ops::Range; use std::sync::Arc; @@ -150,6 +153,14 @@ impl<'a> TextRun<'a> { pub fn full_text(&self) -> String { self.spans.iter().map(|s| s.text.as_ref()).collect() } + + /// Borrows the common single-span case; only a multi-span run needs joining. + fn full_text_cow(&self) -> Cow<'_, str> { + match self.spans.as_slice() { + [span] => Cow::Borrowed(&span.text), + _ => Cow::Owned(self.full_text()), + } + } } /// The galley moved so its rect starts at x = 0: egui anchors a centred or right-aligned galley at its centre or @@ -215,12 +226,138 @@ pub(crate) fn line_baseline(ctx: &Context, env: &TextEnv<'_>, role: TypeRole, ce centre - line.size().y / 2.0 + line.first_baseline } +/// A bounded per-context cache. Equality compares the complete input, rather than trusting a hash collision. +#[derive(Clone, PartialEq)] +struct LayoutKey { + run: TextRun<'static>, + tokens: u64, + direction: Direction, + ink: Color32, + fonts: StackFacts, + width: u32, + scale: u32, +} + +struct CachedText { + key: LayoutKey, + layout: Option>, + least: Option, +} + +#[derive(Default)] +struct TextMemo { + entries: HashMap>, + order: VecDeque, + generation: u64, + sentinel: Option>, +} + +fn with_memo(ctx: &Context, f: impl FnOnce(&mut TextMemo) -> R) -> R { + // Egui clears its galley cache whenever the atlas or any layout input owned by fonts changes. + // Keeping this cached empty galley lets us observe that reset, including external providers and rasterizers. + let sentinel = ctx.fonts_mut(|fonts| fonts.layout_job(LayoutJob::default())); + memory::with::(ctx, |memo| { + if memo.sentinel.as_ref().is_none_or(|old| !Arc::ptr_eq(old, &sentinel)) { + memo.entries.clear(); + memo.order.clear(); + memo.generation = memo.generation.wrapping_add(1); + memo.sentinel = Some(sentinel); + } + f(memo) + }) +} + +impl LayoutKey { + // Hash the text and the common discriminators. Equality checks the remaining fields and resolves collisions. + fn hash(&self) -> u64 { + let mut hash = std::collections::hash_map::DefaultHasher::new(); + for span in &self.run.spans { + span.text.hash(&mut hash); + } + self.run.role.hash(&mut hash); + self.tokens.hash(&mut hash); + self.direction.hash(&mut hash); + self.width.hash(&mut hash); + self.scale.hash(&mut hash); + hash.finish() + } +} + +impl TextMemo { + fn get(&self, key: &LayoutKey) -> Option<&CachedText> { + self.entries.get(&key.hash())?.iter().find(|entry| entry.key == *key) + } + + fn put(&mut self, key: LayoutKey, layout: Option>, least: Option) { + // Large document text should not pin galleys in a UI-label cache. + if key.run.spans.iter().fold(0usize, |len, span| len.saturating_add(span.text.len())) > 16 * 1024 { + return; + } + let hash = key.hash(); + if let Some(entry) = self.entries.get_mut(&hash).and_then(|bucket| bucket.iter_mut().find(|entry| entry.key == key)) { + if layout.is_some() { + entry.layout = layout; + } + if least.is_some() { + entry.least = least; + } + return; + } + // Bound retained text and galleys, including colliding keys. + if self.order.len() >= 4096 + && let Some(old) = self.order.pop_front() + { + if let Some(bucket) = self.entries.get_mut(&old) { + bucket.remove(0); + if bucket.is_empty() { + self.entries.remove(&old); + } + } + } + self.entries.entry(hash).or_default().push(CachedText { key, layout, least }); + self.order.push_back(hash); + } +} + impl TextRun<'_> { + /// All inputs read by `job`, the cutting and row-alignment steps. + fn layout_key(&self, ctx: &Context, env: &TextEnv<'_>, max_width: f32) -> LayoutKey { + let spans = self + .spans + .iter() + .map(|span| Span { + text: Cow::Owned(span.text.to_string()), + italic: span.italic, + tabular: span.tabular, + mono: span.mono, + muted: span.muted, + shortcut: span.shortcut, + highlight: span.highlight, + underline: span.underline, + strong: span.strong, + }) + .collect(); + LayoutKey { + run: TextRun { spans, role: self.role, color: self.color, wrap: self.wrap, ltr: self.ltr, align: self.align, rotation: self.rotation }, + tokens: env.tokens.key(), + direction: env.direction, + ink: env.ink, + fonts: env.fonts, + width: max_width.to_bits(), + scale: ctx.pixels_per_point().to_bits(), + } + } + /// The one text layout behind `MeasureCx::layout`, `PartsCx::layout`, `TextParts::layout` and `Draw::text`: the /// paragraph direction comes from the caller's env, so measure and paint agree. `max_width` is the room; a /// `Line` run ignores it. pub(crate) fn layout(&self, ctx: &Context, env: &TextEnv<'_>, max_width: f32) -> TextLayout { - let full = self.full_text(); + let key = self.layout_key(ctx, env, max_width); + let (cached, generation) = with_memo(ctx, |memo| (memo.get(&key).and_then(|entry| entry.layout.clone()), memo.generation)); + if let Some(layout) = cached { + return (*layout).clone(); + } + let full = self.full_text_cow(); // Every cut goes through the one cut that `least_width` measures, so a run shown at its least keeps its // readable characters. let galley = match self.wrap { @@ -228,8 +365,13 @@ impl TextRun<'_> { _ => text_layout::layout(ctx, self.job(env, self.spans.iter().map(|s| (s, s.text.as_ref())), max_width)), }; let elided = galley.elided || self.wrap.cuts() && galley.job.text != full; - let mut layout = TextLayout::new(aligned_rows(galley, self.align, self.is_rtl(env), ctx.pixels_per_point()), elided, full); + let mut layout = TextLayout::new(aligned_rows(galley, self.align, self.is_rtl(env), ctx.pixels_per_point()), elided, full.into_owned()); layout.rotation = self.rotation; + with_memo(ctx, |memo| { + if memo.generation == generation { + memo.put(key, Some(Arc::new(layout.clone())), None); + } + }); layout } @@ -237,7 +379,22 @@ impl TextRun<'_> { /// [`READABLE_CHARACTERS`](Self::READABLE_CHARACTERS) and the ellipsis, or whole when it has no more than one /// character beyond them. pub(crate) fn least_width(&self, ctx: &Context, env: &TextEnv<'_>) -> f32 { - let full = self.full_text(); + let key = self.layout_key(ctx, env, f32::INFINITY); + let (cached, generation) = with_memo(ctx, |memo| (memo.get(&key).and_then(|entry| entry.least), memo.generation)); + if let Some(least) = cached { + return least; + } + let least = self.compute_least_width(ctx, env); + with_memo(ctx, |memo| { + if memo.generation == generation { + memo.put(key, None, Some(least)); + } + }); + least + } + + fn compute_least_width(&self, ctx: &Context, env: &TextEnv<'_>) -> f32 { + let full = self.full_text_cow(); let whole = text_layout::layout(ctx, self.job(env, self.spans.iter().map(|s| (s, s.text.as_ref())), f32::INFINITY)).size().x; let ends: Vec = full.char_indices().map(|(at, _)| at).chain([full.len()]).collect(); if ends.len() - 1 <= Self::READABLE_CHARACTERS + 1 { @@ -565,3 +722,106 @@ impl ReadingMeasure { ReadingMeasure { target: average * Self::TARGET_CHARACTERS, least: average * Self::LEAST_CHARACTERS } } } + +#[cfg(feature = "testing")] +mod memo_tests { + use super::*; + use crate::testing::trial; + use craft_theme::{Appearance, Contrast, Mode, Size, TextSize, builtins, resolve}; + + #[trial] + fn layouts_reuse_equal_inputs_and_font_updates_invalidate_them() { + let appearance = + Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::Compact, text_size: TextSize::Small, reduced_motion: false }; + let tokens = UiTokens::new(Arc::new(resolve(&builtins()[0], appearance, None).tokens), Contrast::Standard, Size::Compact); + let ctx = Context::default(); + let mut output = ctx.run_pass(Default::default(), |ctx| { + let env = TextEnv { tokens: &tokens, direction: Direction::Ltr, ink: Color32::WHITE, fonts: StackFacts::default() }; + let run = TextRun::new("a label long enough to elide").elide(); + let first = run.layout(ctx, &env, 80.0); + let second = run.layout(ctx, &env, 80.0); + assert!(Arc::ptr_eq(&first.galley, &second.galley)); + let _ = run.layout(ctx, &env, 120.0); + let _ = run.least_width(ctx, &env); + let least_key = run.layout_key(ctx, &env, f32::INFINITY); + with_memo(ctx, |memo| { + assert_eq!(memo.order.len(), 3); + assert!(memo.get(&least_key).is_some_and(|entry| entry.least.is_some())); + }); + let mut variants = Vec::new(); + let mut changed = run.clone(); + changed.spans[0].text = Cow::Borrowed("a different label"); + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].italic = true; + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].tabular = true; + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].mono = true; + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].muted = true; + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].shortcut = true; + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].highlight = true; + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].underline = true; + variants.push(changed); + let mut changed = run.clone(); + changed.spans[0].strong = true; + variants.push(changed); + let mut changed = run.clone(); + changed.color = Some(StyleColor(Color32::BLUE)); + variants.push(changed); + let mut changed = run.clone(); + changed.role = TypeRole::Body; + variants.push(changed); + let mut changed = run.clone(); + changed.wrap = Wrap::Clip; + variants.push(changed); + let mut changed = run.clone(); + changed.align = HAlign::Center; + variants.push(changed); + let mut changed = run.clone(); + changed.ltr = true; + variants.push(changed); + let mut changed = run.clone(); + changed.rotation = 0.5; + variants.push(changed); + for changed in variants { + let before = with_memo(ctx, |memo| memo.order.len()); + let _ = changed.layout(ctx, &env, 80.0); + let _ = changed.layout(ctx, &env, 80.0); + assert_eq!(with_memo(ctx, |memo| memo.order.len()), before + 1); + } + let rtl = TextEnv { direction: Direction::Rtl, ..env }; + let _ = run.layout(ctx, &rtl, 80.0); + let ink = TextEnv { ink: Color32::RED, ..env }; + let _ = run.layout(ctx, &ink, 80.0); + let fonts = TextEnv { fonts: StackFacts { semibold: true, ..env.fonts }, ..env }; + let _ = run.layout(ctx, &fonts, 80.0); + let mut changed_tokens = (**tokens.tokens()).clone(); + changed_tokens.color.text.muted = craft_theme::Rgba([12, 34, 56, 255]); + let changed_tokens = UiTokens::new(Arc::new(changed_tokens), Contrast::Standard, Size::Compact); + let styled = TextEnv { tokens: &changed_tokens, ..env }; + let _ = run.layout(ctx, &styled, 80.0); + let before = with_memo(ctx, |memo| memo.order.len()); + assert_eq!(before, 22); + }); + output.textures_delta.clear(); + // A direct egui font replacement bypasses framework hooks; the sentinel must detect it. + let mut definitions = ctx.fonts(|fonts| fonts.definitions().clone()); + definitions.families.insert(egui::FontFamily::Name("memo trial".into()), Vec::new()); + ctx.set_fonts(definitions); + let mut output = ctx.run_pass(Default::default(), |ctx| { + with_memo(ctx, |memo| assert!(memo.order.is_empty())); + }); + output.textures_delta.clear(); + } +} diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index e2c4c79a3..cb9d46565 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1235,6 +1235,7 @@ pub(crate) mod guard { ("runtime::egui::painted::Elisions", "elisions: written where text paints, which a measuring run does not"), ("Stamped>", "per-pass id sets: read"), // Caches: equal inputs give equal values, whichever run fills them. + ("primitives::text::TextMemo", "text layouts: a bounded cache keyed by the layout inputs and egui's font-cache generation"), ("style::cache::StyleCache", "style cache"), ("style::replacements::Frozen", "frozen style replacements: cache"), ("runtime::env::tokens::RootTokenCache", "root tokens: cache"), From e17bb9328b2da77f9bf2338d1e1ac556c3b6f81a Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:06:38 +0100 Subject: [PATCH 02/22] Compute text details on demand --- crates/ui-contract/src/primitives/content.rs | 2 +- crates/ui-contract/src/primitives/mod.rs | 2 +- crates/ui-contract/src/primitives/text.rs | 308 ++++++++++++++++--- 3 files changed, 268 insertions(+), 44 deletions(-) diff --git a/crates/ui-contract/src/primitives/content.rs b/crates/ui-contract/src/primitives/content.rs index cd13babcf..88dd1c996 100644 --- a/crates/ui-contract/src/primitives/content.rs +++ b/crates/ui-contract/src/primitives/content.rs @@ -168,7 +168,7 @@ impl<'a> DocText<'a> { } let galley = text_layout::layout(ctx, job); let elided = galley.elided; - TextLayout::new(aligned_rows(galley, self.align, direction == Direction::Rtl, ctx.pixels_per_point()), elided, self.full_text()) + TextLayout::from_job(aligned_rows(galley, self.align, direction == Direction::Rtl, ctx.pixels_per_point()), elided, None) } } diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index d302024b4..2aa2d0b44 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -54,7 +54,7 @@ pub use surface::Surface; pub(crate) use surface::SurfaceSlot; pub use surround::paint_surround; pub use svg_set::{AppIcons, register_app_icons}; -pub use text::{ChordText, HAlign, LayoutRun, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; +pub use text::{ChordText, HAlign, LayoutRun, LayoutRuns, LayoutText, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; pub use text_input::{Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, TextKey, TextOptions}; pub use textures::TextureCache; pub use tool::ToolIcon; diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index e9565cd45..90946177b 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -12,8 +12,8 @@ use egui::{Color32, Context, Galley}; use std::borrow::Cow; use std::collections::{HashMap, VecDeque}; use std::hash::{Hash, Hasher}; -use std::ops::Range; -use std::sync::Arc; +use std::ops::{Deref, Range}; +use std::sync::{Arc, OnceLock}; /// How a run fits its room. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] @@ -238,6 +238,17 @@ struct LayoutKey { scale: u32, } +/// A lookup borrows the spans; only a new cache entry copies their text. +struct LayoutQuery<'a> { + run: &'a TextRun<'a>, + tokens: u64, + direction: Direction, + ink: Color32, + fonts: StackFacts, + width: u32, + scale: u32, +} + struct CachedText { key: LayoutKey, layout: Option>, @@ -267,7 +278,7 @@ fn with_memo(ctx: &Context, f: impl FnOnce(&mut TextMemo) -> R) -> R { }) } -impl LayoutKey { +impl LayoutQuery<'_> { // Hash the text and the common discriminators. Equality checks the remaining fields and resolves collisions. fn hash(&self) -> u64 { let mut hash = std::collections::hash_map::DefaultHasher::new(); @@ -281,20 +292,66 @@ impl LayoutKey { self.scale.hash(&mut hash); hash.finish() } + + fn matches(&self, key: &LayoutKey) -> bool { + key.run == *self.run + && key.tokens == self.tokens + && key.direction == self.direction + && key.ink == self.ink + && key.fonts == self.fonts + && key.width == self.width + && key.scale == self.scale + } + + fn owned(&self) -> LayoutKey { + let spans = self + .run + .spans + .iter() + .map(|span| Span { + text: Cow::Owned(span.text.to_string()), + italic: span.italic, + tabular: span.tabular, + mono: span.mono, + muted: span.muted, + shortcut: span.shortcut, + highlight: span.highlight, + underline: span.underline, + strong: span.strong, + }) + .collect(); + LayoutKey { + run: TextRun { + spans, + role: self.run.role, + color: self.run.color, + wrap: self.run.wrap, + ltr: self.run.ltr, + align: self.run.align, + rotation: self.run.rotation, + }, + tokens: self.tokens, + direction: self.direction, + ink: self.ink, + fonts: self.fonts, + width: self.width, + scale: self.scale, + } + } } impl TextMemo { - fn get(&self, key: &LayoutKey) -> Option<&CachedText> { - self.entries.get(&key.hash())?.iter().find(|entry| entry.key == *key) + fn get(&self, key: &LayoutQuery<'_>) -> Option<&CachedText> { + self.entries.get(&key.hash())?.iter().find(|entry| key.matches(&entry.key)) } - fn put(&mut self, key: LayoutKey, layout: Option>, least: Option) { + fn put(&mut self, key: &LayoutQuery<'_>, layout: Option>, least: Option) { // Large document text should not pin galleys in a UI-label cache. - if key.run.spans.iter().fold(0usize, |len, span| len.saturating_add(span.text.len())) > 16 * 1024 { + if key.run.spans.len() > 1024 || key.run.spans.iter().fold(0usize, |len, span| len.saturating_add(span.text.len())) > 16 * 1024 { return; } let hash = key.hash(); - if let Some(entry) = self.entries.get_mut(&hash).and_then(|bucket| bucket.iter_mut().find(|entry| entry.key == key)) { + if let Some(entry) = self.entries.get_mut(&hash).and_then(|bucket| bucket.iter_mut().find(|entry| key.matches(&entry.key))) { if layout.is_some() { entry.layout = layout; } @@ -314,31 +371,16 @@ impl TextMemo { } } } - self.entries.entry(hash).or_default().push(CachedText { key, layout, least }); + self.entries.entry(hash).or_default().push(CachedText { key: key.owned(), layout, least }); self.order.push_back(hash); } } impl TextRun<'_> { /// All inputs read by `job`, the cutting and row-alignment steps. - fn layout_key(&self, ctx: &Context, env: &TextEnv<'_>, max_width: f32) -> LayoutKey { - let spans = self - .spans - .iter() - .map(|span| Span { - text: Cow::Owned(span.text.to_string()), - italic: span.italic, - tabular: span.tabular, - mono: span.mono, - muted: span.muted, - shortcut: span.shortcut, - highlight: span.highlight, - underline: span.underline, - strong: span.strong, - }) - .collect(); - LayoutKey { - run: TextRun { spans, role: self.role, color: self.color, wrap: self.wrap, ltr: self.ltr, align: self.align, rotation: self.rotation }, + fn layout_key<'a>(&'a self, ctx: &Context, env: &TextEnv<'_>, max_width: f32) -> LayoutQuery<'a> { + LayoutQuery { + run: self, tokens: env.tokens.key(), direction: env.direction, ink: env.ink, @@ -357,19 +399,22 @@ impl TextRun<'_> { if let Some(layout) = cached { return (*layout).clone(); } - let full = self.full_text_cow(); + // Only a custom cut needs the joined text: other jobs already own the full text. + let full = self.wrap.cuts().then(|| self.full_text_cow()); // Every cut goes through the one cut that `least_width` measures, so a run shown at its least keeps its // readable characters. - let galley = match self.wrap { - Wrap::Elide | Wrap::ElideStart | Wrap::ElideMiddle | Wrap::ElidePath => self.layout_cut(ctx, env, &full, max_width), - _ => text_layout::layout(ctx, self.job(env, self.spans.iter().map(|s| (s, s.text.as_ref())), max_width)), + let galley = match &full { + Some(full) => self.layout_cut(ctx, env, full, max_width), + None => text_layout::layout(ctx, self.job(env, self.spans.iter().map(|s| (s, s.text.as_ref())), max_width)), }; - let elided = galley.elided || self.wrap.cuts() && galley.job.text != full; - let mut layout = TextLayout::new(aligned_rows(galley, self.align, self.is_rtl(env), ctx.pixels_per_point()), elided, full.into_owned()); + let changed = full.as_ref().is_some_and(|full| galley.job.text != *full); + let elided = galley.elided || changed; + let original = full.filter(|_| changed).map(|full| Arc::::from(full.as_ref())); + let mut layout = TextLayout::from_job(aligned_rows(galley, self.align, self.is_rtl(env), ctx.pixels_per_point()), elided, original); layout.rotation = self.rotation; with_memo(ctx, |memo| { if memo.generation == generation { - memo.put(key, Some(Arc::new(layout.clone())), None); + memo.put(&key, Some(Arc::new(layout.clone())), None); } }); layout @@ -387,7 +432,7 @@ impl TextRun<'_> { let least = self.compute_least_width(ctx, env); with_memo(ctx, |memo| { if memo.generation == generation { - memo.put(key, None, Some(least)); + memo.put(&key, None, Some(least)); } }); least @@ -587,12 +632,110 @@ pub struct LayoutRun { /// Records that the galley of `layout` was painted, and its full text when the layout cut text. pub(crate) fn note_painted(ctx: &Context, layout: &TextLayout) { if layout.elided { - crate::runtime::egui::painted::note_elided(ctx, &layout.galley, &layout.full); + crate::runtime::egui::painted::note_elided(ctx, &layout.galley, layout.full()); + } +} + +/// The full text of a layout, materialized only when read. +/// +/// Dereferences to `String` so existing field reads continue to work. +pub struct LayoutText { + galley: Arc, + original: Option>, + value: Arc>, +} + +impl LayoutText { + fn shared(&self) -> Self { + Self { galley: self.galley.clone(), original: self.original.clone(), value: self.value.clone() } + } +} + +impl std::fmt::Debug for LayoutText { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(self.deref(), f) + } +} + +impl std::fmt::Display for LayoutText { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(self.deref(), f) + } +} + +impl AsRef for LayoutText { + fn as_ref(&self) -> &str { + self.deref() + } +} + +impl PartialEq for LayoutText { + fn eq(&self, other: &Self) -> bool { + self.deref() == other.deref() + } +} + +impl PartialEq<&str> for LayoutText { + fn eq(&self, other: &&str) -> bool { + self.deref() == other + } +} + +impl PartialEq for LayoutText { + fn eq(&self, other: &String) -> bool { + self.deref() == other + } +} + +impl Deref for LayoutText { + type Target = String; + + fn deref(&self) -> &String { + self.value.get_or_init(|| self.original.as_deref().unwrap_or(&self.galley.job.text).to_owned()) + } +} + +/// A layout's single-row direction runs, built only when read. +/// +/// Dereferences to `Vec` so existing field reads continue to work. +pub struct LayoutRuns { + galley: Arc, + value: Arc>>, +} + +impl LayoutRuns { + fn shared(&self) -> Self { + Self { galley: self.galley.clone(), value: self.value.clone() } + } +} + +impl std::fmt::Debug for LayoutRuns { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(self.deref(), f) + } +} + +impl PartialEq for LayoutRuns { + fn eq(&self, other: &Self) -> bool { + self.deref() == other.deref() + } +} + +impl PartialEq> for LayoutRuns { + fn eq(&self, other: &Vec) -> bool { + self.deref() == other + } +} + +impl Deref for LayoutRuns { + type Target = Vec; + + fn deref(&self) -> &Vec { + self.value.get_or_init(|| if self.galley.rows.len() <= 1 { TextLayout::build_row_runs(&self.galley, 0) } else { Vec::new() }) } } /// A laid-out run. -#[derive(Clone)] #[non_exhaustive] pub struct TextLayout { /// The galley. @@ -600,25 +743,54 @@ pub struct TextLayout { /// The layout cut text. pub elided: bool, /// The full text, as the tooltip and accessible name of an elided run. - pub full: String, + pub full: LayoutText, /// The first row's baseline, from the layout's top. pub first_baseline: f32, /// The bidi runs of a single-row layout; empty for a wrapped one. - pub runs: Vec, + pub runs: LayoutRuns, /// The run's paint angle, in radians clockwise about the layout's top-left corner. pub rotation: f32, } +impl Clone for TextLayout { + fn clone(&self) -> Self { + Self { + galley: self.galley.clone(), + elided: self.elided, + full: self.full.shared(), + first_baseline: self.first_baseline, + runs: self.runs.shared(), + rotation: self.rotation, + } + } +} + impl TextLayout { pub(crate) fn new(galley: Arc, elided: bool, full: String) -> TextLayout { + let original = (galley.job.text != full).then(|| Arc::::from(full)); + Self::from_job(galley, elided, original) + } + + pub(super) fn from_job(galley: Arc, elided: bool, full: Option>) -> TextLayout { let first_baseline = galley.rows.first().map_or(0.0, |placed| match placed.row.glyphs.first() { Some(glyph) => placed.pos.y + glyph.pos.y, None => placed.pos.y + placed.row.size.y, }); - let runs = if galley.rows.len() <= 1 { Self::build_row_runs(&galley, 0) } else { Vec::new() }; + let full = LayoutText { galley: galley.clone(), original: full, value: Arc::new(OnceLock::new()) }; + let runs = LayoutRuns { galley: galley.clone(), value: Arc::new(OnceLock::new()) }; TextLayout { galley, elided, full, first_baseline, runs, rotation: 0.0 } } + /// The full text, as the tooltip and accessible name of an elided run. + pub fn full(&self) -> &str { + &self.full + } + + /// The bidi runs of a single-row layout; empty for a wrapped one. + pub fn runs(&self) -> &[LayoutRun] { + &self.runs + } + /// One run per maximal stretch of glyphs with one direction; an empty row is one empty left-to-right run. fn build_row_runs(galley: &Galley, row: usize) -> Vec { let glyphs = galley.rows.get(row).map_or(&[][..], |placed| &placed.row.glyphs[..]); @@ -650,7 +822,8 @@ impl TextLayout { .map(|at| { let placed = &self.galley.rows[at]; let text = placed.row.glyphs.iter().map(|glyph| glyph.chr).collect(); - (text, egui::Rect::from_min_size(placed.pos, placed.row.size), Self::build_row_runs(&self.galley, at)) + let runs = if self.galley.rows.len() == 1 { self.runs().to_vec() } else { Self::build_row_runs(&self.galley, at) }; + (text, egui::Rect::from_min_size(placed.pos, placed.row.size), runs) }) .collect() } @@ -741,6 +914,14 @@ mod memo_tests { let first = run.layout(ctx, &env, 80.0); let second = run.layout(ctx, &env, 80.0); assert!(Arc::ptr_eq(&first.galley, &second.galley)); + assert!(first.runs.value.get().is_none()); + assert!(first.full.value.get().is_none()); + assert_eq!(first.full(), "a label long enough to elide"); + assert!(second.full.value.get().is_some()); + let _ = first.runs(); + assert!(second.runs.value.get().is_some()); + let _: String = first.full.clone(); + let _: Vec = first.runs.clone(); let _ = run.layout(ctx, &env, 120.0); let _ = run.least_width(ctx, &env); let least_key = run.layout_key(ctx, &env, f32::INFINITY); @@ -753,6 +934,9 @@ mod memo_tests { changed.spans[0].text = Cow::Borrowed("a different label"); variants.push(changed); let mut changed = run.clone(); + changed.spans = vec![Span::new("a label "), Span::new("long enough to elide")]; + variants.push(changed); + let mut changed = run.clone(); changed.spans[0].italic = true; variants.push(changed); let mut changed = run.clone(); @@ -806,13 +990,17 @@ mod memo_tests { let _ = run.layout(ctx, &ink, 80.0); let fonts = TextEnv { fonts: StackFacts { semibold: true, ..env.fonts }, ..env }; let _ = run.layout(ctx, &fonts, 80.0); + let fonts = TextEnv { fonts: StackFacts { system_ui: true, ..env.fonts }, ..env }; + let _ = run.layout(ctx, &fonts, 80.0); + let fonts = TextEnv { fonts: StackFacts { line_ratio: 1.25, ..env.fonts }, ..env }; + let _ = run.layout(ctx, &fonts, 80.0); let mut changed_tokens = (**tokens.tokens()).clone(); changed_tokens.color.text.muted = craft_theme::Rgba([12, 34, 56, 255]); let changed_tokens = UiTokens::new(Arc::new(changed_tokens), Contrast::Standard, Size::Compact); let styled = TextEnv { tokens: &changed_tokens, ..env }; let _ = run.layout(ctx, &styled, 80.0); let before = with_memo(ctx, |memo| memo.order.len()); - assert_eq!(before, 22); + assert_eq!(before, 25); }); output.textures_delta.clear(); // A direct egui font replacement bypasses framework hooks; the sentinel must detect it. @@ -824,4 +1012,40 @@ mod memo_tests { }); output.textures_delta.clear(); } + + #[trial] + fn idle_text_reuses_galleys_and_changed_text_lays_out_once_per_width() { + let appearance = + Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::Compact, text_size: TextSize::Small, reduced_motion: false }; + let tokens = UiTokens::new(Arc::new(resolve(&builtins()[0], appearance, None).tokens), Contrast::Standard, Size::Compact); + let ctx = Context::default(); + let run = TextRun::new("the initial label for the cache trial").wrap(Wrap::Wrap); + let env = TextEnv { tokens: &tokens, direction: Direction::Ltr, ink: Color32::WHITE, fonts: StackFacts::default() }; + let mut output = ctx.run_pass(Default::default(), |ctx| { + let _ = run.layout(ctx, &env, 80.0); + let _ = run.layout(ctx, &env, 120.0); + }); + output.textures_delta.clear(); + let mut output = ctx.run_pass(Default::default(), |ctx| { + let before = ctx.fonts(|fonts| fonts.num_galleys_in_cache()); + let _ = run.layout(ctx, &env, 80.0); + let _ = run.layout(ctx, &env, 120.0); + assert_eq!(ctx.fonts(|fonts| fonts.num_galleys_in_cache()), before); + let changed = TextRun::new("a different label for the cache trial").wrap(Wrap::Wrap); + let _ = changed.layout(ctx, &env, 80.0); + let _ = changed.layout(ctx, &env, 120.0); + assert_eq!(ctx.fonts(|fonts| fonts.num_galleys_in_cache()), before + 2); + }); + output.textures_delta.clear(); + ctx.set_pixels_per_point(2.0); + let mut output = ctx.run_pass(Default::default(), |ctx| { + assert_eq!(ctx.pixels_per_point(), 2.0); + let _ = run.layout(ctx, &env, 80.0); + let after = with_memo(ctx, |memo| memo.order.len()); + let _ = run.layout(ctx, &env, 80.0); + assert_eq!(with_memo(ctx, |memo| memo.order.len()), after); + assert_eq!(after, 1); + }); + output.textures_delta.clear(); + } } From f59d3076520c78869002a0f595a9c4dc4e7dfcbd Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 10:10:59 +0100 Subject: [PATCH 03/22] Simplify text memo eviction guard --- crates/ui-contract/src/primitives/text.rs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 90946177b..d53523ef4 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -363,12 +363,11 @@ impl TextMemo { // Bound retained text and galleys, including colliding keys. if self.order.len() >= 4096 && let Some(old) = self.order.pop_front() + && let Some(bucket) = self.entries.get_mut(&old) { - if let Some(bucket) = self.entries.get_mut(&old) { - bucket.remove(0); - if bucket.is_empty() { - self.entries.remove(&old); - } + bucket.remove(0); + if bucket.is_empty() { + self.entries.remove(&old); } } self.entries.entry(hash).or_default().push(CachedText { key: key.owned(), layout, least }); From 5ab63236e417b0d14b4f7b467864e691ebd0c680 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 11:38:50 +0100 Subject: [PATCH 04/22] Preserve mutation of lazy text details --- crates/ui-contract/src/primitives/text.rs | 50 +++++++++++++++++++---- 1 file changed, 42 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index d53523ef4..f80147731 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -12,7 +12,7 @@ use egui::{Color32, Context, Galley}; use std::borrow::Cow; use std::collections::{HashMap, VecDeque}; use std::hash::{Hash, Hasher}; -use std::ops::{Deref, Range}; +use std::ops::{Deref, DerefMut, Range}; use std::sync::{Arc, OnceLock}; /// How a run fits its room. @@ -642,11 +642,12 @@ pub struct LayoutText { galley: Arc, original: Option>, value: Arc>, + changed: Option, } impl LayoutText { fn shared(&self) -> Self { - Self { galley: self.galley.clone(), original: self.original.clone(), value: self.value.clone() } + Self { galley: self.galley.clone(), original: self.original.clone(), value: self.value.clone(), changed: self.changed.clone() } } } @@ -690,7 +691,14 @@ impl Deref for LayoutText { type Target = String; fn deref(&self) -> &String { - self.value.get_or_init(|| self.original.as_deref().unwrap_or(&self.galley.job.text).to_owned()) + self.changed.as_ref().unwrap_or_else(|| self.value.get_or_init(|| self.original.as_deref().unwrap_or(&self.galley.job.text).to_owned())) + } +} + +impl DerefMut for LayoutText { + fn deref_mut(&mut self) -> &mut String { + let (value, original, galley) = (&self.value, &self.original, &self.galley); + self.changed.get_or_insert_with(|| value.get_or_init(|| original.as_deref().unwrap_or(&galley.job.text).to_owned()).clone()) } } @@ -700,11 +708,12 @@ impl Deref for LayoutText { pub struct LayoutRuns { galley: Arc, value: Arc>>, + changed: Option>, } impl LayoutRuns { fn shared(&self) -> Self { - Self { galley: self.galley.clone(), value: self.value.clone() } + Self { galley: self.galley.clone(), value: self.value.clone(), changed: self.changed.clone() } } } @@ -730,7 +739,18 @@ impl Deref for LayoutRuns { type Target = Vec; fn deref(&self) -> &Vec { - self.value.get_or_init(|| if self.galley.rows.len() <= 1 { TextLayout::build_row_runs(&self.galley, 0) } else { Vec::new() }) + self.changed.as_ref().unwrap_or_else(|| { + self.value.get_or_init(|| if self.galley.rows.len() <= 1 { TextLayout::build_row_runs(&self.galley, 0) } else { Vec::new() }) + }) + } +} + +impl DerefMut for LayoutRuns { + fn deref_mut(&mut self) -> &mut Vec { + let (value, galley) = (&self.value, &self.galley); + self.changed.get_or_insert_with(|| { + value.get_or_init(|| if galley.rows.len() <= 1 { TextLayout::build_row_runs(galley, 0) } else { Vec::new() }).clone() + }) } } @@ -775,8 +795,8 @@ impl TextLayout { Some(glyph) => placed.pos.y + glyph.pos.y, None => placed.pos.y + placed.row.size.y, }); - let full = LayoutText { galley: galley.clone(), original: full, value: Arc::new(OnceLock::new()) }; - let runs = LayoutRuns { galley: galley.clone(), value: Arc::new(OnceLock::new()) }; + let full = LayoutText { galley: galley.clone(), original: full, value: Arc::new(OnceLock::new()), changed: None }; + let runs = LayoutRuns { galley: galley.clone(), value: Arc::new(OnceLock::new()), changed: None }; TextLayout { galley, elided, full, first_baseline, runs, rotation: 0.0 } } @@ -821,7 +841,11 @@ impl TextLayout { .map(|at| { let placed = &self.galley.rows[at]; let text = placed.row.glyphs.iter().map(|glyph| glyph.chr).collect(); - let runs = if self.galley.rows.len() == 1 { self.runs().to_vec() } else { Self::build_row_runs(&self.galley, at) }; + let runs = if self.galley.rows.len() == 1 && self.runs.changed.is_none() { + self.runs().to_vec() + } else { + Self::build_row_runs(&self.galley, at) + }; (text, egui::Rect::from_min_size(placed.pos, placed.row.size), runs) }) .collect() @@ -921,6 +945,16 @@ mod memo_tests { assert!(second.runs.value.get().is_some()); let _: String = first.full.clone(); let _: Vec = first.runs.clone(); + let mut changed = first.clone(); + changed.full.push('!'); + changed.runs.clear(); + assert_eq!(first.full(), "a label long enough to elide"); + assert_ne!(changed.full(), first.full()); + assert!(!first.runs().is_empty()); + assert!(changed.runs().is_empty()); + let again = run.layout(ctx, &env, 80.0); + assert_eq!(again.full(), first.full()); + assert_eq!(again.runs(), first.runs()); let _ = run.layout(ctx, &env, 120.0); let _ = run.least_width(ctx, &env); let least_key = run.layout_key(ctx, &env, f32::INFINITY); From 61b0fc0b41a43888eedc8ce189d95629f8ca8d7f Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 11:48:53 +0100 Subject: [PATCH 05/22] Measure opted-in leaf sizes together --- crates/ui-contract/src/contract/mod.rs | 13 ++++ crates/ui-contract/src/contract/run.rs | 48 +++++++++++--- crates/ui-contract/src/contract/run/typed.rs | 5 ++ crates/ui-contract/src/contract/steps.rs | 2 +- .../ui-contract/src/contract/steps/measure.rs | 16 +++++ crates/ui-contract/tests/it/layout/fill.rs | 64 ++++++++++++++++++- crates/ui-widgets/src/buttons/button.rs | 6 ++ crates/ui-widgets/src/buttons/face.rs | 16 +++++ crates/ui-widgets/src/buttons/link.rs | 14 ++++ crates/ui-widgets/src/buttons/split_button.rs | 9 +++ .../ui-widgets/src/buttons/toggle_button.rs | 6 ++ crates/ui-widgets/src/display/text.rs | 21 ++++++ crates/ui-widgets/src/pickers/face.rs | 27 ++++++++ 13 files changed, 237 insertions(+), 10 deletions(-) diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 6c4877339..29206c8c4 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -411,6 +411,19 @@ pub trait Component: Meta + Sized { Vec2::ZERO } + /// Set when `measure_pair` may answer a paired request. The default avoids calling the hook for legacy components. + const PAIRED_MEASURE: bool = false; + + /// Optionally answers an ideal and a least content measure together. The answers must match `measure` under + /// the two supplied contexts, including the external inputs each reads, and leave the component as those calls + /// would. The component's fill declaration and label-scope reads must not change during either measure. Both + /// answers are replayed under the union of those inputs, so use this only when that preserves each answer. Return + /// `None` without reading either context or changing state to keep the ordinary separate calls; + /// that is the default. + fn measure_pair(&mut self, _ideal: &MeasureCx<'_, Self>, _least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + None + } + /// The axis along which the component takes all the room the flow offers when that is more than it measured, /// as a container with `Sizing::Fill` does: the width when its caller set `Sizing::FillWidth` (a search field /// before a count) or `Sizing::Fill` (which takes the height as well). A component that fills by what it is diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index fa0d9923d..4671f66a7 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -438,6 +438,7 @@ pub(crate) struct TypeFacts { pub canvas_control: bool, pub labelled_after: bool, pub binds_view: bool, + pub paired_measure: bool, /// `DISABLED` is `Faded`. pub faded: bool, /// `RULE`. @@ -459,6 +460,7 @@ impl TypeFacts { canvas_control: C::CANVAS_CONTROL, labelled_after: C::LABELLED_AFTER, binds_view: C::BINDS_VIEW, + paired_measure: C::PAIRED_MEASURE, faded: C::DISABLED == super::DisabledLook::Faded, rule: C::RULE, style_key: TypeId::of::(), @@ -497,6 +499,7 @@ pub(crate) trait Erased { fn cut_first(&self) -> bool; /// What `C::measure` gives for the shown value. fn measure_content(&mut self, input: &MeasureIn<'_>, resolved: &Resolved<'_>) -> (Vec2, Inputs); + fn measure_content_pair(&mut self, ideal: &MeasureIn<'_>, least: &MeasureIn<'_>, resolved: &Resolved<'_>) -> Option<((Vec2, Vec2), Inputs)>; fn measured_extent(&mut self, at: &Measuring<'_, '_>, stage: &mut MemoryStage) -> Vec2; fn pass_extent(&mut self, at: &Measuring<'_, '_>) -> Vec2; /// Builds the component's `Cx` over `core` and `style` (what `style` gave), runs `rest` with it, then `finish`. @@ -1609,8 +1612,8 @@ fn measure_step( let ask = |t: &mut dyn Erased, proposal: Proposal, room: Option, extent: Vec2| { measured(t, &MeasureIn { ui: &*ui, env, proposal, room }, style, resolved, extent) }; - let (size, inputs) = ask(&mut *t, Proposal::Ideal, room, extent); - let ideal = Call { proposal: Proposal::Ideal, room, inputs, took: size }; + // Legacy components keep their original ordering: measure before asking whether they fill. + let initial = (!facts.paired_measure).then(|| ask(&mut *t, Proposal::Ideal, room, extent)); // A control in a label scope reports its narrowest width, in a measuring run too: the real run's label step reads // it to decide whether the row fits the label beside it. let in_label = shape == ShapeKind::Leaf && scope::in_label(ctx); @@ -1621,10 +1624,36 @@ fn measure_step( let tells_least = shape == ShapeKind::Leaf && matches!(at, ShowAt::Flow) && [craft_behavior::Axis::X, craft_behavior::Axis::Y].into_iter().any(|axis| fills(axis) && crate::layout::counting_fills(ui, axis)); - let min = (in_label || tells_least).then(|| { - let (took, inputs) = ask(&mut *t, Proposal::Min, None, Vec2::ZERO); - Call { proposal: Proposal::Min, room: None, inputs, took } - }); + let pair = if facts.paired_measure + && (in_label || tells_least || (shape == ShapeKind::Leaf && matches!(shrink, Some(crate::layout::Shrink::Count(_))))) + { + let ideal_input = MeasureIn { ui, env, proposal: Proposal::Ideal, room }; + let least_input = MeasureIn { ui, env, proposal: Proposal::Min, room: None }; + t.measure_content_pair(&ideal_input, &least_input, resolved).map(|((ideal, least), inputs)| { + let size = steps::measure(style, &ideal_input, ideal, extent, resolved); + let least = steps::measure(style, &least_input, least, Vec2::ZERO, resolved); + (size, inputs, least, ideal) + }) + } else { + None + }; + let paired = pair.as_ref().map(|(_, _, least, content)| (*least, *content)); + let (size, ideal, min) = match pair { + Some((size, inputs, least, _)) => { + let ideal = Call { proposal: Proposal::Ideal, room, inputs: inputs.clone(), took: size }; + let min = Call { proposal: Proposal::Min, room: None, inputs, took: least }; + (size, ideal, Some(min)) + } + None => { + let (size, inputs) = initial.unwrap_or_else(|| ask(&mut *t, Proposal::Ideal, room, extent)); + let ideal = Call { proposal: Proposal::Ideal, room, inputs, took: size }; + let min = (in_label || tells_least).then(|| { + let (took, inputs) = ask(&mut *t, Proposal::Min, None, Vec2::ZERO); + Call { proposal: Proposal::Min, room: None, inputs, took } + }); + (size, ideal, min) + } + }; let min_took = min.as_ref().filter(|_| in_label).map(|min| min.took); // A leaf's measure calls are what its body's layout takes from it: a measuring run keeps them in the body's // transcript, and a real run its kept transcript serves checks them against this run's. A leaf shown at a rect @@ -1684,10 +1713,13 @@ fn measure_step( Some(crate::layout::Shrink::Count(row)) if shape == ShapeKind::Leaf => { // The `Ideal` size in no room, and the least width at which its content shows whole. let input = MeasureIn { ui, env, proposal: Proposal::Ideal, room: None }; - let (content, _) = t.measure_content(&input, resolved); + let content = match paired.filter(|_| room.is_none()) { + Some((_, content)) => content, + None => t.measure_content(&input, resolved).0, + }; let ideal = steps::measure(style, &input, content, Vec2::ZERO, resolved).x; let whole = steps::whole(style, content, Vec2::ZERO, resolved); - let least = ask(&mut *t, Proposal::Min, None, Vec2::ZERO).0.x; + let least = paired.map_or_else(|| ask(&mut *t, Proposal::Min, None, Vec2::ZERO).0.x, |(least, _)| least.x); crate::layout::report_shrink(ctx, row, id, size.x, ideal, Some((whole, least)), t.cut_first()); } Some(crate::layout::Shrink::Count(row)) => crate::layout::report_shrink(ctx, row, id, size.x, size.x, None, false), diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index 838a651f1..fd8695ecb 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -176,6 +176,11 @@ impl Erased for Typed<'_, '_, C> { steps::measure_content(self.comp.get(), input, style, resolved, self.shown.as_deref()) } + fn measure_content_pair(&mut self, ideal: &MeasureIn<'_>, least: &MeasureIn<'_>, resolved: &Resolved<'_>) -> Option<((Vec2, Vec2), Inputs)> { + let style = step_style(&self.style); + steps::measure_content_pair(self.comp.get(), ideal, least, style, resolved, self.shown.as_deref()) + } + fn measured_extent(&mut self, at: &Measuring<'_, '_>, stage: &mut MemoryStage) -> Vec2 { let style = step_style(&self.style); let (extent, shown) = measured_extent(self.comp.get(), &mut *self.hooks, at, stage, style, self.shown.take()); diff --git a/crates/ui-contract/src/contract/steps.rs b/crates/ui-contract/src/contract/steps.rs index 3d4f3551e..c4aeec092 100644 --- a/crates/ui-contract/src/contract/steps.rs +++ b/crates/ui-contract/src/contract/steps.rs @@ -29,7 +29,7 @@ pub(crate) use finish::{before_finish, inert_response, record_body_size, record_ pub(super) use id::measuring; pub(crate) use id::{claim_id, draft, id, keeping_ids}; pub(crate) use label::scrub_by_label; -pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_cx, padding, whole}; +pub(crate) use measure::{MeasureIn, guard, measure, measure_content, measure_content_pair, measure_cx, padding, whole}; pub(crate) use paint::{Fade, UnderVeil, fade, next_shape, paint_focus, paint_part_layers, paint_surface, surface_ink, unfade}; pub(crate) use parts::{PartsStep, check_parts, declares_none}; pub(crate) use place::place; diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 6293bebde..41f0bbf28 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -30,6 +30,22 @@ pub(crate) fn measure_content( layout_memory::measure_call(input.ui.ctx(), || comp.measure(&cx)) } +/// Asks a component that supports it for both measures in one call. Both answers share the inputs read by the call, +/// so replay checks each answer under all of those inputs. +pub(crate) fn measure_content_pair( + comp: &mut C, + ideal: &MeasureIn<'_>, + least: &MeasureIn<'_>, + style: &C::Style, + resolved: &Resolved<'_>, + value: Option<&ValueOf>, +) -> Option<((Vec2, Vec2), Inputs)> { + let ideal_cx = measure_cx::(ideal, style, resolved, value); + let least_cx = measure_cx::(least, style, resolved, value); + let (pair, inputs) = layout_memory::measure_call(ideal.ui.ctx(), || comp.measure_pair(&ideal_cx, &least_cx)); + pair.map(|pair| (pair, inputs)) +} + /// Step 5, measure: the `content` size plus padding, then `max(min_size)`, and for any proposal but `Min` at least the /// ideal width, up to the room, unless the component is sized to its content (`sizing`, a leaf's `Sizing::Content`). /// At `Min` a least width the style sets takes the place of `min_size`'s width. `extent` is what the shape adds to the diff --git a/crates/ui-contract/tests/it/layout/fill.rs b/crates/ui-contract/tests/it/layout/fill.rs index 635f450d5..064855127 100644 --- a/crates/ui-contract/tests/it/layout/fill.rs +++ b/crates/ui-contract/tests/it/layout/fill.rs @@ -127,6 +127,7 @@ const LINE: f32 = 20.0; struct Asked { ideal: Cell, min: Cell, + pair: Cell, } /// A leaf `IDEAL` wide that narrows to `LEAST`, whatever its room; it counts the measures it answers in measuring runs. @@ -136,11 +137,13 @@ struct Stretch<'a> { common: Common, seen: &'a RefCell, asked: &'a Asked, + paired: bool, + track_input: bool, } impl<'a> Stretch<'a> { fn new(seen: &'a RefCell, asked: &'a Asked) -> Self { - Stretch { common: Common::new(), seen, asked } + Stretch { common: Common::new(), seen, asked, paired: false, track_input: false } } } @@ -154,6 +157,9 @@ impl Component for Stretch<'_> { } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if self.track_input { + let _ = cx.column_room(); + } let (count, width) = if cx.proposal == Proposal::Min { (&self.asked.min, LEAST) } else { (&self.asked.ideal, IDEAL) }; if is_measuring(cx.ui.ctx()) { count.set(count.get() + 1); @@ -161,6 +167,24 @@ impl Component for Stretch<'_> { Vec2::new(width, LINE) } + const PAIRED_MEASURE: bool = true; + + fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + if !self.paired { + return None; + } + assert_eq!(ideal.proposal, Proposal::Ideal); + assert_eq!(least.proposal, Proposal::Min); + if self.track_input { + let _ = ideal.column_room(); + let _ = least.column_room(); + } + if is_measuring(ideal.ui.ctx()) { + self.asked.pair.set(self.asked.pair.get() + 1); + } + Some((Vec2::new(IDEAL, LINE), Vec2::new(LEAST, LINE))) + } + fn sense(&self) -> Sense { Sense::empty() } @@ -174,6 +198,44 @@ impl Component for Stretch<'_> { } } +/// Compare the paired path with the legacy component calls through a nested filling body and its kept transcript. +fn nested_pair(paired: bool) -> (Rect, Rect, usize, usize, usize) { + let seen = Rc::new(RefCell::new(Seen::default())); + let asked = Rc::new(Asked::default()); + let (shown, counts) = (Rc::clone(&seen), Rc::clone(&asked)); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("outer").show(ui, |ui, _| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("inner").show(ui, |ui, _| { + let mut child = Stretch::new(&shown, &counts); + child.paired = paired; + child.track_input = true; + child.sizing(Sizing::FillWidth).id_salt("child").show(ui); + }); + }); + }); + fixture.room(Vec2::new(200.0, 100.0)).settle(); + let rect = seen.borrow().rect; + let pairs = asked.pair.get(); + let separate_calls = asked.ideal.get() + asked.min.get(); + fixture.idle(3); + let after_idle = asked.pair.get(); + fixture.room(Vec2::new(140.0, 100.0)).settle(); + let resized = seen.borrow().rect; + (rect, resized, pairs, after_idle, separate_calls) +} + +#[trial] +fn paired_measure_matches_separate_calls_through_a_nested_body_and_replay() { + let (separate, separate_resized, _, _, separate_calls) = nested_pair(false); + let (paired, paired_resized, before_idle, after_idle, paired_calls) = nested_pair(true); + assert!(paired.width() > 0.0); + assert!((paired.size() - separate.size()).abs().max_elem() < 0.5, "paired {paired:?}, separate {separate:?}"); + assert!((paired_resized.size() - separate_resized.size()).abs().max_elem() < 0.5, "paired {paired_resized:?}, separate {separate_resized:?}"); + assert!(before_idle > 0, "the nested filling leaf used the paired path"); + assert!(paired_calls < separate_calls, "paired calls {paired_calls}, separate calls {separate_calls}"); + assert_eq!(before_idle, after_idle, "the kept transcript needs no new paired measure on idle frames"); +} + /// The rect of a row that fills a room `width` wide, scrolling along x when `scrolls`, and of the `Stretch` that fills /// its width alone in it. fn stretched(width: f32, scrolls: bool) -> (Rect, Rect) { diff --git a/crates/ui-widgets/src/buttons/button.rs b/crates/ui-widgets/src/buttons/button.rs index e4ea9fdcd..a208b0587 100644 --- a/crates/ui-widgets/src/buttons/button.rs +++ b/crates/ui-widgets/src/buttons/button.rs @@ -210,6 +210,12 @@ impl Component for Button<'_> { face::measure(cx, &self.spec(cx.resolved.label)) } + const PAIRED_MEASURE: bool = true; + + fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + Some(face::measure_pair(ideal, least, &self.spec(ideal.resolved.label))) + } + fn sense(&self) -> Sense { if self.loading { Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS } } diff --git a/crates/ui-widgets/src/buttons/face.rs b/crates/ui-widgets/src/buttons/face.rs index 16494c2f0..27bc12e75 100644 --- a/crates/ui-widgets/src/buttons/face.rs +++ b/crates/ui-widgets/src/buttons/face.rs @@ -168,6 +168,22 @@ pub(crate) fn measure(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>) Vec2::new(text.x + fixed, text.y.max(icon)) } +/// The ideal and least face sizes from one paired component measure. +pub(crate) fn measure_pair(ideal: &MeasureCx<'_, C>, least: &MeasureCx<'_, C>, spec: &FaceSpec<'_>) -> (Vec2, Vec2) { + let icon = ideal.icon(); + let fixed = icon * spec.icons() as f32 + ideal.gap() * spec.gaps() as f32; + let (whole, narrow) = if spec.label.is_empty() { + (Vec2::ZERO, Vec2::ZERO) + } else { + let run = spec.run(); + let whole = ideal.layout_at(&run, ideal.room.map_or(f32::INFINITY, |room| (room - fixed).max(0.0))).size(); + let width = least.least_width(&run); + let height = least.layout_at(&run, f32::INFINITY).size().y; + (whole, Vec2::new(width, height)) + }; + (Vec2::new(whole.x + fixed, whole.y.max(icon)), Vec2::new(narrow.x + fixed, narrow.y.max(icon))) +} + /// `icon` in `color`, unless the spec names a colour of its own. pub(super) fn tinted<'a>(icon: &IconSpec<'a>, color: StyleColor) -> IconSpec<'a> { let icon = icon.clone(); diff --git a/crates/ui-widgets/src/buttons/link.rs b/crates/ui-widgets/src/buttons/link.rs index 7547049da..4c4b7c1d4 100644 --- a/crates/ui-widgets/src/buttons/link.rs +++ b/crates/ui-widgets/src/buttons/link.rs @@ -94,6 +94,20 @@ impl Component for Link { Vec2::new(layout.size().x, painted_height(&layout)) } + const PAIRED_MEASURE: bool = true; + + fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + if !self.cut_first() { + return None; + } + let run = self.run(ideal.resolved.label); + let layout = ideal.layout_at(&run, ideal.room.unwrap_or(f32::INFINITY)); + let ideal_size = Vec2::new(layout.size().x, painted_height(&layout)); + let width = least.least_width(&run); + let whole = least.layout_at(&run, f32::INFINITY); + Some((ideal_size, Vec2::new(width, painted_height(&whole)))) + } + fn update(&mut self, cx: &mut Cx<'_, Self>) { let middle_click = match cx.press().phase { PressPhase::Release { start, click: true, .. } => start.button == PointerButton::Middle, diff --git a/crates/ui-widgets/src/buttons/split_button.rs b/crates/ui-widgets/src/buttons/split_button.rs index bf8fdd083..abd9e5b1d 100644 --- a/crates/ui-widgets/src/buttons/split_button.rs +++ b/crates/ui-widgets/src/buttons/split_button.rs @@ -143,6 +143,15 @@ impl Component for SplitButton<'_, T> { Vec2::new(face.x + cx.icon(), face.y) } + const PAIRED_MEASURE: bool = true; + + fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + let (mut whole, mut narrow) = face::measure_pair(ideal, least, &self.spec(ideal.resolved.label)); + whole.x += ideal.icon(); + narrow.x += least.icon(); + Some((whole, narrow)) + } + fn sense(&self) -> Sense { Sense::CLICK | Sense::FOCUS } diff --git a/crates/ui-widgets/src/buttons/toggle_button.rs b/crates/ui-widgets/src/buttons/toggle_button.rs index bf4ee21b0..936e47df0 100644 --- a/crates/ui-widgets/src/buttons/toggle_button.rs +++ b/crates/ui-widgets/src/buttons/toggle_button.rs @@ -160,6 +160,12 @@ impl Component for ToggleButton<'_> { face::measure(cx, &self.spec(cx.resolved.label, true)) } + const PAIRED_MEASURE: bool = true; + + fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + Some(face::measure_pair(ideal, least, &self.spec(ideal.resolved.label, true))) + } + fn sense(&self) -> Sense { Sense::CLICK | Sense::FOCUS } diff --git a/crates/ui-widgets/src/display/text.rs b/crates/ui-widgets/src/display/text.rs index 666161ab6..b80feac11 100644 --- a/crates/ui-widgets/src/display/text.rs +++ b/crates/ui-widgets/src/display/text.rs @@ -183,6 +183,27 @@ impl Component for Text { } } + const PAIRED_MEASURE: bool = true; + + fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + // Wrapped and document text need their own least-measure logic; keep the separate path for them. + if !self.spans.is_empty() || self.elide == Elide::Off { + return None; + } + let band = ideal.column_room().unwrap_or(f32::INFINITY); + let run = self.run(ideal.style.text.role, ideal.resolved.label); + let layout = ideal.layout_at(&run, band); + let ideal_size = match ideal.room { + Some(room) if layout.elided => Vec2::new(room, layout.size().y), + _ => layout.size(), + }; + // `measure` reads the column room even in its least branch. + let _ = least.column_room(); + let width = least.least_width(&run); + let height = least.layout_at(&run, f32::INFINITY).size().y; + Some((ideal_size, Vec2::new(width, height))) + } + fn cut_first(&self) -> bool { self.elide != Elide::Off } diff --git a/crates/ui-widgets/src/pickers/face.rs b/crates/ui-widgets/src/pickers/face.rs index c4afb34fb..0e5fbf64c 100644 --- a/crates/ui-widgets/src/pickers/face.rs +++ b/crates/ui-widgets/src/pickers/face.rs @@ -209,6 +209,33 @@ impl Component for SelectFace<'_> { Vec2::new(beside + text.x, text.y.max(picture)) } + const PAIRED_MEASURE: bool = true; + + fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { + // A caption may wrap differently under two rooms, so keep the separate path when the ideal has a room. + if ideal.room.is_some() { + return None; + } + let run = TextRun::new(ideal.resolved.label).role(ideal.style.text.role).elide(); + let whole = if self.name { ideal.layout_at(&run, f32::INFINITY).size() } else { Vec2::ZERO }; + let width = if self.name { least.least_width(&run) } else { 0.0 }; + let caption = self.caption_run(&ideal.style.caption).map_or(Vec2::ZERO, |run| ideal.layout(&run).size()); + let picture = match (&self.thumb, caption.y > 0.0) { + (None, _) => 0.0, + (Some(_), false) => ideal.style.thumb, + (Some(_), true) => ideal.style.thumb + ideal.style.caption_gap + caption.y, + }; + let beside = self.lead(ideal.style, caption.x) + reserve(&ideal.style.field, &self.leading_glyphs(), &[Self::chevron()]); + let mut ideal_width = whole.x; + if self.fit && self.name { + let field = ideal.style.field.metrics(); + let room = field.ideal_width - ideal.style.metrics.padding.start - ideal.style.metrics.padding.end - beside; + ideal_width = ideal_width.min(room.max(width)); + } + let height = whole.y.max(picture); + Some((Vec2::new(beside + ideal_width, height), Vec2::new(beside + width, height))) + } + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let chevron = Self::chevron(); let rtl = cx.flow.is_rtl(); From e840877d93bc85e895ec59deb971a2d7d85f7132 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:07:46 +0100 Subject: [PATCH 06/22] Cover cold lazy text mutations --- crates/ui-contract/src/primitives/text.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index f80147731..5dda5c2f7 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -939,7 +939,12 @@ mod memo_tests { assert!(Arc::ptr_eq(&first.galley, &second.galley)); assert!(first.runs.value.get().is_none()); assert!(first.full.value.get().is_none()); + let mut cold = first.clone(); + cold.full.push('?'); + cold.runs.clear(); + assert!(cold.runs().is_empty()); assert_eq!(first.full(), "a label long enough to elide"); + assert_ne!(cold.full(), first.full()); assert!(second.full.value.get().is_some()); let _ = first.runs(); assert!(second.runs.value.get().is_some()); From db604faefb9537a12da3a513ce84679cf2f1d8d1 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:29:33 +0100 Subject: [PATCH 07/22] Reuse prepared steps for adjacent labelled leaves --- crates/ui-contract/src/contract/paint_ui.rs | 33 ++++++- crates/ui-contract/src/contract/run.rs | 40 +++++--- crates/ui-contract/src/contract/run/typed.rs | 96 +++++++++++++++++- crates/ui-contract/src/runtime/env.rs | 5 + crates/ui-contract/src/runtime/measure.rs | 29 ++++++ crates/ui-contract/src/testing/mod.rs | 2 +- crates/ui-contract/tests/it/contract/mod.rs | 1 + .../ui-contract/tests/it/contract/prepared.rs | 99 +++++++++++++++++++ 8 files changed, 288 insertions(+), 17 deletions(-) create mode 100644 crates/ui-contract/tests/it/contract/prepared.rs diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index db26e8ca6..9de6e2ee9 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -166,11 +166,18 @@ impl PaintUi<'_> { layout_memory::boundary(&ctx, true, || { let placed = crate::layout::ColumnGroup::field(&mut *self.ui, |ui| label::leaf(ui, &env, &at, &mut child, None)); let mut control = placed.control; + let mut prepared = None; if child.fills() != Some(craft_behavior::Axis::Y) { - let ideal = run::measure_under(&mut child, &*self.ui, Some(id), craft_behavior::Proposal::Ideal, Some(&under)); + let ideal = if self.fade.is_none() { + let (ideal, kept) = run::measure_under_prepared(&mut child, &*self.ui, id, craft_behavior::Proposal::Ideal, &under); + prepared = kept; + ideal + } else { + run::measure_under(&mut child, &*self.ui, Some(id), craft_behavior::Proposal::Ideal, Some(&under)) + }; control.max.y = control.max.y.min(control.min.y + ideal.y); } - let output = self.child_with(id, control, child, None, under.inside.clone()); + let output = self.child_with_prepared(id, control, child, None, under.inside.clone(), prepared); placed.finish(&ctx); output }) @@ -179,6 +186,18 @@ impl PaintUi<'_> { /// Shows `child` at `rect` under the composite's `enabled` and `size`, and `inside`, the inside label of the side /// label the child is the control of. fn child_with(&mut self, id: Id, rect: Rect, child: C, tip: Option>, inside: Option>) -> C::Output { + self.child_with_prepared(id, rect, child, tip, inside, None) + } + + fn child_with_prepared( + &mut self, + id: Id, + rect: Rect, + child: C, + tip: Option>, + inside: Option>, + prepared: Option>, + ) -> C::Output { let scope = sub(self.id, "children"); let parent = &mut *self.ui; let kids = self.kids.get_or_insert_with(|| { @@ -186,7 +205,10 @@ impl PaintUi<'_> { alloc::child(parent, access::with_parent(builder, self.id)) }); let ctx = kids.ctx().clone(); - let env = super::cx::child_env(&Env::of(kids), &super::cx::Under { enabled: self.enabled, size: self.size, inside }); + let source = Env::of(kids); + let child = super::Props::id(child, id); + let prepared = prepared.filter(|prepared| self.fade.is_none() && prepared.matches(&child, &source)); + let env = super::cx::child_env(&source, &super::cx::Under { enabled: self.enabled, size: self.size, inside }); // A child shown while the owner's fade runs lies under the owner's veil, so a faded child adds none of its own. let env = match self.fade { Some(_) => { @@ -200,7 +222,10 @@ impl PaintUi<'_> { let installed = Env::install_for(kids, env); // The child sits in a rect its owner chose, and the owner's own measure answers for it: no body's transcript // holds it. - let output = layout_memory::boundary(&ctx, true, || run::show_leaf(&mut Some(super::Props::id(child, id)), kids, ShowAt::Rect(rect), tip)); + let output = layout_memory::boundary(&ctx, true, || match prepared { + Some(prepared) => run::show_leaf_prepared(&mut Some(child), kids, ShowAt::Rect(rect), tip, prepared), + None => run::show_leaf(&mut Some(child), kids, ShowAt::Rect(rect), tip), + }); Env::restore(&ctx, installed); output } diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 4671f66a7..67922c122 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -29,8 +29,8 @@ use std::sync::Arc; mod typed; pub(crate) use typed::{ - MemberNode, MemberPrep, MemberShown, measure_container, measure_under, measured_extent, member_prepare, member_show, paint_face, show_container, - show_container_taking, show_items, show_leaf, + MemberNode, MemberPrep, MemberShown, PreparedLeaf, measure_container, measure_under, measure_under_prepared, measured_extent, member_prepare, + member_show, paint_face, show_container, show_container_taking, show_items, show_leaf, show_leaf_prepared, }; /// Where a component is placed. @@ -1387,22 +1387,31 @@ fn measured(t: &mut dyn Erased, input: &MeasureIn<'_>, style: &dyn StyleView, re /// 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) struct PreparedStep { + step1: steps::EnvStep, + style: Arc, +} + pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { + run_with(t, ui, at, tip, None); +} + +fn run_with(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, prepared: 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)); + crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || run_steps(t, ui, at, tip, prepared)); } - None => run_steps(t, ui, at, tip), + None => run_steps(t, ui, at, tip, prepared), } } /// Steps 1 to 17 of `run`. A component's children run inside step 5 (a body's measuring run) and inside the passes /// of steps 6 to 16, so the frames on that path keep only what the run reads after them: each step runs in its own /// function, and `run_steps` holds what steps 1 to 5 found. -fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { - let begun = begin(t, ui); +fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, prepared: Option) { + let begun = begin(t, ui, prepared); let mut stage = begun.open_stage(t); let mixed = value_step(t, &begun, &mut stage); let resolved = begun.resolved(t); @@ -1467,7 +1476,7 @@ impl Begun { /// Steps 1 to 3: env, style and id. // Kept out of the recursive frame above it: opt-level 2 inlines it there, so its locals stay on the stack while children run. #[inline(never)] -fn begin(t: &mut dyn Erased, ui: &Ui) -> Begun { +fn begin(t: &mut dyn Erased, ui: &Ui, prepared: Option) -> Begun { let ctx = ui.ctx().clone(); let facts = t.facts(); crate::runtime::measure::count_run(&ctx, facts.name); @@ -1484,9 +1493,14 @@ fn begin(t: &mut dyn Erased, ui: &Ui) -> Begun { // scope, and everything it shows inherits it. let env = scoped_env(&ctx, Env::of(ui), t.theme_scope()); let common: Common = t.take_common(); - let step1 = steps::env(&ctx, &env, &common, t.variants(common.variant)); - // 2 style - let style = t.style(&ctx, &steps::style_cx(&ctx, &env, &step1)); + let (step1, style) = match prepared { + Some(prepared) => (prepared.step1, prepared.style), + None => { + let step1 = steps::env(&ctx, &env, &common, t.variants(common.variant)); + let style = t.style(&ctx, &steps::style_cx(&ctx, &env, &step1)); + (step1, style) + } + }; // 3 id let id = steps::id(ui, &common.id, !sizing, true, facts.style_key, facts.name); if recording { @@ -1843,6 +1857,10 @@ fn scoped_env(ctx: &Context, env: Env, theme: Option) -> Env { /// use next (or `id`). It reads memory through a peek, registers no id and applies nothing. `under` is the /// composite's resolved `(enabled, size)` when it measures a child it shows with `PaintUi::child`. pub(super) fn measure_shape(t: &mut dyn Erased, ui: &Ui, id: Option, proposal: Proposal, under: Option<&super::cx::Under>) -> Vec2 { + measure_shape_with(t, ui, id, proposal, under).0 +} + +fn measure_shape_with(t: &mut dyn Erased, ui: &Ui, id: Option, proposal: Proposal, under: Option<&super::cx::Under>) -> (Vec2, steps::EnvStep) { let facts = t.facts(); let env = match under { Some(under) => super::cx::child_env(&Env::of(ui), under), @@ -1879,7 +1897,7 @@ pub(super) fn measure_shape(t: &mut dyn Erased, ui: &Ui, id: Option, proposa if let Some(key) = t.bind_key(id) { reads::note(ui.ctx(), key, id, true, &[Sample { proposal, room: None, took }]); } - took + (took, step1) } /// The flags a host passes to its faces: the validity of its value. The rest (focus, selection, open) belong to the diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index fd8695ecb..36597e9fd 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -12,7 +12,7 @@ use crate::contract::{ use crate::primitives::{FaceRecord, face_id}; use crate::runtime::access::{Politeness, SetPosition}; use crate::runtime::commands::{self, ResolvedCommand}; -use crate::runtime::env::{AppValues, Env, Message, ThemeScope}; +use crate::runtime::env::{AppValues, Env, Label, Message, ThemeScope}; use crate::runtime::focus; use crate::runtime::layout_memory::Inputs; use crate::runtime::memory::{MemoryStage, sub}; @@ -529,6 +529,100 @@ fn measure_shape( super::measure_shape(&mut Typed::new(Held::Lent(comp), hooks), ui, id, proposal, under) } +/// Step 1 and style from a measure immediately followed by a show of the same leaf. +pub(crate) struct PreparedLeaf { + source: Env, + inputs: StepInputs, + style_key: C::StyleKey, + step1: steps::EnvStep, + style: Arc, +} + +#[derive(PartialEq)] +struct StepInputs { + label: Label, + enabled: Option, + read_only: Option, + size: Option, + glyphs: Option, + variant: Option, +} + +impl StepInputs { + fn of(common: &Common) -> Option { + // A command or catalogue word can change independently during measure; disabled children get a different + // inherited env in the label step. Those cases take the ordinary path. + if common.command.is_some() || matches!(&common.label, Label::Word(_)) || common.enabled == Some(false) { + return None; + } + Some(Self { + label: common.label.clone(), + enabled: common.enabled, + read_only: common.read_only, + size: common.size, + glyphs: common.glyphs, + variant: common.variant, + }) + } +} + +impl PreparedLeaf { + pub(crate) fn matches(&self, child: &C, source: &Env) -> bool { + self.source.same_source(source) + && StepInputs::of(child.common(Internal::new())).as_ref() == Some(&self.inputs) + && child.style_key() == self.style_key + } +} + +/// Measures a leaf and keeps its steps only when the same component and scope are still present afterwards. +pub(crate) fn measure_under_prepared( + comp: &mut C, + ui: &Ui, + id: Id, + proposal: Proposal, + under: &crate::contract::cx::Under, +) -> (Vec2, Option>) { + let Some(inputs) = StepInputs::of(comp.common(Internal::new())) else { + return (measure_under(comp, ui, Some(id), proposal, Some(under)), None); + }; + let source = Env::of(ui); + let key = comp.style_key(); + let mut hooks = LeafHooks { scope: None }; + let mut typed = Typed::new(Held::Lent(comp), &mut hooks); + let (size, step1) = super::measure_shape_with(&mut typed, ui, Some(id), proposal, Some(under)); + let style = typed.style.clone(); + drop(typed); + let prepared = style.and_then(|style| { + (source.same_source(&Env::of(ui)) && StepInputs::of(comp.common(Internal::new())).as_ref() == Some(&inputs) && comp.style_key() == key) + .then_some(PreparedLeaf { source, inputs, style_key: key, step1, style }) + }); + (size, prepared) +} + +/// Shows the same leaf with steps kept by `measure_under_prepared`. +pub(crate) fn show_leaf_prepared( + slot: &mut Option, + ui: &mut Ui, + at: ShowAt, + tip: Option>, + prepared: PreparedLeaf, +) -> C::Output { + let PreparedLeaf { step1, style, .. } = prepared; + #[cfg(feature = "testing")] + { + crate::runtime::measure::count_prepared_leaf(ui.ctx()); + let env = Env::of(ui); + let scx = steps::style_cx(ui.ctx(), &env, &step1); + crate::testing::style::record::(ui.ctx(), &scx, held(slot).style_key(), &style); + } + let mut hooks = LeafHooks { scope: held(slot).common(Internal::new()).command_scope }; + let mut typed = Typed::owned(slot, &mut hooks); + typed.style = Some(Arc::clone(&style)); + let style: Arc = style; + super::run_with(&mut typed, ui, at, tip, Some(super::PreparedStep { step1, style })); + typed.output() +} + pub(crate) fn show_leaf>( slot: &mut Option, ui: &mut Ui, diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 151339c28..82f35e533 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -416,6 +416,11 @@ impl EnvCapture { } impl Env { + /// Whether both views come from the same immutable scope. A derived scope has a different source. + pub(crate) fn same_source(&self, other: &Env) -> bool { + Arc::ptr_eq(&self.scoped, &other.scoped) + } + /// The word set `L` in the scope's language. pub fn words(&self) -> Arc { self.words.set::() diff --git a/crates/ui-contract/src/runtime/measure.rs b/crates/ui-contract/src/runtime/measure.rs index c281c04a5..18cfbd3c7 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -214,6 +214,35 @@ pub fn body_runs(ctx: &Context) -> Vec<(Id, u32)> { store::with::(ctx, |log| log.runs.clone()) } +/// Adjacent leaf measures whose environment and style steps were reused in the current pass. +#[cfg(feature = "testing")] +#[derive(Default)] +struct PreparedLeafCounts { + pass: u64, + count: u32, +} + +#[cfg(feature = "testing")] +pub(crate) fn count_prepared_leaf(ctx: &Context) { + if active(ctx) { + return; + } + let pass = ctx.cumulative_pass_nr(); + store::with::(ctx, |counts| { + if counts.pass != pass { + *counts = PreparedLeafCounts { pass, count: 0 }; + } + counts.count += 1; + }); +} + +/// Adjacent leaf measures whose steps were reused in the last pass. +#[cfg(feature = "testing")] +pub fn last_pass_prepared_leaves(ctx: &Context) -> u32 { + let last = ctx.cumulative_pass_nr().saturating_sub(1); + store::with::(ctx, |counts| if counts.pass == last { counts.count } else { 0 }) +} + /// Counts a run of a component of the type `name` in this pass, measuring or real. Counts nothing without `testing`. pub(crate) fn count_run(ctx: &Context, name: &'static str) { #[cfg(feature = "testing")] diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 90ed467df..ca8eb5af4 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -42,7 +42,7 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::measure::{ active as is_measuring, body_runs as measuring_runs, contributions as measured_contributions, last_pass_body_runs as last_pass_measuring_runs, - last_pass_runs, least_runs as shrink_least_runs, row_measures, run as measuring_run, take_effects, widest_runs, + last_pass_prepared_leaves, last_pass_runs, least_runs as shrink_least_runs, 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-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index b37aa95dc..4687f5694 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -5,5 +5,6 @@ mod gesture; mod hit_order; mod pages; mod pointer; +mod prepared; mod style; mod visited_type; diff --git a/crates/ui-contract/tests/it/contract/prepared.rs b/crates/ui-contract/tests/it/contract/prepared.rs new file mode 100644 index 000000000..87b95262d --- /dev/null +++ b/crates/ui-contract/tests/it/contract/prepared.rs @@ -0,0 +1,99 @@ +//! Adjacent measurement and show reuse only unchanged environment and style inputs. + +use craft_behavior::{Proposal, Sense}; +use craft_ui::contract::{Common, Component, Cx, MeasureCx, PaintUi, Props as _, Role, Show as _, SideLabel}; +use craft_ui::style::{ComponentStyle as _, StyleCx}; +use craft_ui::testing::{Fixture, last_pass_prepared_leaves, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Response, Vec2}; +use std::cell::Cell; +use std::rc::Rc; + +#[derive(Component)] +struct Child { + #[common] + common: Common, + #[style_key] + changed: bool, + mutate: bool, + seen: Rc>, +} + +impl Component for Child { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, key: ChildStyleKey) -> PlainStyle { + PlainStyle::min(Vec2::new(if key.changed { 40.0 } else { 20.0 }, 20.0)) + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if self.mutate && cx.proposal == Proposal::Ideal { + self.changed = true; + } + Vec2::new(10.0, 20.0) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + self.seen.set(cx.style.metrics().min_size.x); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[derive(Component)] +struct Owner { + #[common] + common: Common, + mutate: bool, + seen: Rc>, +} + +impl Component for Owner { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: OwnerStyleKey) -> PlainStyle { + PlainStyle::min(Vec2::new(200.0, 50.0)) + } + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let child = Child { common: Common::new(), changed: false, mutate: self.mutate, seen: self.seen.clone() }; + ui.labelled("child", cx.rect, "Caption".into(), SideLabel::new(), child); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +fn show(mutate: bool) -> (u32, f32) { + let seen = Rc::new(Cell::new(0.0)); + let output = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + Owner { common: Common::new(), mutate, seen: output.clone() }.id_salt("owner").show(ui); + }); + fixture.frame(Vec::new()); + (last_pass_prepared_leaves(fixture.ctx()), seen.get()) +} + +#[trial] +fn adjacent_leaf_reuses_steps_only_while_its_style_key_is_unchanged() { + let (reused, unchanged) = show(false); + assert!(reused > 0, "unchanged child reuses its adjacent measure steps"); + assert_eq!(unchanged, 20.0); + let (reused, changed) = show(true); + assert_eq!(reused, 0, "a changed style key uses the ordinary path"); + assert_eq!(changed, 40.0, "the shown child receives its changed style"); +} From bb7314039e33578de5a8798c5169b2552d4276ad Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:21:47 +0100 Subject: [PATCH 08/22] Share word-width measurement across wrapping text proposals --- crates/ui-widgets/src/display/text.rs | 68 +++++++++++++-------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/crates/ui-widgets/src/display/text.rs b/crates/ui-widgets/src/display/text.rs index b80feac11..ab56942a6 100644 --- a/crates/ui-widgets/src/display/text.rs +++ b/crates/ui-widgets/src/display/text.rs @@ -103,6 +103,26 @@ impl Text { self } + fn widest_word(&self, cx: &MeasureCx<'_, Self>) -> f32 { + let role = cx.style.text.role; + cx.resolved.label.split_whitespace().map(|word| cx.layout_at(&self.run(role, word), f32::INFINITY).size().x).fold(0.0, f32::max) + } + + fn ideal_plain(&self, cx: &MeasureCx<'_, Self>, run: &TextRun<'_>, band: f32, widest: Option) -> Vec2 { + let mut layout = cx.layout_at(run, band); + // A row can offer less than a word. Its shrink step will make room for the word. + if self.elide == Elide::Off && layout.galley.rows.len() > 1 { + let widest = widest.unwrap_or_else(|| self.widest_word(cx)); + if widest > band { + layout = cx.layout_at(run, widest); + } + } + match cx.room { + Some(room) if layout.elided => Vec2::new(room, layout.size().y), + _ => layout.size(), + } + } + fn doc(&self) -> DocText<'_> { let doc = DocText::new(&self.spans); if self.elide == Elide::Off { doc } else { doc.elide() } @@ -153,52 +173,32 @@ impl Component for Text { _ => layout.size(), }; } - let role = cx.style.text.role; - // A line breaks between words, never inside one: a wrapped text is never narrower than its widest word. - let widest = - || cx.resolved.label.split_whitespace().map(|word| cx.layout_at(&self.run(role, word), f32::INFINITY).size().x).fold(0.0, f32::max); - if cx.proposal == Proposal::Min && self.elide == Elide::Off { - let widest = widest(); - return Vec2::new(widest, cx.layout_at(&self.run(role, cx.resolved.label), widest).size().y); - } - // At its least an elided line is at its readable least. + let run = self.run(cx.style.text.role, cx.resolved.label); if cx.proposal == Proposal::Min { - let run = self.run(role, cx.resolved.label); + if self.elide == Elide::Off { + let widest = self.widest_word(cx); + return Vec2::new(widest, cx.layout_at(&run, widest).size().y); + } return Vec2::new(cx.least_width(&run), cx.layout_at(&run, f32::INFINITY).size().y); } - let band = wrap.unwrap_or(f32::INFINITY); - let mut layout = cx.layout_at(&self.run(role, cx.resolved.label), band); - // In a row the room is what the earlier siblings left, which can be less than a word; the row's shrink step - // then makes room for the word. - if self.elide == Elide::Off && layout.galley.rows.len() > 1 { - let widest = widest(); - if widest > band { - layout = cx.layout_at(&self.run(role, cx.resolved.label), widest); - } - } - // A cut line takes the whole room: its width must not follow where the last glyph happened to fit. - match cx.room { - Some(room) if layout.elided => Vec2::new(room, layout.size().y), - _ => layout.size(), - } + self.ideal_plain(cx, &run, wrap.unwrap_or(f32::INFINITY), None) } const PAIRED_MEASURE: bool = true; fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { - // Wrapped and document text need their own least-measure logic; keep the separate path for them. - if !self.spans.is_empty() || self.elide == Elide::Off { + if !self.spans.is_empty() { return None; } let band = ideal.column_room().unwrap_or(f32::INFINITY); - let run = self.run(ideal.style.text.role, ideal.resolved.label); - let layout = ideal.layout_at(&run, band); - let ideal_size = match ideal.room { - Some(room) if layout.elided => Vec2::new(room, layout.size().y), - _ => layout.size(), - }; - // `measure` reads the column room even in its least branch. let _ = least.column_room(); + let run = self.run(ideal.style.text.role, ideal.resolved.label); + if self.elide == Elide::Off { + let widest = self.widest_word(least); + let ideal_size = self.ideal_plain(ideal, &run, band, Some(widest)); + return Some((ideal_size, Vec2::new(widest, least.layout_at(&run, widest).size().y))); + } + let ideal_size = self.ideal_plain(ideal, &run, band, None); let width = least.least_width(&run); let height = least.layout_at(&run, f32::INFINITY).size().y; Some((ideal_size, Vec2::new(width, height))) From de5472ff34eece0e7bb2b7044de74ab172bb3937 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:31:58 +0100 Subject: [PATCH 09/22] Use explicit imports in text memo trials --- crates/ui-contract/src/primitives/text.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 5dda5c2f7..c41e646fe 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -921,7 +921,9 @@ impl ReadingMeasure { #[cfg(feature = "testing")] mod memo_tests { - use super::*; + use super::{ + Arc, Color32, Context, Cow, Direction, HAlign, LayoutRun, Span, StackFacts, StyleColor, TextEnv, TextRun, TypeRole, UiTokens, Wrap, with_memo, + }; use crate::testing::trial; use craft_theme::{Appearance, Contrast, Mode, Size, TextSize, builtins, resolve}; From d26057203e7be88f956c78e4b8124fa60cd4ef4c Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:41:39 +0100 Subject: [PATCH 10/22] Cover conditional nested body measurement --- crates/ui-contract/tests/it/layout/body.rs | 78 ++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index 7857a3ef7..3be63ec8d 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -63,6 +63,84 @@ const TEXT: f32 = 240.0; const WORD: f32 = 60.0; const LINE: f32 = 20.0; +#[trial] +fn a_fill_before_a_wrapping_sibling_keeps_its_geometry_after_replay_and_resize() { + let rects = Rc::new(Cell::new([Rect::NOTHING; 2])); + let shown = Rc::clone(&rects); + let mut fixture = Fixture::new(move |ui| { + let (fill, wrap) = (RefCell::new(Seen::default()), RefCell::new(Seen::default())); + let measures = Measures::default(); + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("row").show(ui, |ui, _| { + Probe::new(&fill).size(Vec2::new(20.0, LINE)).sizing(Sizing::FillWidth).id_salt("fill").show(ui); + Wrap::new(&wrap, &measures).id_salt("wrap").show(ui); + }); + shown.set([fill.borrow().rect, wrap.borrow().rect]); + }); + for width in [400.0, 240.0, 400.0] { + fixture.room(Vec2::new(width, 400.0)).settle(); + let [fill, wrap] = rects.get(); + assert!(fill.width() > 0.0 && wrap.width() >= WORD - SLACK, "fill and wrap are visible: {fill:?}, {wrap:?}"); + assert!(fill.max.x <= wrap.min.x + SLACK, "wrap follows fill: {fill:?}, {wrap:?}"); + fixture.idle(3); + let replayed = rects.get(); + assert_eq!([fill, wrap], replayed, "replay preserves the measured geometry"); + } +} + +#[derive(Component)] +struct ConditionalDemand { + #[common] + common: Common, +} + +impl Component for ConditionalDemand { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: ConditionalDemandStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + Vec2::new(if cx.proposal == Proposal::Min { 10.0 } else { 100.0 }, LINE) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[trial] +fn a_nested_body_can_have_different_children_in_its_least_probe() { + let saw = Rc::new(RefCell::new(Vec::new())); + let found = Rc::clone(&saw); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("outer").show(ui, |ui, _| { + Panel::new().layout(BodyLayout::row()).id_salt("nested").show(ui, |ui, _| { + ConditionalDemand { common: Common::new() }.id_salt("a").show(ui); + let width = ui.available_rect_before_wrap().width(); + let unbounded = !width.is_finite(); + if is_measuring(ui.ctx()) { + found.borrow_mut().push(width); + } + if unbounded { + Block::new(Vec2::new(200.0, LINE)).show(ui); + } + }); + Block::new(Vec2::new(180.0, LINE)).show(ui); + }); + }); + fixture.room(Vec2::new(200.0, 300.0)).settle(); + assert!(!craft_ui::testing::shrink_least_runs(fixture.ctx()).is_empty(), "the outer row ran its least probe"); + let saw = saw.borrow(); + assert!(saw.iter().any(|width| width.is_finite()) && saw.iter().any(|width| !width.is_finite()), "observed {saw:?}"); +} + /// How many ideal measures a `Wrap` answered in measuring runs, without a room and in one. #[derive(Default)] struct Measures { From e605a842181275b40677ae44fc97d55982460b4b Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 12:50:00 +0100 Subject: [PATCH 11/22] Verify nested transcript reuse and fallback --- crates/ui-contract/tests/it/layout/fill.rs | 34 ++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/crates/ui-contract/tests/it/layout/fill.rs b/crates/ui-contract/tests/it/layout/fill.rs index 064855127..a63079fd2 100644 --- a/crates/ui-contract/tests/it/layout/fill.rs +++ b/crates/ui-contract/tests/it/layout/fill.rs @@ -236,6 +236,40 @@ fn paired_measure_matches_separate_calls_through_a_nested_body_and_replay() { assert_eq!(before_idle, after_idle, "the kept transcript needs no new paired measure on idle frames"); } +#[trial] +fn a_nested_body_reuses_a_settled_transcript_and_remeasures_after_its_room_changes() { + let seen = Rc::new(RefCell::new(Seen::default())); + let asked = Rc::new(Asked::default()); + let sweeps = Rc::new(Cell::new(0)); + let (shown, counts, swept) = (Rc::clone(&seen), Rc::clone(&asked), Rc::clone(&sweeps)); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("outer").show(ui, |ui, _| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("inner").show(ui, |ui, _| { + if is_measuring(ui.ctx()) { + swept.set(swept.get() + 1); + } + let mut child = Stretch::new(&shown, &counts); + child.paired = true; + child.track_input = true; + child.sizing(Sizing::FillWidth).id_salt("child").show(ui); + }); + }); + }); + fixture.room(Vec2::new(240.0, 100.0)).settle(); + assert!(sweeps.get() > 0 && asked.pair.get() > 0, "the first layout measures the nested body"); + let before = seen.borrow().rect; + sweeps.set(0); + asked.pair.set(0); + fixture.idle(3); + assert_eq!(sweeps.get(), 0, "a kept transcript skips nested measuring sweeps"); + assert_eq!(asked.pair.get(), 0, "recorded inputs need no paired measurement on idle"); + assert_eq!(seen.borrow().rect, before, "replay keeps the same geometry"); + fixture.room(Vec2::new(140.0, 100.0)).settle(); + assert!(sweeps.get() > 0 && asked.pair.get() > 0, "a changed room takes the measuring fallback"); + let after = seen.borrow().rect; + assert!((before.width() - after.width()).abs() > 0.5, "the changed input updates geometry: {before:?} -> {after:?}"); +} + /// The rect of a row that fills a room `width` wide, scrolling along x when `scrolls`, and of the `Stretch` that fills /// its width alone in it. fn stretched(width: f32, scrolls: bool) -> (Rect, Rect) { From 7d3437841b8285bf5733b637f7ee56a7a0d71ad6 Mon Sep 17 00:00:00 2001 From: FredApps Date: Thu, 19 Nov 2026 13:47:09 +0100 Subject: [PATCH 12/22] Use theme colours in text memo trials --- crates/ui-contract/src/primitives/text.rs | 26 +++++++++++++++++------ 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index c41e646fe..865e4907d 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -922,7 +922,7 @@ impl ReadingMeasure { #[cfg(feature = "testing")] mod memo_tests { use super::{ - Arc, Color32, Context, Cow, Direction, HAlign, LayoutRun, Span, StackFacts, StyleColor, TextEnv, TextRun, TypeRole, UiTokens, Wrap, with_memo, + Arc, Context, Cow, Direction, HAlign, LayoutRun, Span, StackFacts, StyleColor, TextEnv, TextRun, TypeRole, UiTokens, Wrap, with_memo, }; use crate::testing::trial; use craft_theme::{Appearance, Contrast, Mode, Size, TextSize, builtins, resolve}; @@ -934,7 +934,12 @@ mod memo_tests { let tokens = UiTokens::new(Arc::new(resolve(&builtins()[0], appearance, None).tokens), Contrast::Standard, Size::Compact); let ctx = Context::default(); let mut output = ctx.run_pass(Default::default(), |ctx| { - let env = TextEnv { tokens: &tokens, direction: Direction::Ltr, ink: Color32::WHITE, fonts: StackFacts::default() }; + let env = TextEnv { + tokens: &tokens, + direction: Direction::Ltr, + ink: crate::style::rgba_color(tokens.tokens().color.text.normal), + fonts: StackFacts::default(), + }; let run = TextRun::new("a label long enough to elide").elide(); let first = run.layout(ctx, &env, 80.0); let second = run.layout(ctx, &env, 80.0); @@ -1001,7 +1006,7 @@ mod memo_tests { changed.spans[0].strong = true; variants.push(changed); let mut changed = run.clone(); - changed.color = Some(StyleColor(Color32::BLUE)); + changed.color = Some(StyleColor(crate::style::rgba_color(tokens.tokens().color.text.muted))); variants.push(changed); let mut changed = run.clone(); changed.role = TypeRole::Body; @@ -1026,7 +1031,8 @@ mod memo_tests { } let rtl = TextEnv { direction: Direction::Rtl, ..env }; let _ = run.layout(ctx, &rtl, 80.0); - let ink = TextEnv { ink: Color32::RED, ..env }; + let ink = TextEnv { ink: crate::style::rgba_color(tokens.tokens().color.text.muted), ..env }; + assert_ne!(ink.ink, env.ink); let _ = run.layout(ctx, &ink, 80.0); let fonts = TextEnv { fonts: StackFacts { semibold: true, ..env.fonts }, ..env }; let _ = run.layout(ctx, &fonts, 80.0); @@ -1060,7 +1066,12 @@ mod memo_tests { let tokens = UiTokens::new(Arc::new(resolve(&builtins()[0], appearance, None).tokens), Contrast::Standard, Size::Compact); let ctx = Context::default(); let run = TextRun::new("the initial label for the cache trial").wrap(Wrap::Wrap); - let env = TextEnv { tokens: &tokens, direction: Direction::Ltr, ink: Color32::WHITE, fonts: StackFacts::default() }; + let env = TextEnv { + tokens: &tokens, + direction: Direction::Ltr, + ink: crate::style::rgba_color(tokens.tokens().color.text.normal), + fonts: StackFacts::default(), + }; let mut output = ctx.run_pass(Default::default(), |ctx| { let _ = run.layout(ctx, &env, 80.0); let _ = run.layout(ctx, &env, 120.0); @@ -1077,9 +1088,10 @@ mod memo_tests { assert_eq!(ctx.fonts(|fonts| fonts.num_galleys_in_cache()), before + 2); }); output.textures_delta.clear(); - ctx.set_pixels_per_point(2.0); + let scale = 2.0; + ctx.set_pixels_per_point(scale); let mut output = ctx.run_pass(Default::default(), |ctx| { - assert_eq!(ctx.pixels_per_point(), 2.0); + assert_eq!(ctx.pixels_per_point(), scale); let _ = run.layout(ctx, &env, 80.0); let after = with_memo(ctx, |memo| memo.order.len()); let _ = run.layout(ctx, &env, 80.0); From e61b412dd3db5906f558afc05cf6b10c7b1fc1c6 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 03:56:04 +0100 Subject: [PATCH 13/22] Guard prepared leaf and text memo inputs --- crates/ui-contract/src/contract/paint_ui.rs | 4 +- crates/ui-contract/src/primitives/text.rs | 14 +++- .../ui-contract/tests/it/contract/prepared.rs | 78 +++++++++++++++++++ 3 files changed, 94 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 9de6e2ee9..f2c31e145 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -168,7 +168,9 @@ impl PaintUi<'_> { let mut control = placed.control; let mut prepared = None; if child.fills() != Some(craft_behavior::Axis::Y) { - let ideal = if self.fade.is_none() { + // The minimum measure above may have changed the child's enabled state. In that + // case `under` can differ from what the child inherits when it is shown. + let ideal = if self.fade.is_none() && under.enabled == self.enabled { let (ideal, kept) = run::measure_under_prepared(&mut child, &*self.ui, id, craft_behavior::Proposal::Ideal, &under); prepared = kept; ideal diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 865e4907d..8e6ebe4b7 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -231,6 +231,7 @@ pub(crate) fn line_baseline(ctx: &Context, env: &TextEnv<'_>, role: TypeRole, ce struct LayoutKey { run: TextRun<'static>, tokens: u64, + token_values: Arc, direction: Direction, ink: Color32, fonts: StackFacts, @@ -242,6 +243,7 @@ struct LayoutKey { struct LayoutQuery<'a> { run: &'a TextRun<'a>, tokens: u64, + token_values: &'a Arc, direction: Direction, ink: Color32, fonts: StackFacts, @@ -296,6 +298,7 @@ impl LayoutQuery<'_> { fn matches(&self, key: &LayoutKey) -> bool { key.run == *self.run && key.tokens == self.tokens + && (Arc::ptr_eq(&key.token_values, self.token_values) || key.token_values.as_ref() == self.token_values.as_ref()) && key.direction == self.direction && key.ink == self.ink && key.fonts == self.fonts @@ -331,6 +334,7 @@ impl LayoutQuery<'_> { rotation: self.run.rotation, }, tokens: self.tokens, + token_values: Arc::clone(self.token_values), direction: self.direction, ink: self.ink, fonts: self.fonts, @@ -377,10 +381,11 @@ impl TextMemo { impl TextRun<'_> { /// All inputs read by `job`, the cutting and row-alignment steps. - fn layout_key<'a>(&'a self, ctx: &Context, env: &TextEnv<'_>, max_width: f32) -> LayoutQuery<'a> { + fn layout_key<'a>(&'a self, ctx: &Context, env: &'a TextEnv<'_>, max_width: f32) -> LayoutQuery<'a> { LayoutQuery { run: self, tokens: env.tokens.key(), + token_values: env.tokens.tokens(), direction: env.direction, ink: env.ink, fonts: env.fonts, @@ -1041,9 +1046,16 @@ mod memo_tests { let fonts = TextEnv { fonts: StackFacts { line_ratio: 1.25, ..env.fonts }, ..env }; let _ = run.layout(ctx, &fonts, 80.0); let mut changed_tokens = (**tokens.tokens()).clone(); + let equal_tokens = UiTokens::new(Arc::new(changed_tokens.clone()), Contrast::Standard, Size::Compact); + let equal_env = TextEnv { tokens: &equal_tokens, ..env }; + let equal_key = run.layout_key(ctx, &equal_env, 80.0); + with_memo(ctx, |memo| assert!(memo.get(&equal_key).is_some(), "equal token values from distinct Arcs may reuse the entry")); changed_tokens.color.text.muted = craft_theme::Rgba([12, 34, 56, 255]); let changed_tokens = UiTokens::new(Arc::new(changed_tokens), Contrast::Standard, Size::Compact); let styled = TextEnv { tokens: &changed_tokens, ..env }; + let mut collision = run.layout_key(ctx, &styled, 80.0); + collision.tokens = tokens.key(); + with_memo(ctx, |memo| assert!(memo.get(&collision).is_none(), "a token-hash collision must not reuse a different token set")); let _ = run.layout(ctx, &styled, 80.0); let before = with_memo(ctx, |memo| memo.order.len()); assert_eq!(before, 25); diff --git a/crates/ui-contract/tests/it/contract/prepared.rs b/crates/ui-contract/tests/it/contract/prepared.rs index 87b95262d..af1555e6e 100644 --- a/crates/ui-contract/tests/it/contract/prepared.rs +++ b/crates/ui-contract/tests/it/contract/prepared.rs @@ -97,3 +97,81 @@ fn adjacent_leaf_reuses_steps_only_while_its_style_key_is_unchanged() { assert_eq!(reused, 0, "a changed style key uses the ordinary path"); assert_eq!(changed, 40.0, "the shown child receives its changed style"); } + +#[derive(Component)] +struct EnablesOnMinimum { + #[common] + common: Common, + seen: Rc>>, +} + +impl Component for EnablesOnMinimum { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: EnablesOnMinimumStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if cx.proposal == Proposal::Min { + self.common = Common::new(); + } + Vec2::new(10.0, 20.0) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + self.seen.set(Some(cx.core.resolved.enabled)); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[derive(Component)] +struct EnabledOwner { + #[common] + common: Common, + seen: Rc>>, +} + +impl Component for EnabledOwner { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: EnabledOwnerStyleKey) -> PlainStyle { + PlainStyle::min(Vec2::new(200.0, 50.0)) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + let child = EnablesOnMinimum { common: Common::new(), seen: self.seen.clone() }.enabled(false); + ui.labelled("child", cx.rect, "Caption".into(), SideLabel::new(), child); + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[trial] +fn labelled_child_enabling_itself_in_minimum_measure_uses_the_current_enabled_state() { + let seen = Rc::new(Cell::new(None)); + let output = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + EnabledOwner { common: Common::new(), seen: output.clone() }.id_salt("owner").show(ui); + }); + fixture.frame(Vec::new()); + assert_eq!(seen.get(), Some(true), "the shown child uses its enabled state after the minimum measure"); + assert_eq!(last_pass_prepared_leaves(fixture.ctx()), 0, "different inherited enabled states use the ordinary path"); +} From 4e0a3d5313c741ca907407c6004483ecbedac6b3 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 04:56:51 +0100 Subject: [PATCH 14/22] Keep memo token comparison within style --- crates/ui-contract/src/primitives/text.rs | 12 ++++++------ crates/ui-contract/src/style/tokens.rs | 5 +++++ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 8e6ebe4b7..55c77b6f7 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -227,11 +227,11 @@ pub(crate) fn line_baseline(ctx: &Context, env: &TextEnv<'_>, role: TypeRole, ce } /// A bounded per-context cache. Equality compares the complete input, rather than trusting a hash collision. -#[derive(Clone, PartialEq)] +#[derive(Clone)] struct LayoutKey { run: TextRun<'static>, tokens: u64, - token_values: Arc, + token_values: UiTokens, direction: Direction, ink: Color32, fonts: StackFacts, @@ -243,7 +243,7 @@ struct LayoutKey { struct LayoutQuery<'a> { run: &'a TextRun<'a>, tokens: u64, - token_values: &'a Arc, + token_values: &'a UiTokens, direction: Direction, ink: Color32, fonts: StackFacts, @@ -298,7 +298,7 @@ impl LayoutQuery<'_> { fn matches(&self, key: &LayoutKey) -> bool { key.run == *self.run && key.tokens == self.tokens - && (Arc::ptr_eq(&key.token_values, self.token_values) || key.token_values.as_ref() == self.token_values.as_ref()) + && key.token_values.same_source_tokens(self.token_values) && key.direction == self.direction && key.ink == self.ink && key.fonts == self.fonts @@ -334,7 +334,7 @@ impl LayoutQuery<'_> { rotation: self.run.rotation, }, tokens: self.tokens, - token_values: Arc::clone(self.token_values), + token_values: self.token_values.clone(), direction: self.direction, ink: self.ink, fonts: self.fonts, @@ -385,7 +385,7 @@ impl TextRun<'_> { LayoutQuery { run: self, tokens: env.tokens.key(), - token_values: env.tokens.tokens(), + token_values: env.tokens, direction: env.direction, ink: env.ink, fonts: env.fonts, diff --git a/crates/ui-contract/src/style/tokens.rs b/crates/ui-contract/src/style/tokens.rs index 504731b04..792ef9dd7 100644 --- a/crates/ui-contract/src/style/tokens.rs +++ b/crates/ui-contract/src/style/tokens.rs @@ -80,6 +80,11 @@ impl UiTokens { &self.tokens } + /// Whether the resolved source tokens used by text layout are equal. + pub(crate) fn same_source_tokens(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.tokens, &other.tokens) || self.tokens == other.tokens + } + /// The theme's token-group values. pub fn groups(&self) -> &GroupValues { &self.groups From f1edd22a0ab299c0e9761b3016be727002b19520 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 14:48:24 +0100 Subject: [PATCH 15/22] Reuse text layouts without a sentinel job --- crates/ui-contract/src/primitives/text.rs | 42 ++++++++++++++++++----- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 55c77b6f7..a3efca4a4 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -7,6 +7,7 @@ pub use crate::style::Span; use crate::style::text_measure::{paragraph_job, span_format}; use crate::style::{StyleColor, TypeRole, UiTokens}; use craft_i18n::Direction; +use egui::epaint::text::FontCacheRevision; use egui::text::{LayoutJob, TextWrapping}; use egui::{Color32, Context, Galley}; use std::borrow::Cow; @@ -262,19 +263,18 @@ struct TextMemo { entries: HashMap>, order: VecDeque, generation: u64, - sentinel: Option>, + font_revision: Option, } fn with_memo(ctx: &Context, f: impl FnOnce(&mut TextMemo) -> R) -> R { - // Egui clears its galley cache whenever the atlas or any layout input owned by fonts changes. - // Keeping this cached empty galley lets us observe that reset, including external providers and rasterizers. - let sentinel = ctx.fonts_mut(|fonts| fonts.layout_job(LayoutJob::default())); + // Mark the viewport as using fonts so same-pass changes wait, just as a fresh layout would. + let font_revision = ctx.fonts_mut(|fonts| fonts.cache_revision_and_mark_used()); memory::with::(ctx, |memo| { - if memo.sentinel.as_ref().is_none_or(|old| !Arc::ptr_eq(old, &sentinel)) { + if memo.font_revision.as_ref() != Some(&font_revision) { memo.entries.clear(); memo.order.clear(); memo.generation = memo.generation.wrapping_add(1); - memo.sentinel = Some(sentinel); + memo.font_revision = Some(font_revision); } f(memo) }) @@ -932,6 +932,31 @@ mod memo_tests { use crate::testing::trial; use craft_theme::{Appearance, Contrast, Mode, Size, TextSize, builtins, resolve}; + #[trial] + fn cached_layout_does_not_call_egui_layout_for_a_sentinel() { + let appearance = + Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::Compact, text_size: TextSize::Small, reduced_motion: false }; + let tokens = UiTokens::new(Arc::new(resolve(&builtins()[0], appearance, None).tokens), Contrast::Standard, Size::Compact); + let ctx = Context::default(); + let env = TextEnv { tokens: &tokens, direction: Direction::Ltr, ink: egui::Color32::WHITE, fonts: StackFacts::default() }; + let run = TextRun::new("cached layout"); + let mut first = None; + let mut output = ctx.run_pass(Default::default(), |ctx| first = Some(run.layout(ctx, &env, 100.0).galley)); + output.textures_delta.clear(); + // Let egui evict its own galleys while our external memo retains the layout. + for _ in 0..2 { + let mut output = ctx.run_pass(Default::default(), |_| {}); + output.textures_delta.clear(); + } + let mut output = ctx.run_pass(Default::default(), |ctx| { + assert_eq!(ctx.fonts(|fonts| fonts.num_galleys_in_cache()), 0); + let cached = run.layout(ctx, &env, 100.0); + assert!(Arc::ptr_eq(first.as_ref().unwrap(), &cached.galley)); + assert_eq!(ctx.fonts(|fonts| fonts.num_galleys_in_cache()), 0, "a memo hit must not call egui layout_job"); + }); + output.textures_delta.clear(); + } + #[trial] fn layouts_reuse_equal_inputs_and_font_updates_invalidate_them() { let appearance = @@ -1061,7 +1086,7 @@ mod memo_tests { assert_eq!(before, 25); }); output.textures_delta.clear(); - // A direct egui font replacement bypasses framework hooks; the sentinel must detect it. + // A direct egui font replacement bypasses framework hooks; the revision must detect it. let mut definitions = ctx.fonts(|fonts| fonts.definitions().clone()); definitions.families.insert(egui::FontFamily::Name("memo trial".into()), Vec::new()); ctx.set_fonts(definitions); @@ -1104,11 +1129,12 @@ mod memo_tests { ctx.set_pixels_per_point(scale); let mut output = ctx.run_pass(Default::default(), |ctx| { assert_eq!(ctx.pixels_per_point(), scale); + let before = with_memo(ctx, |memo| memo.order.len()); let _ = run.layout(ctx, &env, 80.0); let after = with_memo(ctx, |memo| memo.order.len()); let _ = run.layout(ctx, &env, 80.0); assert_eq!(with_memo(ctx, |memo| memo.order.len()), after); - assert_eq!(after, 1); + assert_eq!(after, before + 1, "a new scale has its own cached layout"); }); output.textures_delta.clear(); } From c4c4129493ff5da91633db75e5d07778eef7ddef Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 15:12:29 +0100 Subject: [PATCH 16/22] Expose text memo trials to the registry --- crates/ui-contract/src/primitives/text.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index ec85401fd..9f5aea05b 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -960,7 +960,7 @@ impl ReadingMeasure { } #[cfg(feature = "testing")] -mod memo_tests { +pub(crate) mod memo_tests { use super::{ Arc, Context, Cow, Direction, HAlign, LayoutRun, Span, StackFacts, StyleColor, TextEnv, TextRun, TypeRole, UiTokens, Wrap, with_memo, }; From dda31ff79bb90f20823df163ed3d7ae6f25548d1 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 15:22:14 +0100 Subject: [PATCH 17/22] Preserve button face sizing in paired measurement --- crates/ui-widgets/src/buttons/button.rs | 8 +++++++- crates/ui-widgets/src/buttons/face.rs | 13 +------------ crates/ui-widgets/src/buttons/split_button.rs | 10 +++++++--- 3 files changed, 15 insertions(+), 16 deletions(-) diff --git a/crates/ui-widgets/src/buttons/button.rs b/crates/ui-widgets/src/buttons/button.rs index 0db402260..2e7e47526 100644 --- a/crates/ui-widgets/src/buttons/button.rs +++ b/crates/ui-widgets/src/buttons/button.rs @@ -297,7 +297,13 @@ impl Component for Button<'_> { const PAIRED_MEASURE: bool = true; fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { - Some(face::measure_pair(ideal, least, &self.spec(ideal.resolved.label))) + let (mut whole, mut narrow) = face::measure_pair(ideal, least, &self.spec(ideal.resolved.label, ideal.style)); + if let Some(room) = &self.room_for { + let (room_whole, room_narrow) = face::measure_pair(ideal, least, &self.face_of(room.as_str(), ideal.style)); + whole = whole.max(room_whole); + narrow = narrow.max(room_narrow); + } + Some((whole, narrow)) } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/src/buttons/face.rs b/crates/ui-widgets/src/buttons/face.rs index 2e97575e8..7f7151d2d 100644 --- a/crates/ui-widgets/src/buttons/face.rs +++ b/crates/ui-widgets/src/buttons/face.rs @@ -427,18 +427,7 @@ pub(crate) fn measure(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>) /// The ideal and least face sizes from one paired component measure. pub(crate) fn measure_pair(ideal: &MeasureCx<'_, C>, least: &MeasureCx<'_, C>, spec: &FaceSpec<'_>) -> (Vec2, Vec2) { - let icon = ideal.icon(); - let fixed = icon * spec.icons() as f32 + ideal.gap() * spec.gaps() as f32; - let (whole, narrow) = if spec.label.is_empty() { - (Vec2::ZERO, Vec2::ZERO) - } else { - let run = spec.run(); - let whole = ideal.layout_at(&run, ideal.room.map_or(f32::INFINITY, |room| (room - fixed).max(0.0))).size(); - let width = least.least_width(&run); - let height = least.layout_at(&run, f32::INFINITY).size().y; - (whole, Vec2::new(width, height)) - }; - (Vec2::new(whole.x + fixed, whole.y.max(icon)), Vec2::new(narrow.x + fixed, narrow.y.max(icon))) + (measure(ideal, spec), measure(least, spec)) } /// `icon` in `color`, unless the spec names a colour of its own. diff --git a/crates/ui-widgets/src/buttons/split_button.rs b/crates/ui-widgets/src/buttons/split_button.rs index 0f689283a..0970527b6 100644 --- a/crates/ui-widgets/src/buttons/split_button.rs +++ b/crates/ui-widgets/src/buttons/split_button.rs @@ -200,9 +200,13 @@ impl Component for SplitButton<'_, T> { const PAIRED_MEASURE: bool = true; fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> { - let (mut whole, mut narrow) = face::measure_pair(ideal, least, &self.spec(ideal.resolved.label)); - whole.x += ideal.icon(); - narrow.x += least.icon(); + let arrow = face::arrow_room(ideal.env.get::(), ideal.env.get::()); + let chevron = chevron(&FaceLook { arrow, ..ideal.style.face.clone() }); + let (mut whole, mut narrow) = face::measure_pair(ideal, least, &self.spec(ideal.resolved.label, &chevron)); + if self.arrangement != Arrangement::Stacked { + whole.x += arrow.unwrap_or_else(|| face::measured_icon(ideal)); + narrow.x += arrow.unwrap_or_else(|| face::measured_icon(least)); + } Some((whole, narrow)) } From c16583e194949e561e872e9009b2f65435e2f1a8 Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 15:29:22 +0100 Subject: [PATCH 18/22] Compare paired and separate button sizing --- crates/ui-widgets/tests/it/buttons.rs | 94 ++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 3 deletions(-) diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index e310965ab..10bd3e52b 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -2,21 +2,24 @@ //! group level, under which an inline button drops its label and keeps it as its name and tooltip, the room a button //! keeps for its widest text, and a picture in the leading icon's place. -use craft_behavior::{IconId, PartKey}; +use craft_behavior::{IconId, PartKey, Sense}; use craft_theme::ControlSize; use craft_theme::Variant; use craft_ui::buttons::{Arrangement, Button, ControlPlace, GroupLevel, SplitButton, SplitMenu, ToggleButton}; use craft_ui::contract::tooltip::DELAY; -use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Role, Show as _}; +use craft_ui::contract::{Bind, CommandSet, Common, Component, Cx, Entry, Hover, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::Picture; +use craft_ui::layout::BodyLayout; use craft_ui::list::ThumbAspect; use craft_ui::pickers::ComboBox; use craft_ui::runtime::commands::CommandState; use craft_ui::runtime::env::with_env; +use craft_ui::style::StyleCx; use craft_ui::testing::pictures::sample_picture; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{Fixture, trial}; -use egui::{Event, Id, Pos2, Rect, Response, Ui}; +use craft_ui_test_kit::contract::{Panel, PlainStyle}; +use egui::{Event, Id, Pos2, Rect, Response, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -28,6 +31,91 @@ enum Kind { Split, } +#[derive(Clone, Copy, Debug)] +enum PairedFaceCase { + RoomFor, + Stacked, + Compact, +} + +fn paired_face(case: PairedFaceCase) -> Button<'static> { + let button = Button::new("Save").icon(IconId::new("copy")); + match case { + PairedFaceCase::RoomFor => button.room_for("A much wider button label"), + PairedFaceCase::Stacked => button.arrangement(Arrangement::Stacked), + PairedFaceCase::Compact => button, + } +} + +/// Uses the same real button's separate ideal and least measurements as a comparison leaf. +#[derive(Component)] +struct SeparateFace { + #[common] + common: Common, + case: PairedFaceCase, +} + +impl Component for SeparateFace { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: SeparateFaceStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + paired_face(self.case).measure_in(cx.ui, cx.proposal) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +fn face_in_row(case: PairedFaceCase, paired: bool, width: f32) -> Vec2 { + let seen = Rc::new(Cell::new(Vec2::ZERO)); + let output = seen.clone(); + let mut fixture = Fixture::new(move |ui| { + with_env( + ui, + |overrides| { + if matches!(case, PairedFaceCase::Compact) { + overrides.values.set(GroupLevel::Compact); + } + }, + |ui| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("face-row").show(ui, |ui, _| { + let size = if paired { + paired_face(case).sizing(Sizing::FillWidth).id_salt("face").show(ui).response.rect.size() + } else { + SeparateFace { common: Common::new(), case }.sizing(Sizing::FillWidth).id_salt("face").show(ui).rect.size() + }; + output.set(size); + }); + }, + ); + }); + fixture.room(Vec2::new(width, 160.0)).settle(); + seen.get() +} + +#[trial] +fn paired_button_faces_match_separate_measurements() { + for case in [PairedFaceCase::RoomFor, PairedFaceCase::Stacked, PairedFaceCase::Compact] { + for width in [80.0, 240.0] { + let paired = face_in_row(case, true, width); + let separate = face_in_row(case, false, width); + assert!(paired.x > 0.0 && paired.y > 0.0); + assert!((paired - separate).abs().max_elem() < 0.5, "{case:?} in {width}: paired {paired:?}, separate {separate:?}"); + } + } +} + /// One stacked control of `kind` with `label` at `size`, shown alone: its rect and the rects of the label lines it /// paints, in paint order. fn stacked(kind: Kind, label: &'static str, size: ControlSize) -> (Rect, Vec) { From 038cc09e88f768bc7d59e507a7fb5232f267393c Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 15:33:17 +0100 Subject: [PATCH 19/22] Check warmed paired faces avoid text layouts --- crates/ui-widgets/tests/it/buttons.rs | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index 10bd3e52b..9096237f0 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -17,7 +17,7 @@ use craft_ui::runtime::env::with_env; use craft_ui::style::StyleCx; use craft_ui::testing::pictures::sample_picture; use craft_ui::testing::pointer::{moved, press, release}; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::{Fixture, forget_measurements, last_pass_measure_asks, last_pass_text_layouts, trial}; use craft_ui_test_kit::contract::{Panel, PlainStyle}; use egui::{Event, Id, Pos2, Rect, Response, Ui, Vec2}; use std::cell::{Cell, RefCell}; @@ -101,6 +101,13 @@ fn face_in_row(case: PairedFaceCase, paired: bool, width: f32) -> Vec2 { ); }); fixture.room(Vec2::new(width, 160.0)).settle(); + if paired { + forget_measurements(fixture.ctx()); + fixture.frame(Vec::new()); + let asks = last_pass_measure_asks(fixture.ctx()); + assert!(asks.iter().any(|(name, count)| name.contains("Button") && *count > 0), "the face must be measured again: {asks:?}"); + assert_eq!(last_pass_text_layouts(fixture.ctx()), 0, "a warmed face must reuse its text layouts"); + } seen.get() } From 5b556d052e438df2c1eb489380d7453d15c857ab Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 15:40:51 +0100 Subject: [PATCH 20/22] Avoid unwrap in text cache trial --- crates/ui-contract/src/primitives/text.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 9f5aea05b..d5c5d918a 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -986,7 +986,7 @@ pub(crate) mod memo_tests { let mut output = ctx.run_pass(Default::default(), |ctx| { assert_eq!(ctx.fonts(|fonts| fonts.num_galleys_in_cache()), 0); let cached = run.layout(ctx, &env, 100.0); - assert!(Arc::ptr_eq(first.as_ref().unwrap(), &cached.galley)); + assert!(first.as_ref().is_some_and(|first| Arc::ptr_eq(first, &cached.galley))); assert_eq!(ctx.fonts(|fonts| fonts.num_galleys_in_cache()), 0, "a memo hit must not call egui layout_job"); }); output.textures_delta.clear(); From 1ed5bd9f111fa0a1c19b5111a24422a346fb6fbd Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 16:36:20 +0100 Subject: [PATCH 21/22] Use the theme ink in the text cache trial --- crates/ui-contract/src/primitives/text.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index d5c5d918a..14d22a389 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -973,7 +973,12 @@ pub(crate) mod memo_tests { Appearance { mode: Mode::Dark, contrast: Contrast::Standard, size: Size::Compact, text_size: TextSize::Small, reduced_motion: false }; let tokens = UiTokens::new(Arc::new(resolve(&builtins()[0], appearance, None).tokens), Contrast::Standard, Size::Compact); let ctx = Context::default(); - let env = TextEnv { tokens: &tokens, direction: Direction::Ltr, ink: egui::Color32::WHITE, fonts: StackFacts::default() }; + let env = TextEnv { + tokens: &tokens, + direction: Direction::Ltr, + ink: crate::style::rgba_color(tokens.tokens().color.text.normal), + fonts: StackFacts::default(), + }; let run = TextRun::new("cached layout"); let mut first = None; let mut output = ctx.run_pass(Default::default(), |ctx| first = Some(run.layout(ctx, &env, 100.0).galley)); From d292c8a7426035008c78d0be05b5694c6758806f Mon Sep 17 00:00:00 2001 From: FredApps Date: Fri, 20 Nov 2026 19:56:31 +0100 Subject: [PATCH 22/22] Format combined measurement exports --- crates/ui-contract/src/testing/mod.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index 69d9665d7..195516379 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -55,8 +55,9 @@ pub use crate::runtime::layout_memory::forget_kept as forget_measurements; pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; 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_prepared_leaves, - last_pass_runs, last_pass_text_layouts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_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_prepared_leaves, last_pass_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};