diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index cf914b824..de1112200 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -118,11 +118,6 @@ impl 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, diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 44dee4d71..14ea466f7 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -419,19 +419,6 @@ 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/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index b49f97831..498f64829 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -166,20 +166,11 @@ 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) { - // 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)) - }; + let ideal = 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_prepared(id, control, child, None, under.inside.clone(), prepared); + let output = self.child_with(id, control, child, None, under.inside.clone()); placed.finish(&ctx); output }) @@ -188,18 +179,6 @@ 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(|| { @@ -207,10 +186,7 @@ impl PaintUi<'_> { alloc::child(parent, access::with_parent(builder, self.id)) }); let ctx = kids.ctx().clone(); - 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 }); + let env = super::cx::child_env(&Env::of(kids), &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(_) => { @@ -224,10 +200,7 @@ 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, || 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), - }); + let output = layout_memory::boundary(&ctx, true, || run::show_leaf(&mut Some(super::Props::id(child, id)), 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 338c3d35b..f7e3aab2d 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, 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, + 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, }; /// Where a component is placed. @@ -439,7 +439,6 @@ 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`. @@ -461,7 +460,6 @@ 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::(), @@ -500,7 +498,6 @@ 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`. @@ -1410,39 +1407,30 @@ 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) { if crate::runtime::pass_state::in_component_tree() { - return run_in_context(t, ui, at, tip, prepared); + 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, prepared)); + crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip)); } -fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, prepared: Option) { +fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { let cell = (matches!(at, ShowAt::Flow) && t.in_flow()).then(|| crate::layout::grid_cell(ui)).flatten(); match cell { Some((grid, column, sized)) => { let ctx = ui.ctx().clone(); - crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || run_steps(t, ui, at, tip, prepared)); + crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || run_steps(t, ui, at, tip)); } - None => run_steps(t, ui, at, tip, prepared), + None => run_steps(t, ui, at, tip), } } /// 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>, prepared: Option) { - let begun = begin(t, ui, prepared); +fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { + let begun = begin(t, ui); let mut stage = begun.open_stage(t); let mixed = value_step(t, &begun, &mut stage); let resolved = begun.resolved(t); @@ -1507,7 +1495,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, prepared: Option) -> Begun { +fn begin(t: &mut dyn Erased, ui: &Ui) -> Begun { let ctx = ui.ctx().clone(); let facts = t.facts(); crate::runtime::measure::count_run(&ctx, facts.name); @@ -1524,14 +1512,9 @@ fn begin(t: &mut dyn Erased, ui: &Ui, prepared: Option) -> 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, 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) - } - }; + let step1 = steps::env(&ctx, &env, &common, t.variants(common.variant)); + // 2 style + let style = t.style(&ctx, &steps::style_cx(&ctx, &env, &step1)); // 3 id let id = steps::id(ui, &common.id, !sizing, true, facts.style_key, facts.name); if recording { @@ -1657,8 +1640,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) }; - // 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)); + let (size, inputs) = ask(&mut *t, Proposal::Ideal, room, extent); + let ideal = Call { proposal: Proposal::Ideal, room, inputs, took: size }; // 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); @@ -1669,36 +1652,10 @@ 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 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 = (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 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 @@ -1758,13 +1715,10 @@ 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 = match paired.filter(|_| room.is_none()) { - Some((_, content)) => content, - None => t.measure_content(&input, resolved).0, - }; + let (content, _) = t.measure_content(&input, resolved); let ideal = steps::measure(style, &input, content, Vec2::ZERO, resolved).x; let whole = steps::whole(style, content, Vec2::ZERO, resolved); - let least = paired.map_or_else(|| ask(&mut *t, Proposal::Min, None, Vec2::ZERO).0.x, |(least, _)| least.x); + let least = ask(&mut *t, Proposal::Min, None, Vec2::ZERO).0.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), @@ -1906,17 +1860,6 @@ 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, - 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), @@ -1953,7 +1896,7 @@ fn measure_shape_with( if let Some(key) = t.bind_key(id) { reads::note(ui.ctx(), key, id, true, &[Sample { proposal, room: None, took }]); } - (took, step1) + took } /// 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 7ed30f285..0be4e115f 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, Label, Message, ThemeScope}; +use crate::runtime::env::{AppValues, Env, Message, ThemeScope}; use crate::runtime::focus; use crate::runtime::layout_memory::Inputs; use crate::runtime::memory::{MemoryStage, sub}; @@ -176,11 +176,6 @@ 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()); @@ -530,100 +525,6 @@ fn measure_shape( 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 { - 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), 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( - 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/contract/steps.rs b/crates/ui-contract/src/contract/steps.rs index 3ee404f29..b424f2a7d 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_content_pair, measure_cx, padding, whole}; +pub(crate) use measure::{MeasureIn, guard, measure, measure_content, 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; diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index b55eb0ab8..6ccec0dbf 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -32,26 +32,6 @@ 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)); - #[cfg(feature = "testing")] - if pair.is_some() { - crate::runtime::measure::count_measure_ask(ideal.ui.ctx(), std::any::type_name::()); - } - 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/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 4bc7910c0..e76026fef 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -327,8 +327,8 @@ fn facts(core: &CxCore<'_>, state: &mut TextState, widget: egui::Id, out: &adapt state.rows = None; return; } - let rows = adapter::Rows::of(&out.layout, &out.layout.full, rect.min); - let text = out.layout.full.clone(); + let rows = adapter::Rows::of(&out.layout, out.layout.full(), rect.min); + let text = out.layout.full().to_owned(); let selection = adapter::selection(&core.ctx, widget).map(|(caret, anchor)| (rows.pos(&text, anchor), rows.pos(&text, caret))); *core.text_access.borrow_mut() = Some(text_access::TextFacts { widget, text, masked, editable: !read_only, disabled: !enabled, lines: rows.lines.clone(), selection }); @@ -551,12 +551,12 @@ pub(crate) fn run( cx.core.text_invalid = state.invalid; cx.core.text_unparsed = part.options.unparsed.clone().filter(|_| state.invalid); cx.core.escape_to_list = state.completions.open || list_open; - if state.draft.is_some() || (part.options.clear_on_escape && !out.layout.full.is_empty()) { + if state.draft.is_some() || (part.options.clear_on_escape && !out.layout.full().is_empty()) { keys::hold_escape(&ctx, id); } let completions = state.completions.items.clone(); // The caret after every move of this pass, which a bound caret is written back from. - let caret = adapter::caret_byte(&ctx, widget, state.draft.as_deref().unwrap_or(&out.layout.full)); + let caret = adapter::caret_byte(&ctx, widget, state.draft.as_deref().unwrap_or(out.layout.full())); *cx.core.memory.shown::(state_id) = state; let mut outcome = resolved.outcome; outcome.layout = Some(out.layout); diff --git a/crates/ui-contract/src/primitives/draw.rs b/crates/ui-contract/src/primitives/draw.rs index af372d7ba..b9645b533 100644 --- a/crates/ui-contract/src/primitives/draw.rs +++ b/crates/ui-contract/src/primitives/draw.rs @@ -315,7 +315,8 @@ impl<'a> Draw<'a> { pub fn doc(&self, rect: Rect, text: &DocText<'_>) -> TextLayout { let text = DocText { wrap: Some(rect.width()), ..*text }; let layout = text.layout(self.painter.ctx(), self.env.tokens, self.text_direction); - let layout = TextLayout { galley: super::text::anchored_at_start(layout.galley.clone()), ..layout }; + let anchored = super::text::anchored_at_start(layout.galley.clone()); + let layout = layout.with_galley(anchored); let share = super::text::free_room_before(text.align, self.text_direction == Direction::Rtl); let x = rect.left() + (rect.width() - layout.size().x).max(0.0) * share; // The runs' colours are data. @@ -366,7 +367,7 @@ impl<'a> Draw<'a> { let mut record = self.record.borrow_mut(); record.baseline.get_or_insert(pos.y + layout.first_baseline); if layout.elided && record.elided.is_none() { - record.elided = Some(layout.full.clone()); + record.elided = Some(layout.full().to_owned()); } drop(record); super::text::note_painted(self.painter.ctx(), layout); diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index 6a47d5c02..3d75e3d4e 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -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, LayoutRuns, LayoutText, LeastLayout, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; +pub use text::{ChordText, HAlign, LayoutRun, LeastLayout, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; pub use text_input::{ Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp, TabKey, TextKey, TextOptions, }; diff --git a/crates/ui-contract/src/primitives/text.rs b/crates/ui-contract/src/primitives/text.rs index 94bf0405e..9b36826d8 100644 --- a/crates/ui-contract/src/primitives/text.rs +++ b/crates/ui-contract/src/primitives/text.rs @@ -11,9 +11,9 @@ use egui::epaint::text::FontCacheRevision; use egui::text::{LayoutJob, TextWrapping}; use egui::{Color32, Context, Galley}; use std::borrow::Cow; -use std::collections::{HashMap, VecDeque}; +use std::collections::HashMap; use std::hash::{Hash, Hasher}; -use std::ops::{Deref, DerefMut, Range}; +use std::ops::Range; use std::sync::{Arc, OnceLock}; /// How a run fits its room. @@ -256,12 +256,29 @@ struct CachedText { key: LayoutKey, layout: Option>, least: Option, + /// The pass that last read or wrote the entry. + used: u64, + /// What the entry retains, as [`retained_bytes`] estimates it. + bytes: usize, } +/// Passes an entry stays without being read: egui's galley cache drops a galley unused for one pass; the memo keeps +/// an entry longer, so text whose body replays its kept measurement for a few passes still finds its layout when the +/// body runs again. +const UNUSED_PASSES: u64 = 60; +/// The most the memo retains in all, as [`retained_bytes`] estimates it: the per-entry caps in `put` bound one +/// entry, this bounds many wide paragraphs at many widths. +const BUDGET_BYTES: usize = 32 * 1024 * 1024; +/// Where an eviction over the budget stops, below the budget so that one eviction covers many new entries. +const EVICT_TO_BYTES: usize = BUDGET_BYTES / 4 * 3; + #[derive(Default)] struct TextMemo { entries: HashMap>, - order: VecDeque, + /// The sum of the entries' `bytes`. + bytes: usize, + /// The current pass, as of the last access. + pass: u64, generation: u64, font_revision: Option, } @@ -269,17 +286,41 @@ struct TextMemo { fn with_memo(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()); + let pass = ctx.cumulative_pass_nr(); memory::with::(ctx, |memo| { if memo.font_revision.as_ref() != Some(&font_revision) { memo.entries.clear(); - memo.order.clear(); + memo.bytes = 0; memo.generation = memo.generation.wrapping_add(1); memo.font_revision = Some(font_revision); } + if memo.pass != pass { + memo.pass = pass; + memo.retain(|entry| pass.saturating_sub(entry.used) < UNUSED_PASSES); + } f(memo) }) } +/// What a memo entry keeps alive: its key's text, and its galley's text, glyphs and mesh. +fn retained_bytes(key: &LayoutKey, layout: Option<&TextLayout>) -> usize { + use egui::epaint::Vertex; + use egui::epaint::text::{Glyph, LayoutSection}; + use std::mem::size_of; + let text: usize = key.run.spans.iter().map(|span| size_of::>() + span.text.len()).sum(); + let galley = layout.map_or(0, |layout| { + let galley = &layout.galley; + let glyphs: usize = galley.rows.iter().map(|placed| placed.row.glyphs.len()).sum(); + galley.job.text.len() + + galley.job.sections.len() * size_of::() + + glyphs * size_of::() + + galley.num_vertices * size_of::() + + galley.num_indices * size_of::() + + layout.full.as_ref().map_or(0, |full| full.len()) + }); + size_of::() + text + galley +} + impl LayoutQuery<'_> { // Hash the text and the common discriminators. Equality checks the remaining fields and resolves collisions. fn hash(&self) -> u64 { @@ -346,8 +387,12 @@ impl LayoutQuery<'_> { } impl TextMemo { - fn get(&self, key: &LayoutQuery<'_>) -> Option<&CachedText> { - self.entries.get(&key.hash())?.iter().find(|entry| key.matches(&entry.key)) + /// The entry for `key`, marked as used in this pass. + fn get(&mut self, key: &LayoutQuery<'_>) -> Option<&CachedText> { + let pass = self.pass; + let entry = self.entries.get_mut(&key.hash())?.iter_mut().find(|entry| key.matches(&entry.key))?; + entry.used = pass; + Some(entry) } fn put(&mut self, key: &LayoutQuery<'_>, layout: Option>, least: Option) { @@ -356,6 +401,7 @@ impl TextMemo { return; } let hash = key.hash(); + let pass = self.pass; 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; @@ -363,20 +409,52 @@ impl TextMemo { if least.is_some() { entry.least = least; } + entry.used = pass; + let bytes = retained_bytes(&entry.key, entry.layout.as_deref()); + self.bytes = self.bytes - entry.bytes + bytes; + entry.bytes = bytes; 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); - } + let key = key.owned(); + let bytes = retained_bytes(&key, layout.as_deref()); + if self.bytes + bytes > BUDGET_BYTES { + self.evict_to(EVICT_TO_BYTES.saturating_sub(bytes)); } - self.entries.entry(hash).or_default().push(CachedText { key: key.owned(), layout, least }); - self.order.push_back(hash); + self.bytes += bytes; + self.entries.entry(hash).or_default().push(CachedText { key, layout, least, used: pass, bytes }); + } + + /// Drops the least recently used entries until the memo retains no more than `bytes`. + fn evict_to(&mut self, bytes: usize) { + let mut ages: Vec<(u64, usize)> = self.entries.values().flatten().map(|entry| (entry.used, entry.bytes)).collect(); + ages.sort_unstable_by_key(|&(used, _)| used); + let mut left = self.bytes; + let mut last = None; + for (used, size) in ages { + if left <= bytes { + break; + } + left -= size; + last = Some(used); + } + if let Some(last) = last { + self.retain(|entry| entry.used > last); + } + } + + fn retain(&mut self, keep: impl Fn(&CachedText) -> bool) { + let mut bytes = 0; + self.entries.retain(|_, bucket| { + bucket.retain(|entry| keep(entry)); + bytes += bucket.iter().map(|entry| entry.bytes).sum::(); + !bucket.is_empty() + }); + self.bytes = bytes; + } + + #[cfg(all(feature = "testing", any(test, feature = "suite")))] + fn len(&self) -> usize { + self.entries.values().map(Vec::len).sum() } } @@ -390,7 +468,8 @@ impl TextRun<'_> { direction: env.direction, ink: env.ink, fonts: env.fonts, - width: max_width.to_bits(), + // A `Line` run lays out at infinite width whatever the room (`job`), so every room shares one entry. + width: if self.wrap == Wrap::Line { f32::INFINITY } else { max_width }.to_bits(), scale: ctx.pixels_per_point().to_bits(), } } @@ -651,125 +730,6 @@ pub(crate) fn note_painted(ctx: &Context, layout: &TextLayout) { } } -/// 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>, - changed: Option, -} - -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 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.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` so existing field reads continue to work. -pub struct LayoutRuns { - galley: Arc, - value: Arc>>, - changed: Option>, -} - -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> for LayoutRuns { - fn eq(&self, other: &Vec) -> bool { - self.deref() == other - } -} - -impl Deref for LayoutRuns { - type Target = Vec; - - fn deref(&self) -> &Vec { - 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() - }) - } -} - /// A run laid out whole on its line, and its width at its readable least: what a text that elides measures at /// `Proposal::Min`. #[derive(Clone)] @@ -789,59 +749,51 @@ impl LeastLayout { } /// A laid-out run. +#[derive(Clone)] #[non_exhaustive] pub struct TextLayout { /// The galley. pub galley: Arc, /// The layout cut text. pub elided: bool, - /// The full text, as the tooltip and accessible name of an elided run. - pub full: LayoutText, + /// The full text when it differs from the galley's, which a cut shortened. + full: Option>, /// 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: LayoutRuns, + /// The bidi runs of a single-row layout, built on first read and shared by the layout's clones. + runs: Arc>>, /// 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) + let full = (galley.job.text != full).then(|| Arc::::from(full)); + Self::from_job(galley, elided, full) } + /// The layout of `galley`; `full` is the full text when it differs from the galley's. 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 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 } + TextLayout { galley, elided, full, first_baseline, runs: Arc::default(), rotation: 0.0 } + } + + /// The layout with `galley` in place of its own, the same text placed elsewhere. + pub(super) fn with_galley(self, galley: Arc) -> TextLayout { + TextLayout { galley, runs: Arc::default(), ..self } } /// The full text, as the tooltip and accessible name of an elided run. pub fn full(&self) -> &str { - &self.full + self.full.as_deref().unwrap_or(&self.galley.job.text) } /// The bidi runs of a single-row layout; empty for a wrapped one. pub fn runs(&self) -> &[LayoutRun] { - &self.runs + self.runs.get_or_init(|| if self.galley.rows.len() <= 1 { Self::build_row_runs(&self.galley, 0) } else { Vec::new() }) } /// One run per maximal stretch of glyphs with one direction; an empty row is one empty left-to-right run. @@ -875,11 +827,7 @@ 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.changed.is_none() { - self.runs().to_vec() - } else { - 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() @@ -962,86 +910,76 @@ impl ReadingMeasure { #[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, + Arc, BUDGET_BYTES, Context, Cow, Direction, HAlign, Span, StackFacts, StyleColor, TextEnv, TextRun, TypeRole, UNUSED_PASSES, 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() { + fn tokens() -> UiTokens { 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); + UiTokens::new(Arc::new(resolve(&builtins()[0], appearance, None).tokens), Contrast::Standard, Size::Compact) + } + + fn env(tokens: &UiTokens) -> TextEnv<'_> { + TextEnv { tokens, direction: Direction::Ltr, ink: crate::style::rgba_color(tokens.tokens().color.text.normal), fonts: StackFacts::default() } + } + + /// Runs one pass of `ctx` with `f`. + fn pass(ctx: &Context, f: impl FnMut(&Context)) { + let mut output = ctx.run_pass(Default::default(), f); + output.textures_delta.clear(); + } + + fn entries(ctx: &Context) -> usize { + with_memo(ctx, |memo| memo.len()) + } + + #[trial] + fn cached_layout_does_not_call_egui_layout_for_a_sentinel() { + let tokens = tokens(); + let env = env(&tokens); 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(); + pass(&ctx, |ctx| first = Some(run.layout(ctx, &env, 100.0).galley)); // 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(); + pass(&ctx, |_| {}); } - let mut output = ctx.run_pass(Default::default(), |ctx| { + pass(&ctx, |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 tokens = tokens(); + let env = env(&tokens); 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(), - }; + pass(&ctx, |ctx| { 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()); + // The runs are built on first read, once for every copy of the memo's layout. + assert!(first.runs.get().is_none()); 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 = 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()); + assert!(second.runs.get().is_some()); let again = run.layout(ctx, &env, 80.0); assert_eq!(again.full(), first.full()); assert_eq!(again.runs(), first.runs()); + let before = entries(ctx); 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_eq!(memo.len(), before + 2, "a new room and the least width each add an entry"); assert!(memo.get(&least_key).is_some_and(|entry| entry.least.is_some())); }); let mut variants = Vec::new(); @@ -1097,22 +1035,22 @@ pub(crate) mod memo_tests { changed.rotation = 0.5; variants.push(changed); for changed in variants { - let before = with_memo(ctx, |memo| memo.order.len()); + let before = entries(ctx); 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); + assert_eq!(entries(ctx), 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 semibold = TextEnv { fonts: StackFacts { semibold: true, ..env.fonts }, ..env }; + let system_ui = TextEnv { fonts: StackFacts { system_ui: true, ..env.fonts }, ..env }; + let line_ratio = TextEnv { fonts: StackFacts { line_ratio: 1.25, ..env.fonts }, ..env }; + for changed in [rtl, ink, semibold, system_ui, line_ratio] { + let before = entries(ctx); + let _ = run.layout(ctx, &changed, 80.0); + assert_eq!(entries(ctx), before + 1); + } 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 }; @@ -1124,40 +1062,28 @@ pub(crate) mod memo_tests { 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 before = entries(ctx); let _ = run.layout(ctx, &styled, 80.0); - let before = with_memo(ctx, |memo| memo.order.len()); - assert_eq!(before, 26); + assert_eq!(entries(ctx), before + 1); }); - 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(); + pass(&ctx, |ctx| assert_eq!(entries(ctx), 0)); } #[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 tokens = tokens(); + let env = env(&tokens); 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| { + pass(&ctx, |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| { + pass(&ctx, |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); @@ -1167,18 +1093,83 @@ pub(crate) mod memo_tests { 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| { + pass(&ctx, |ctx| { assert_eq!(ctx.pixels_per_point(), scale); - let before = with_memo(ctx, |memo| memo.order.len()); + let before = entries(ctx); let _ = run.layout(ctx, &env, 80.0); - let after = with_memo(ctx, |memo| memo.order.len()); + let after = entries(ctx); let _ = run.layout(ctx, &env, 80.0); - assert_eq!(with_memo(ctx, |memo| memo.order.len()), after); + assert_eq!(entries(ctx), after); assert_eq!(after, before + 1, "a new scale has its own cached layout"); }); - output.textures_delta.clear(); + } + + #[trial] + fn a_line_label_keeps_one_entry_at_every_room() { + let tokens = tokens(); + let env = env(&tokens); + let ctx = Context::default(); + let line = TextRun::new("a one-line label"); + let wrapped = TextRun::new("a wrapping paragraph").wrap(Wrap::Wrap); + pass(&ctx, |ctx| { + let first = line.layout(ctx, &env, 100.0); + let before = entries(ctx); + // A window resize offers the label a new room every pass. + for room in (101..150).map(|room| room as f32) { + assert!(Arc::ptr_eq(&line.layout(ctx, &env, room).galley, &first.galley), "a Line run hits at room {room}"); + } + let _ = line.least_width(ctx, &env); + assert_eq!(entries(ctx), before, "the label's rooms and its least width share one entry"); + for room in [100.0, 120.0, 140.0] { + let _ = wrapped.layout(ctx, &env, room); + } + assert_eq!(entries(ctx), before + 3, "a wrapping run keeps one entry per room"); + }); + } + + #[trial] + fn a_used_label_stays_while_a_changing_label_churns() { + let tokens = tokens(); + let env = env(&tokens); + let ctx = Context::default(); + let label = TextRun::new("a static label"); + let mut first = None; + let passes = 3 * UNUSED_PASSES; + for at in 0..passes { + pass(&ctx, |ctx| { + let shown = label.layout(ctx, &env, 100.0).galley; + assert!(Arc::ptr_eq(first.get_or_insert_with(|| shown.clone()), &shown), "the static label hits in pass {at}"); + let _ = TextRun::new(format!("frame {at}")).layout(ctx, &env, 100.0); + }); + } + // Each pass leaves one entry for the changing label; only the passes still kept hold theirs. + let kept = entries(&ctx); + assert!(kept > 1 && (kept as u64) <= UNUSED_PASSES + 1, "{kept} entries after {passes} passes"); + } + + #[trial] + fn many_wide_paragraphs_at_many_widths_stay_within_the_budget() { + let tokens = tokens(); + let env = env(&tokens); + let ctx = Context::default(); + let paragraph = "A paragraph wide enough to wrap into many rows at every width the trial offers. ".repeat(150); + let run = TextRun::new(¶graph).wrap(Wrap::Wrap); + pass(&ctx, |ctx| { + let mut added = 0; + let mut room = 200.0; + // Lay out until the layouts would have retained twice the budget. + while added <= 2 * BUDGET_BYTES { + let layout = run.layout(ctx, &env, room); + added += super::retained_bytes(&run.layout_key(ctx, &env, room).owned(), Some(&layout)); + with_memo(ctx, |memo| { + assert!(memo.bytes <= BUDGET_BYTES, "{} bytes retained", memo.bytes); + assert_eq!(memo.bytes, memo.entries.values().flatten().map(|entry| entry.bytes).sum::()); + }); + assert!(Arc::ptr_eq(&run.layout(ctx, &env, room).galley, &layout.galley), "the newest layout is kept"); + room += 7.0; + } + }); } } diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 248c09145..e9c7866fb 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -615,7 +615,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut state.focused = shown.focused || input.held; let full = display; let layout = TextLayout::new(shown.galley, false, full); - let baseline = (!layout.full.is_empty()).then_some(shown.galley_pos.y + layout.first_baseline); + let baseline = (!layout.full().is_empty()).then_some(shown.galley_pos.y + layout.first_baseline); AdapterOut { layout, focused: shown.focused, tab, clicked: shown.clicked, baseline } } @@ -643,7 +643,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { let ctx = ui.ctx().clone(); let multiline = run.wrap == crate::primitives::Wrap::Wrap; let keep = if multiline { KeepKeys::BlockArrows } else { KeepKeys::InlineArrows }; - let mut shown = layout.full.clone(); + let mut shown = layout.full().to_owned(); // A line longer than its room is cut at the room's edge, as a field's is. let mut cut = (layout.size().x > rect.width()).then(|| { let mut cut = crate::runtime::egui::alloc::child(ui, egui::UiBuilder::new().max_rect(rect)); diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index 4eaa6c044..ec344c991 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -337,6 +337,6 @@ impl<'a> EditorState<'a> { impl TextLayout { /// The layout's runs as the borrowed runs an editor line takes. pub fn editor_runs(&self) -> Vec> { - self.runs.iter().map(|run| EditorRun::new(run.bytes.clone(), run.rtl, &run.positions, &run.widths)).collect() + self.runs().iter().map(|run| EditorRun::new(run.bytes.clone(), run.rtl, &run.positions, &run.widths)).collect() } } diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 22c67fc11..38a7d029b 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -458,11 +458,6 @@ 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 13de6d95d..6a789786a 100644 --- a/crates/ui-contract/src/runtime/measure.rs +++ b/crates/ui-contract/src/runtime/measure.rs @@ -235,35 +235,6 @@ 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) || uncounted(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 195516379..12c245f68 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -55,9 +55,8 @@ 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_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}; diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index 5d6651bc4..556140903 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -7,7 +7,6 @@ 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; diff --git a/crates/ui-contract/tests/it/contract/prepared.rs b/crates/ui-contract/tests/it/contract/prepared.rs deleted file mode 100644 index 1659c9b73..000000000 --- a/crates/ui-contract/tests/it/contract/prepared.rs +++ /dev/null @@ -1,230 +0,0 @@ -//! 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>, -} - -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"); -} - -#[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"); -} - -#[derive(Component)] -struct LeastTwice { - #[common] - common: Common, - measured: Rc>, -} - -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"); -} diff --git a/crates/ui-contract/tests/it/layout/fill.rs b/crates/ui-contract/tests/it/layout/fill.rs index 140adc854..03a7d1935 100644 --- a/crates/ui-contract/tests/it/layout/fill.rs +++ b/crates/ui-contract/tests/it/layout/fill.rs @@ -127,17 +127,6 @@ const LINE: f32 = 20.0; struct Asked { ideal: Cell, min: Cell, - pair: Cell, - 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. @@ -147,13 +136,12 @@ 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, paired: false, track_input: false } + Stretch { common: Common::new(), seen, asked, track_input: false } } } @@ -167,7 +155,6 @@ 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(); } @@ -178,25 +165,6 @@ 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() } @@ -210,67 +178,6 @@ 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())); @@ -284,23 +191,25 @@ fn a_nested_body_reuses_a_settled_transcript_and_remeasures_after_its_room_chang 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); }); }); }); + // The measures the child answered in measuring runs. + let measured = |asked: &Asked| asked.ideal.get() + asked.min.get(); fixture.room(Vec2::new(240.0, 100.0)).settle(); - assert!(sweeps.get() > 0 && asked.pair.get() > 0, "the first layout measures the nested body"); + assert!(sweeps.get() > 0 && measured(&asked) > 0, "the first layout measures the nested body"); let before = seen.borrow().rect; sweeps.set(0); - asked.pair.set(0); + asked.ideal.set(0); + asked.min.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!(measured(&asked), 0, "recorded inputs need no new measure 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"); + assert!(sweeps.get() > 0 && measured(&asked) > 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:?}"); } diff --git a/crates/ui-contract/tests/it/text/memo.rs b/crates/ui-contract/tests/it/text/memo.rs new file mode 100644 index 000000000..0bc5fc447 --- /dev/null +++ b/crates/ui-contract/tests/it/text/memo.rs @@ -0,0 +1,63 @@ +//! The text layout memo seen from a component's measure. + +use craft_behavior::Sense; +use craft_ui::contract::{Common, Component, Cx, MeasureCx, Props as _, Role, Show as _}; +use craft_ui::primitives::TextRun; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, 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 LeastTwice { + #[common] + common: Common, + measured: Rc>, +} + +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"); +} diff --git a/crates/ui-contract/tests/it/text/mod.rs b/crates/ui-contract/tests/it/text/mod.rs index 35907c463..abda7da2e 100644 --- a/crates/ui-contract/tests/it/text/mod.rs +++ b/crates/ui-contract/tests/it/text/mod.rs @@ -1,2 +1,3 @@ pub(crate) mod editor; pub(crate) mod input_cap; +pub(crate) mod memo; diff --git a/crates/ui-widgets/src/buttons/button.rs b/crates/ui-widgets/src/buttons/button.rs index 2e7e47526..c24f7ecde 100644 --- a/crates/ui-widgets/src/buttons/button.rs +++ b/crates/ui-widgets/src/buttons/button.rs @@ -294,18 +294,6 @@ 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 } } diff --git a/crates/ui-widgets/src/buttons/face.rs b/crates/ui-widgets/src/buttons/face.rs index 7f7151d2d..ff45035a1 100644 --- a/crates/ui-widgets/src/buttons/face.rs +++ b/crates/ui-widgets/src/buttons/face.rs @@ -425,11 +425,6 @@ 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) { - (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(); diff --git a/crates/ui-widgets/src/buttons/link.rs b/crates/ui-widgets/src/buttons/link.rs index cb788bf5f..a4093c40c 100644 --- a/crates/ui-widgets/src/buttons/link.rs +++ b/crates/ui-widgets/src/buttons/link.rs @@ -95,20 +95,6 @@ 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 0970527b6..686aeeefd 100644 --- a/crates/ui-widgets/src/buttons/split_button.rs +++ b/crates/ui-widgets/src/buttons/split_button.rs @@ -197,19 +197,6 @@ 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 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)) - } - 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 e7e045ed3..f6baee3a2 100644 --- a/crates/ui-widgets/src/buttons/toggle_button.rs +++ b/crates/ui-widgets/src/buttons/toggle_button.rs @@ -164,12 +164,6 @@ 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 7ed3d3b1a..aa75a0e99 100644 --- a/crates/ui-widgets/src/display/text.rs +++ b/crates/ui-widgets/src/display/text.rs @@ -126,26 +126,6 @@ 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) -> 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() } @@ -223,33 +203,33 @@ impl Component for Text { _ => layout.size(), }; } - let run = self.run(cx.style.text.role, cx.resolved.label); + 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. if cx.proposal == Proposal::Min { - if self.elide == Elide::Off { - let widest = self.widest_word(cx); - return Vec2::new(widest, cx.layout_at(&run, widest).size().y); - } + let run = self.run(role, cx.resolved.label); return cx.least(&run).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)> { - if !self.spans.is_empty() { - return None; + 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); + } } - 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))); + // 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 ideal_size = self.ideal_plain(ideal, &run, band, None); - Some((ideal_size, least.least(&run).size())) } fn cut_first(&self) -> bool { diff --git a/crates/ui-widgets/src/pickers/face.rs b/crates/ui-widgets/src/pickers/face.rs index 202a9b017..4ae005ecd 100644 --- a/crates/ui-widgets/src/pickers/face.rs +++ b/crates/ui-widgets/src/pickers/face.rs @@ -216,33 +216,6 @@ 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(); diff --git a/crates/ui-widgets/tests/it/buttons.rs b/crates/ui-widgets/tests/it/buttons.rs index 9096237f0..e310965ab 100644 --- a/crates/ui-widgets/tests/it/buttons.rs +++ b/crates/ui-widgets/tests/it/buttons.rs @@ -2,24 +2,21 @@ //! 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, Sense}; +use craft_behavior::{IconId, PartKey}; 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, Common, Component, Cx, Entry, Hover, MeasureCx, Props as _, Role, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, CommandSet, Entry, Hover, Props as _, Role, Show as _}; 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, 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 craft_ui::testing::{Fixture, trial}; +use egui::{Event, Id, Pos2, Rect, Response, Ui}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -31,98 +28,6 @@ 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) { diff --git a/docs/contract-api.md b/docs/contract-api.md index 3bc202cac..88ba467a8 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1025,6 +1025,7 @@ Box geometry of transform boxes: where the box goes when a part of it is dragged - `pub const fn new(along: Axis, position: f64, kind: SnapKind) -> Self`. A full-height line of `kind` running `along` an axis, at `position` across it: a line along `Axis::Y` - `craft_behavior::geometry::snap::SnapTargets`: `pub struct SnapTargets`. The snap targets of one gesture. - `pub fn new() -> Self`. No targets. + - `pub fn reach_past_spans(mut self) -> Self`. These targets with every span reaching past its extent: a target catches a point or box anywhere along its - `pub fn add(&mut self, target: SnapTarget)`. Add one target. - `pub fn add_rect(&mut self, rect: Rect, edge: SnapKind, center: SnapKind)`. Add a rectangle's four edges as `edge` targets and its two centre lines as `center` - `pub fn with_document(self, options: &SnapOptions, bounds: Rect, guides: impl IntoIterator, grid: Option<(Point, Vec2)>,) -> Self`. Guides as full-height targets, grid lines of `spacing` from `origin` over `bounds`, the @@ -1777,10 +1778,10 @@ The base of the craft UI library: runtime, style, fonts, primitives, the compone - `craft_ui::bind_tracked!`: `macro_rules! bind_tracked`. Write-through bindings to fields of a [`Tracked`](crate::contract::Tracked) value: `bind_tracked!(doc => size)` - `craft_ui::stays!`: `macro_rules! stays`. Types with no place: they stay as they are at any place. -- `craft_ui::testing_registered!`: `macro_rules! testing_registered`. Writes `pub fn registered()` for the invoking package: its library crate's registrations in the running binary. - `craft_ui::InstallError`: re-export of `craft_ui::runtime::install::InstallError`. - `craft_ui::InstallSpec`: re-export of `craft_ui::runtime::install::InstallSpec`. - `craft_ui::install`: re-export of `craft_ui::contract::install`. +- `craft_ui::registry`: re-export of `craft_ui_macros::registry` (outside these crates). - `craft_ui::words`: re-export of `craft_ui_macros::words` (outside these crates). ## `craft_ui::contract` @@ -3058,7 +3059,9 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `craft_ui::primitives::TextKey`: `pub struct TextKey`. A text part's key, typed by the value its codec gives. - `pub const fn new(key: PartKey) -> Self`. The key of the text part `key`. - `pub const fn key(self) -> PartKey`. The part key. -- `craft_ui::primitives::TextLayout`: `pub struct TextLayout { pub galley: Arc, pub elided: bool, pub full: String, pub first_baseline: f32, pub runs: Vec, pub rotation: f32 }`. A laid-out run. +- `craft_ui::primitives::TextLayout`: `pub struct TextLayout { pub galley: Arc, pub elided: bool, pub first_baseline: f32, pub rotation: f32 }`. A laid-out run. + - `pub fn full(&self) -> &str`. The full text, as the tooltip and accessible name of an elided run. + - `pub fn runs(&self) -> &[LayoutRun]`. The bidi runs of a single-row layout; empty for a wrapped one. - `pub fn size(&self) -> egui::Vec2`. The galley size. - `pub fn char_x(&self, chars: usize) -> f32`. Where a caret before character `chars` (counted from the start of the text) stands, from the layout's left edge: - `craft_ui::primitives::TextOptions`: `pub struct TextOptions { pub placeholder: Option