Merge pull request #2361 from storytold/perf/2333-text-layout

Reuse text layouts and measure supported leaves once per sweep
This commit is contained in:
FredApps
2026-11-21 03:16:33 +07:00
committed by GitHub
27 changed files with 1568 additions and 85 deletions
@@ -118,6 +118,11 @@ impl<C: Component> MeasureCx<'_, C> {
run.least(self.ui.ctx(), &self.text_env())
}
/// The readable least width of `run`.
pub fn least_width(&self, run: &TextRun<'_>) -> f32 {
run.least_width(self.ui.ctx(), &self.text_env())
}
fn text_env(&self) -> TextEnv<'_> {
TextEnv {
tokens: self.tokens,
+13
View File
@@ -418,6 +418,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
+31 -4
View File
@@ -166,11 +166,20 @@ 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));
// 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
} 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 +188,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<C: Show>(&mut self, id: Id, rect: Rect, child: C, tip: Option<TipFn<'_>>, inside: Option<Arc<InsideLabel>>) -> C::Output {
self.child_with_prepared(id, rect, child, tip, inside, None)
}
fn child_with_prepared<C: Show>(
&mut self,
id: Id,
rect: Rect,
child: C,
tip: Option<TipFn<'_>>,
inside: Option<Arc<InsideLabel>>,
prepared: Option<run::PreparedLeaf<C>>,
) -> C::Output {
let scope = sub(self.id, "children");
let parent = &mut *self.ui;
let kids = self.kids.get_or_insert_with(|| {
@@ -186,7 +207,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 +224,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
}
+83 -26
View File
@@ -29,8 +29,8 @@ use std::sync::Arc;
mod typed;
pub(crate) use typed::{
MemberNode, MemberPrep, MemberShown, measure_container, measure_face, 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_face, 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.
@@ -439,6 +439,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`.
@@ -460,6 +461,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::<C::StyleKey>(),
@@ -498,6 +500,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`.
@@ -1407,30 +1410,39 @@ 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) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>) {
if crate::runtime::pass_state::in_component_tree() {
return run_in_context(t, ui, at, tip);
}
let ctx = ui.ctx().clone();
crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip));
pub(super) struct PreparedStep {
step1: steps::EnvStep,
style: Arc<dyn StyleView>,
}
fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>) {
pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>) {
run_with(t, ui, at, tip, None);
}
fn run_with(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>, prepared: Option<PreparedStep>) {
if crate::runtime::pass_state::in_component_tree() {
return run_in_context(t, ui, at, tip, prepared);
}
let ctx = ui.ctx().clone();
crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip, prepared));
}
fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>, prepared: Option<PreparedStep>) {
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<TipFn<'_>>) {
let begun = begin(t, ui);
fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option<TipFn<'_>>, prepared: Option<PreparedStep>) {
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);
@@ -1495,7 +1507,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<PreparedStep>) -> Begun {
let ctx = ui.ctx().clone();
let facts = t.facts();
crate::runtime::measure::count_run(&ctx, facts.name);
@@ -1512,9 +1524,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 {
@@ -1640,8 +1657,8 @@ fn measure_step(
let ask = |t: &mut dyn Erased, proposal: Proposal, room: Option<f32>, 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);
@@ -1652,10 +1669,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
@@ -1715,10 +1758,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),
@@ -1860,6 +1906,17 @@ pub(super) fn measure_shape(
under: Option<&super::cx::Under>,
purpose: MeasureFor,
) -> Vec2 {
measure_shape_with(t, ui, id, proposal, under, purpose).0
}
fn measure_shape_with(
t: &mut dyn Erased,
ui: &Ui,
id: Option<Id>,
proposal: Proposal,
under: Option<&super::cx::Under>,
purpose: MeasureFor,
) -> (Vec2, steps::EnvStep) {
let facts = t.facts();
let env = match under {
Some(under) => super::cx::child_env(&Env::of(ui), under),
@@ -1896,7 +1953,7 @@ pub(super) fn measure_shape(
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
+100 -1
View File
@@ -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};
@@ -176,6 +176,11 @@ impl<C: Component> 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());
@@ -525,6 +530,100 @@ fn measure_shape<C: Component>(
super::measure_shape(&mut Typed::new(Held::Lent(comp), hooks), ui, id, proposal, under, purpose)
}
/// Step 1 and style from a measure immediately followed by a show of the same leaf.
pub(crate) struct PreparedLeaf<C: Component> {
source: Env,
inputs: StepInputs,
style_key: C::StyleKey,
step1: steps::EnvStep,
style: Arc<C::Style>,
}
#[derive(PartialEq)]
struct StepInputs {
label: Label,
enabled: Option<bool>,
read_only: Option<bool>,
size: Option<craft_theme::ControlSize>,
glyphs: Option<crate::style::GlyphRole>,
variant: Option<Variant>,
}
impl StepInputs {
fn of(common: &Common) -> Option<Self> {
// 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<C: Component> PreparedLeaf<C> {
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<C: Show>(
comp: &mut C,
ui: &Ui,
id: Id,
proposal: Proposal,
under: &crate::contract::cx::Under,
) -> (Vec2, Option<PreparedLeaf<C>>) {
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), super::MeasureFor::Component);
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<C: Show>(
slot: &mut Option<C>,
ui: &mut Ui,
at: ShowAt,
tip: Option<TipFn<'_>>,
prepared: PreparedLeaf<C>,
) -> 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::<C>(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<dyn StyleView> = style;
super::run_with(&mut typed, ui, at, tip, Some(super::PreparedStep { step1, style }));
typed.output()
}
pub(crate) fn show_leaf<C: Component + Meta<Shape = crate::contract::shape::Leaf>>(
slot: &mut Option<C>,
ui: &mut Ui,
+1 -1
View File
@@ -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};
#[cfg(feature = "testing")]
pub(crate) use parts::declares_none;
@@ -32,6 +32,26 @@ pub(crate) fn measure_content<C: Component>(
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<C: Component>(
comp: &mut C,
ideal: &MeasureIn<'_>,
least: &MeasureIn<'_>,
style: &C::Style,
resolved: &Resolved<'_>,
value: Option<&ValueOf<C>>,
) -> Option<((Vec2, Vec2), Inputs)> {
let ideal_cx = measure_cx::<C>(ideal, style, resolved, value);
let least_cx = measure_cx::<C>(least, style, resolved, value);
let (pair, inputs) = layout_memory::measure_call(ideal.ui.ctx(), || comp.measure_pair(&ideal_cx, &least_cx));
#[cfg(feature = "testing")]
if pair.is_some() {
crate::runtime::measure::count_measure_ask(ideal.ui.ctx(), std::any::type_name::<C>());
}
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
+1 -1
View File
@@ -181,7 +181,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)
}
}
+1 -1
View File
@@ -57,7 +57,7 @@ pub use surround::paint_surround;
#[cfg(feature = "testing")]
pub(crate) use svg_set::Layer;
pub use svg_set::{AppIcons, register_app_icons};
pub use text::{ChordText, HAlign, LayoutRun, LeastLayout, ReadingMeasure, Span, TextLayout, TextRun, Wrap};
pub use text::{ChordText, HAlign, LayoutRun, LayoutRuns, LayoutText, LeastLayout, ReadingMeasure, Span, TextLayout, TextRun, Wrap};
pub use text_input::{
Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp, TabKey, TextKey, TextOptions,
};
+611 -22
View File
@@ -1,16 +1,20 @@
//! `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};
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;
use std::ops::Range;
use std::sync::Arc;
use std::collections::{HashMap, VecDeque};
use std::hash::{Hash, Hasher};
use std::ops::{Deref, DerefMut, Range};
use std::sync::{Arc, OnceLock};
/// How a run fits its room.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
@@ -150,6 +154,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,34 +227,235 @@ 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)]
struct LayoutKey {
run: TextRun<'static>,
tokens: u64,
token_values: UiTokens,
direction: Direction,
ink: Color32,
fonts: StackFacts,
width: u32,
scale: u32,
}
/// A lookup borrows the spans; only a new cache entry copies their text.
struct LayoutQuery<'a> {
run: &'a TextRun<'a>,
tokens: u64,
token_values: &'a UiTokens,
direction: Direction,
ink: Color32,
fonts: StackFacts,
width: u32,
scale: u32,
}
struct CachedText {
key: LayoutKey,
layout: Option<Arc<TextLayout>>,
least: Option<f32>,
}
#[derive(Default)]
struct TextMemo {
entries: HashMap<u64, Vec<CachedText>>,
order: VecDeque<u64>,
generation: u64,
font_revision: Option<FontCacheRevision>,
}
fn with_memo<R>(ctx: &Context, f: impl FnOnce(&mut TextMemo) -> R) -> R {
// 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::<TextMemo, _>(ctx, |memo| {
if memo.font_revision.as_ref() != Some(&font_revision) {
memo.entries.clear();
memo.order.clear();
memo.generation = memo.generation.wrapping_add(1);
memo.font_revision = Some(font_revision);
}
f(memo)
})
}
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();
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()
}
fn matches(&self, key: &LayoutKey) -> bool {
key.run == *self.run
&& key.tokens == self.tokens
&& key.token_values.same_source_tokens(self.token_values)
&& 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,
flag: span.flag,
})
.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,
token_values: self.token_values.clone(),
direction: self.direction,
ink: self.ink,
fonts: self.fonts,
width: self.width,
scale: self.scale,
}
}
}
impl TextMemo {
fn get(&self, key: &LayoutQuery<'_>) -> Option<&CachedText> {
self.entries.get(&key.hash())?.iter().find(|entry| key.matches(&entry.key))
}
fn put(&mut self, key: &LayoutQuery<'_>, layout: Option<Arc<TextLayout>>, least: Option<f32>) {
// Large document text should not pin galleys in a UI-label cache.
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| key.matches(&entry.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()
&& 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: 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<'a>(&'a self, ctx: &Context, env: &'a TextEnv<'_>, max_width: f32) -> LayoutQuery<'a> {
LayoutQuery {
run: self,
tokens: env.tokens.key(),
token_values: env.tokens,
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();
}
// 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` 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);
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::<str>::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);
}
});
layout
}
/// The run laid out whole in unbounded room, and its width at its readable least: cut where its wrap says,
/// keeping [`READABLE_CHARACTERS`](Self::READABLE_CHARACTERS) and the ellipsis, or whole when it has no more than
/// one character beyond them.
/// The whole layout and the width at its readable least, sharing the cached unbounded layout.
pub(crate) fn least(&self, ctx: &Context, env: &TextEnv<'_>) -> LeastLayout {
let full = self.full_text();
let laid = self.layout(ctx, env, f32::INFINITY);
let whole = laid.size().x;
let whole = self.layout(ctx, env, f32::INFINITY);
let width = self.least_width(ctx, env);
LeastLayout { width, whole }
}
/// The width of the run at its readable least: cut where its wrap says, keeping
/// [`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 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 = self.layout(ctx, env, f32::INFINITY).size().x;
let ends: Vec<usize> = full.char_indices().map(|(at, _)| at).chain([full.len()]).collect();
if ends.len() - 1 <= Self::READABLE_CHARACTERS + 1 {
return LeastLayout { width: whole, whole: laid };
return whole;
}
let rtl_text = !self.is_rtl(env) && craft_i18n::base_direction(&full) == Some(Direction::Rtl);
let width = |pieces: &[Piece]| text_layout::layout(ctx, self.job_cut(env, &full, pieces, rtl_text)).size().x;
@@ -261,7 +474,7 @@ impl TextRun<'_> {
} else {
width(&cut_pieces(&full, &ends, 0..full.len(), self.wrap, Self::READABLE_CHARACTERS))
};
LeastLayout { width: least.min(whole), whole: laid }
least.min(whole)
}
/// Whether the paragraph runs right to left: the env's direction, unless the run is fixed left to right.
@@ -434,7 +647,126 @@ 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<Galley>,
original: Option<Arc<str>>,
value: Arc<OnceLock<String>>,
changed: Option<String>,
}
impl LayoutText {
fn shared(&self) -> Self {
Self { galley: self.galley.clone(), original: self.original.clone(), value: self.value.clone(), changed: self.changed.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<str> 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<String> for LayoutText {
fn eq(&self, other: &String) -> bool {
self.deref() == other
}
}
impl Deref for LayoutText {
type Target = String;
fn deref(&self) -> &String {
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())
}
}
/// A layout's single-row direction runs, built only when read.
///
/// Dereferences to `Vec<LayoutRun>` so existing field reads continue to work.
pub struct LayoutRuns {
galley: Arc<Galley>,
value: Arc<OnceLock<Vec<LayoutRun>>>,
changed: Option<Vec<LayoutRun>>,
}
impl LayoutRuns {
fn shared(&self) -> Self {
Self { galley: self.galley.clone(), value: self.value.clone(), changed: self.changed.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<Vec<LayoutRun>> for LayoutRuns {
fn eq(&self, other: &Vec<LayoutRun>) -> bool {
self.deref() == other
}
}
impl Deref for LayoutRuns {
type Target = Vec<LayoutRun>;
fn deref(&self) -> &Vec<LayoutRun> {
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<LayoutRun> {
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()
})
}
}
@@ -457,7 +789,6 @@ impl LeastLayout {
}
/// A laid-out run.
#[derive(Clone)]
#[non_exhaustive]
pub struct TextLayout {
/// The galley.
@@ -465,25 +796,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<LayoutRun>,
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<Galley>, elided: bool, full: String) -> TextLayout {
let original = (galley.job.text != full).then(|| Arc::<str>::from(full));
Self::from_job(galley, elided, original)
}
pub(super) fn from_job(galley: Arc<Galley>, elided: bool, full: Option<Arc<str>>) -> 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()), 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 }
}
/// 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<LayoutRun> {
let glyphs = galley.rows.get(row).map_or(&[][..], |placed| &placed.row.glyphs[..]);
@@ -515,7 +875,12 @@ 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.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()
}
@@ -593,3 +958,227 @@ impl ReadingMeasure {
ReadingMeasure { target: average * Self::TARGET_CHARACTERS, least: average * Self::LEAST_CHARACTERS }
}
}
#[cfg(all(feature = "testing", any(test, feature = "suite")))]
pub(crate) mod memo_tests {
use super::{
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};
#[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: 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));
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!(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();
}
#[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: 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);
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());
let _: String = first.full.clone();
let _: Vec<LayoutRun> = 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);
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 = 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();
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.spans[0].flag = Some(craft_theme::variant::Tone::Bad);
variants.push(changed);
let mut changed = run.clone();
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;
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: 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);
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();
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, 26);
});
output.textures_delta.clear();
// 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);
let mut output = ctx.run_pass(Default::default(), |ctx| {
with_memo(ctx, |memo| assert!(memo.order.is_empty()));
});
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: 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);
});
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();
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(), 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, before + 1, "a new scale has its own cached layout");
});
output.textures_delta.clear();
}
}
+5
View File
@@ -458,6 +458,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<L: WordSet + Send + Sync + 'static>(&self) -> Arc<L> {
self.words.set::<L>()
@@ -1294,6 +1294,7 @@ pub(crate) mod guard {
("runtime::egui::painted::Elisions", "elisions: written where text paints, which a measuring run does not"),
("Stamped<std::collections::hash::set::HashSet<egui::id::Id>>", "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"),
+29
View File
@@ -235,6 +235,35 @@ pub fn body_runs(ctx: &Context) -> Vec<(Id, u32)> {
store::with::<BodyRuns, _>(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) || uncounted(ctx) {
return;
}
let pass = ctx.cumulative_pass_nr();
store::with::<PreparedLeafCounts, _>(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::<PreparedLeafCounts, _>(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")]
+5
View File
@@ -90,6 +90,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
+3 -2
View File
@@ -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_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};
@@ -7,6 +7,7 @@ pub(crate) mod level;
pub(crate) mod memo_key;
pub(crate) mod pages;
pub(crate) mod pointer;
pub(crate) mod prepared;
pub(crate) mod style;
pub(crate) mod tracked_bind;
pub(crate) mod visited_type;
@@ -0,0 +1,230 @@
//! 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::primitives::TextRun;
use craft_ui::style::{ComponentStyle as _, StyleCx};
use craft_ui::testing::{Fixture, last_pass_prepared_leaves, last_pass_text_layouts, 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<Cell<f32>>,
}
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<Cell<f32>>,
}
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");
}
#[derive(Component)]
struct EnablesOnMinimum {
#[common]
common: Common,
seen: Rc<Cell<Option<bool>>>,
}
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<Cell<Option<bool>>>,
}
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");
}
#[derive(Component)]
struct LeastTwice {
#[common]
common: Common,
measured: Rc<Cell<u32>>,
}
impl Component for LeastTwice {
const ROLE: Role = Role::GROUP;
type Style = PlainStyle;
type Output = Response;
fn style(_: &StyleCx<'_>, _: LeastTwiceStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let run = TextRun::new("the complete least layout is retained").elide();
let first = cx.least(&run);
let count = cx.ui.ctx().fonts(|fonts| fonts.num_galleys_in_cache());
let second = cx.least(&run);
assert_eq!(first.width, second.width);
assert!(std::sync::Arc::ptr_eq(&first.whole.galley, &second.whole.galley));
assert_eq!(cx.ui.ctx().fonts(|fonts| fonts.num_galleys_in_cache()), count, "a repeated least request performs no new layouts");
self.measured.set(self.measured.get() + 1);
second.size()
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn finish(self, cx: Cx<'_, Self>) -> Response {
cx.response.clone()
}
}
#[trial]
fn repeated_measure_least_reuses_both_results() {
let measured = Rc::new(Cell::new(0));
let output = measured.clone();
let mut fixture = Fixture::new(move |ui| {
LeastTwice { common: Common::new(), measured: output.clone() }.id_salt("least-twice").show(ui);
});
fixture.frame(Vec::new());
let first_count = measured.get();
assert!(first_count > 0);
fixture.frame(Vec::new());
assert!(measured.get() > first_count, "the second pass must actually request the least layout");
assert_eq!(last_pass_text_layouts(fixture.ctx()), 0, "repeated least requests reuse the whole layout and least width");
}
@@ -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 {
+132 -1
View File
@@ -127,6 +127,17 @@ const LINE: f32 = 20.0;
struct Asked {
ideal: Cell<usize>,
min: Cell<usize>,
pair: Cell<usize>,
observed: Cell<(u64, u32, u32)>,
}
impl Asked {
fn note(&self, ctx: &egui::Context, pair: bool) {
let pass = ctx.cumulative_pass_nr();
let (old, count, pairs) = self.observed.get();
let (count, pairs) = if old == pass { (count, pairs) } else { (0, 0) };
self.observed.set((pass, count + 1, pairs + u32::from(pair)));
}
}
/// A leaf `IDEAL` wide that narrows to `LEAST`, whatever its room; it counts the measures it answers in measuring runs.
@@ -136,11 +147,13 @@ struct Stretch<'a> {
common: Common,
seen: &'a RefCell<Seen>,
asked: &'a Asked,
paired: bool,
track_input: bool,
}
impl<'a> Stretch<'a> {
fn new(seen: &'a RefCell<Seen>, asked: &'a Asked) -> Self {
Stretch { common: Common::new(), seen, asked }
Stretch { common: Common::new(), seen, asked, paired: false, track_input: false }
}
}
@@ -154,6 +167,10 @@ impl Component for Stretch<'_> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
self.asked.note(cx.ui.ctx(), false);
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 +178,25 @@ 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;
}
self.asked.note(ideal.ui.ctx(), true);
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 +210,101 @@ impl Component for Stretch<'_> {
}
}
#[trial]
fn paired_measure_is_counted_once_as_a_measure_ask() {
let asked = Rc::new(Asked::default());
let shown = Rc::clone(&asked);
let mut fixture = Fixture::new(move |ui| {
let seen = RefCell::new(Seen::default());
Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("row").show(ui, |ui, _| {
let mut child = Stretch::new(&seen, &shown);
child.paired = true;
child.sizing(Sizing::FillWidth).id_salt("child").show(ui);
});
});
fixture.room(Vec2::new(240.0, 100.0)).frame(Vec::new());
let (pass, actual, pairs) = asked.observed.get();
assert_eq!(pass, fixture.ctx().cumulative_pass_nr().saturating_sub(1));
assert!(pairs > 0, "the final pass used the paired hook");
let counted = craft_ui::testing::last_pass_measure_asks(fixture.ctx())
.into_iter()
.find_map(|(name, count)| name.contains("Stretch").then_some(count))
.unwrap_or(0);
assert_eq!(counted, actual, "paired and separate calls are each counted once");
}
/// 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");
}
#[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) {
+12
View File
@@ -294,6 +294,18 @@ impl Component for Button<'_> {
}
}
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, 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 {
if self.loading { Sense::FOCUS } else { Sense::CLICK | Sense::FOCUS }
}
+5
View File
@@ -425,6 +425,11 @@ pub(crate) fn measure<C: Component>(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<C: Component>(ideal: &MeasureCx<'_, C>, least: &MeasureCx<'_, C>, spec: &FaceSpec<'_>) -> (Vec2, Vec2) {
(measure(ideal, spec), measure(least, spec))
}
/// `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();
+14
View File
@@ -95,6 +95,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,
@@ -197,6 +197,19 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
}
}
const PAIRED_MEASURE: bool = true;
fn measure_pair(&mut self, ideal: &MeasureCx<'_, Self>, least: &MeasureCx<'_, Self>) -> Option<(Vec2, Vec2)> {
let arrow = face::arrow_room(ideal.env.get::<super::ControlPlace>(), ideal.env.get::<super::RibbonLook>());
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))
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS
}
@@ -164,6 +164,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
}
+42 -22
View File
@@ -126,6 +126,26 @@ impl Text {
self
}
fn widest_word(&self, cx: &MeasureCx<'_, Self>) -> f32 {
let role = cx.style.text.role;
self.word_runs(role, cx.resolved.label).iter().map(|word| cx.layout_at(word, f32::INFINITY).size().x).fold(0.0, f32::max)
}
fn ideal_plain(&self, cx: &MeasureCx<'_, Self>, run: &TextRun<'_>, band: f32, widest: Option<f32>) -> 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() }
@@ -203,33 +223,33 @@ 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 = || self.word_runs(role, cx.resolved.label).iter().map(|word| cx.layout_at(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 cx.least(&run).size();
}
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);
}
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)> {
if !self.spans.is_empty() {
return None;
}
// 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(),
let band = ideal.column_room().unwrap_or(f32::INFINITY);
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);
Some((ideal_size, least.least(&run).size()))
}
fn cut_first(&self) -> bool {
+27
View File
@@ -216,6 +216,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();
+99 -4
View File
@@ -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::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};
use std::rc::Rc;
@@ -28,6 +31,98 @@ 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();
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()
}
#[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<Rect>) {