From 66391f53ed923adbe36099199b97ae420be930d1 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 00:24:59 +0000 Subject: [PATCH 1/4] ui-contract: a run reaches its pass state and its pass facts through one binding The running pass's facts live on the thread's entry for its context, beside the pass state, so frame::running, current_viewport, pass_nr and frame_nr read the component tree's binding instead of a second thread-local searched by context. Inside the tree, pass_state::with runs on the bound state directly; the visit through a dyn callback serves only reads outside it. Per-viewport records of types the pass state names no field for (Facts, dock targets, toasts and the other Stored types) live in the pass state by type, not in egui context data behind its data lock and a service mutex. The memory eviction sweep reads the running pass once, not once per owner. Trial: a settled pass of forty command-bound leaves makes as many context-data lookups and unbound pass-state reads as one of ten. --- crates/ui-contract/src/runtime/egui/pass.rs | 8 +- crates/ui-contract/src/runtime/frame.rs | 42 ++--- crates/ui-contract/src/runtime/memory.rs | 3 +- crates/ui-contract/src/runtime/pass_state.rs | 157 +++++++++++++++---- crates/ui-contract/src/testing/mod.rs | 2 + crates/ui-contract/tests/it/runtime/frame.rs | 16 +- 6 files changed, 154 insertions(+), 74 deletions(-) diff --git a/crates/ui-contract/src/runtime/egui/pass.rs b/crates/ui-contract/src/runtime/egui/pass.rs index cfcbaa3c77..f3a7d6f928 100644 --- a/crates/ui-contract/src/runtime/egui/pass.rs +++ b/crates/ui-contract/src/runtime/egui/pass.rs @@ -5,7 +5,13 @@ use egui::{Context, ViewportId}; /// The pass number of `viewport`; it counts every pass, discard passes included. pub(crate) fn pass_nr(ctx: &Context, viewport: ViewportId) -> u64 { - match frame::running(ctx) { + pass_nr_beside(ctx, frame::running(ctx), viewport) +} + +/// The pass number of `viewport` while `running` is the running pass: for a sweep over the records of every viewport, +/// which reads the running pass once. +pub(crate) fn pass_nr_beside(ctx: &Context, running: Option, viewport: ViewportId) -> u64 { + match running { Some(facts) if facts.viewport == viewport => facts.pass_nr, _ => ctx.cumulative_pass_nr_for(viewport), } diff --git a/crates/ui-contract/src/runtime/frame.rs b/crates/ui-contract/src/runtime/frame.rs index 2b5922e90a..feee472396 100644 --- a/crates/ui-contract/src/runtime/frame.rs +++ b/crates/ui-contract/src/runtime/frame.rs @@ -2,7 +2,6 @@ use crate::runtime::commands::{self, CommandInput, CommandSet as _, Fired}; use crate::runtime::egui::input::{self as raw_input, Arrived, HeldInput, RawInput}; -use crate::runtime::egui::memory as store; use crate::runtime::egui::{clipboard, pass, scale, style}; use crate::runtime::env::{AltCodePages, Env, RootEnv, WheelSpeed, WindowKey}; use crate::runtime::pass_state; @@ -14,7 +13,6 @@ use craft_keymap::Mods; use craft_theme::{AppSizes, Appearance, Contrast, HitSizes, Mode, SUITE_DEFAULT, Size, TextSize, ThemeDef, builtins, resolve_sized}; use egui::{Context, Id, Ui, ViewportId}; use std::any::TypeId; -use std::cell::RefCell; use std::collections::HashMap; use std::sync::Arc; @@ -275,18 +273,18 @@ impl PerViewport { } } -/// Where the records of a [`PerViewport`] type live: a context service unless the type is pass-local -/// (`runtime::pass_state`), which overrides these. +/// Where the records of a [`PerViewport`] type live: in the context's pass state, a field of it for the types the +/// runtime names there (`runtime::pass_state`, which overrides these), else by type beside the fields. #[doc(hidden)] pub trait Stored: Default + Send + 'static { /// Runs `f` on the records of this type. fn records(ctx: &Context, f: impl FnOnce(&mut PerViewport) -> R) -> R { - store::with::, R>(ctx, f) + pass_state::with_records::(ctx, f) } /// Runs `f` on the stamped records of this type. fn stamped(ctx: &Context, f: impl FnOnce(&mut PerViewport>) -> R) -> R { - store::with::>, R>(ctx, f) + pass_state::with_records::, R>(ctx, f) } } @@ -681,14 +679,6 @@ struct ViewportRecord { impl Stored for ViewportRecord {} -/// What the begin hook read of the running pass; steps read it, none writes it. -#[derive(Clone)] -struct RunningPass { - /// The context the pass runs in. Another context on the same thread, and a pass a panic left open, read none of these. - ctx: Context, - facts: PassFacts, -} - /// What a pass fixes for every step: its viewport, numbers and time. #[derive(Clone, Copy)] #[doc(hidden)] @@ -703,15 +693,11 @@ pub struct PassFacts { pub elapsed: f64, } -thread_local! { - /// The passes between their begin and end hooks on this thread, innermost last: nested viewport passes stack. - static RUNNING: RefCell> = const { RefCell::new(Vec::new()) }; -} - -/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. +/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. The begin hook +/// reads them; steps read them, none writes them. #[doc(hidden)] pub fn running(ctx: &Context) -> Option { - RUNNING.with(|running| running.borrow().iter().rev().find(|pass| pass.ctx == *ctx).map(|pass| pass.facts)) + pass_state::running(ctx) } /// The facts of the innermost running pass of `ctx`, or outside every pass of it, what the context says of its @@ -840,13 +826,8 @@ pub(crate) fn begin_pass(ui: &mut Ui) { let elapsed = record.now.replace(now).map_or(0.0, |previous| (now - previous).max(0.0)); (elapsed, std::mem::take(&mut record.press_cancelled)) }); - RUNNING.with(|running| { - let mut running = running.borrow_mut(); - // A pass of this viewport that never ended (a panic unwound through it) is not still running. - running.retain(|pass| !(pass.ctx == ctx && pass.facts.viewport == viewport)); - running.push(RunningPass { ctx: ctx.clone(), facts: PassFacts { viewport, pass_nr, frame_nr, now, elapsed } }); - }); pass_state::hold(&ctx); + pass_state::begin_running(&ctx, PassFacts { viewport, pass_nr, frame_nr, now, elapsed }); if root_pass.is_some() && pass::first_of_frame(&ctx) { prune_closed(&ctx); } @@ -916,11 +897,6 @@ pub(crate) fn end_pass(ui: &mut Ui) { pass_state::with::(&ctx, |state| state.passes_open = state.passes_open.saturating_sub(1)); #[cfg(feature = "testing")] crate::runtime::egui::access::check_parents_acyclic(&ctx); - RUNNING.with(|running| { - let mut running = running.borrow_mut(); - if let Some(at) = running.iter().rposition(|pass| pass.ctx == ctx) { - running.remove(at); - } - }); + pass_state::end_running(&ctx); pass_state::release(&ctx); } diff --git a/crates/ui-contract/src/runtime/memory.rs b/crates/ui-contract/src/runtime/memory.rs index b0da0f3da0..fb53719828 100644 --- a/crates/ui-contract/src/runtime/memory.rs +++ b/crates/ui-contract/src/runtime/memory.rs @@ -326,8 +326,9 @@ fn end_lives(reg: &mut Registry, owners: impl IntoIterator) { pub(crate) fn evict(ctx: &Context) { let now = frame::clock(ctx); let live = pass::live_viewports(ctx); + let running = frame::running(ctx); pass_state::with::(ctx, |reg| { - let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr(ctx, r.viewport), now, live.contains(&r.viewport)); + let due = |r: &OwnerRecord| owner_due(r.pass, r.at, pass::pass_nr_beside(ctx, running, r.viewport), now, live.contains(&r.viewport)); let dead: IdSet = reg.owners.iter().filter(|(_, r)| due(r)).map(|(id, _)| *id).collect(); if dead.is_empty() { return; diff --git a/crates/ui-contract/src/runtime/pass_state.rs b/crates/ui-contract/src/runtime/pass_state.rs index 2ac5ad08b6..8e9d1f9415 100644 --- a/crates/ui-contract/src/runtime/pass_state.rs +++ b/crates/ui-contract/src/runtime/pass_state.rs @@ -10,9 +10,10 @@ //! context runs. Another thread can't reach the state while a pass holds it: the runtime touches these services only //! from the thread that runs the pass. -use crate::runtime::egui::memory::Service; -use crate::runtime::frame::{self, PerViewport, Stamped, Stored}; +use crate::runtime::egui::memory::{FastMap, Service}; +use crate::runtime::frame::{PassFacts, PerViewport, Stamped, Stored}; use egui::{Context, IdSet}; +use std::any::{Any, TypeId}; use std::cell::{Cell, RefCell}; use std::sync::Arc; @@ -33,6 +34,9 @@ macro_rules! pass_state { $($(#[$service_attr])* $service: RefCell<$service_ty>,)* $($record: RefCell>,)* $($stamped: RefCell>>,)* + /// The per-viewport records of the types with no field here (generic ones, and those of crates above the + /// runtime), by type: each value is a `RefCell>`. + others: RefCell>>, } $($(#[$service_attr])* impl PassLocal for $service_ty { @@ -163,6 +167,15 @@ pass_state! { struct Held { ctx: Context, state: Box, + /// The context's passes between their begin and end hooks on this thread, innermost last: nested viewport passes + /// stack. A pass a panic unwound through stays until a pass of its viewport begins again. + passes: RefCell>, +} + +impl Held { + fn running(&self) -> bool { + !self.passes.borrow().is_empty() + } } struct HeldStates { @@ -178,13 +191,13 @@ impl HeldStates { /// Service reads in the same context reuse its slot. A nested context or a swap on release /// can change the slot, so verify its owner before reusing it. - fn get(&self, ctx: &Context) -> Option<&PassState> { + fn get(&self, ctx: &Context) -> Option<&Held> { if let Some(entry) = self.entries.get(self.current.get()).filter(|entry| entry.ctx == *ctx) { - return Some(&entry.state); + return Some(entry); } let at = self.entries.iter().position(|entry| entry.ctx == *ctx)?; self.current.set(at); - Some(&self.entries[at].state) + Some(&self.entries[at]) } } @@ -214,7 +227,7 @@ pub(crate) fn with_component_tree(ctx: &Context, run: impl FnOnce()) { impl Drop for Restore { fn drop(&mut self) { if let Some(entry) = self.0.take() { - if frame::running(&entry.ctx).is_some() { + if entry.running() { keep(entry); } else { park(entry); @@ -249,34 +262,103 @@ impl Default for Parked { pub(crate) fn with(ctx: &Context, f: impl FnOnce(&mut S) -> R) -> R { #[cfg(feature = "testing")] crate::runtime::layout_memory::guard::touch::(); + with_state(ctx, |state| f(&mut S::cell(state).borrow_mut())) +} + +/// Runs `f` on the context's records of `T`, one per viewport, for a type with no field in [`PassState`]. `f` makes +/// no call that reaches the context, so no other record of this kind is first used inside it. +pub(crate) fn with_records(ctx: &Context, f: impl FnOnce(&mut PerViewport) -> R) -> R { + with_state(ctx, |state| { + let key = TypeId::of::>(); + if !state.others.borrow().contains_key(&key) { + state.others.borrow_mut().insert(key, Box::new(RefCell::new(PerViewport::::default()))); + } + let others = state.others.borrow(); + #[expect(clippy::expect_used, reason = "the entry under a type's id is created above with that type")] + let records = others.get(&key).and_then(|records| records.downcast_ref::>>()).expect("the records of the type"); + f(&mut records.borrow_mut()) + }) +} + +/// The facts of the innermost running pass of `ctx` on this thread, `None` outside every pass of it. +pub(crate) fn running(ctx: &Context) -> Option { + if RUNNING.is_set() + && let Some(facts) = RUNNING.with(|entry| (entry.ctx == *ctx).then(|| entry.passes.borrow().last().copied())) + { + return facts; + } + note_unbound(); + HELD.with(|held| held.borrow().get(ctx).and_then(|entry| entry.passes.borrow().last().copied())) +} + +/// Puts the pass the begin hook starts on the running stack of `ctx`, whose state this thread holds: a pass of the +/// same viewport still there never ended (a panic unwound through it). +pub(crate) fn begin_running(ctx: &Context, facts: PassFacts) { + let held = with_entry(ctx, |entry| { + let mut passes = entry.passes.borrow_mut(); + passes.retain(|pass| pass.viewport != facts.viewport); + passes.push(facts); + }); + debug_assert!(held.is_some(), "the begin hook holds the context's pass state"); +} + +/// Takes the innermost pass of `ctx` off its running stack: the end hook. +pub(crate) fn end_running(ctx: &Context) { + with_entry(ctx, |entry| entry.passes.borrow_mut().pop()); +} + +/// Runs `f` on the entry of `ctx` this thread holds, bound or not. +fn with_entry(ctx: &Context, f: impl FnOnce(&Held) -> R) -> Option { + if bound(ctx) { + return Some(RUNNING.with(f)); + } + HELD.with(|held| held.borrow().get(ctx).map(f)) +} + +/// Runs `f` on the context's pass state: inside its component tree, straight from the binding. +fn with_state(ctx: &Context, f: impl FnOnce(&PassState) -> R) -> R { let mut call = Some(f); + if RUNNING.is_set() + && let Some(out) = RUNNING.with(|entry| if entry.ctx == *ctx { call.take().map(|f| f(&entry.state)) } else { None }) + { + return out; + } + note_unbound(); let mut out = None; visit(ctx, &mut |state| { if let Some(f) = call.take() { - out = Some(f(&mut S::cell(state).borrow_mut())); + out = Some(f(state)); } }); #[expect(clippy::expect_used, reason = "visit calls its callback once on both the held and parked paths")] out.expect("the pass state was visited") } -/// The thread-local lookup and the parked-state slow path are shared by every service and caller. +#[cfg(feature = "testing")] +thread_local! { + static UNBOUND: Cell = const { Cell::new(0) }; +} + +/// How many reads of a pass state this thread made outside the component tree that binds it. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn unbound_reads() -> u64 { + UNBOUND.with(Cell::get) +} + +#[inline] +fn note_unbound() { + #[cfg(feature = "testing")] + UNBOUND.with(|reads| reads.set(reads.get() + 1)); +} + +/// The state of a context its component tree does not bind: the thread's held entry, else the parked state, held for +/// this read alone. Shared by every service and caller. fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) { - if RUNNING.is_set() - && RUNNING.with(|entry| { - if entry.ctx != *ctx { - return false; - } - f(&entry.state); - true - }) - { - return; - } let found = HELD.with(|held| { let held = held.borrow(); - let Some(state) = held.get(ctx) else { return false }; - f(state); + let Some(entry) = held.get(ctx) else { return false }; + f(&entry.state); true }); if !found { @@ -292,8 +374,8 @@ fn visit(ctx: &Context, f: &mut dyn FnMut(&PassState)) { HELD.with(|held| { let held = held.borrow(); #[expect(clippy::expect_used, reason = "`hold` has just moved the context's state into this thread")] - let state = held.get(ctx).expect("the state was just taken"); - f(state) + let entry = held.get(ctx).expect("the state was just taken"); + f(&entry.state) }) } } @@ -304,8 +386,7 @@ pub(crate) fn hold(ctx: &Context) { if bound(ctx) { return; } - let stale: Vec = - HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && frame::running(&entry.ctx).is_none()).collect()); + let stale: Vec = HELD.with(|held| held.borrow_mut().entries.extract_if(.., |entry| entry.ctx != *ctx && !entry.running()).collect()); for held in stale { park(held); } @@ -315,15 +396,19 @@ pub(crate) fn hold(ctx: &Context) { let state = Service::::run(ctx, |parked| parked.0.take()); debug_assert!(state.is_some(), "another thread holds this context's pass state"); let state = state.unwrap_or_default(); - keep(Held { ctx: ctx.clone(), state }); + keep(Held { ctx: ctx.clone(), state, passes: RefCell::new(Vec::new()) }); } /// Moves the context's state back into its context data unless a pass of it still runs on this thread: the end hook. pub(crate) fn release(ctx: &Context) { - if bound(ctx) || frame::running(ctx).is_some() { + if bound(ctx) { return; } - if let Some(held) = HELD.with(|held| held.borrow_mut().take(ctx)) { + let idle = HELD.with(|held| { + let mut held = held.borrow_mut(); + if held.get(ctx).is_some_and(Held::running) { None } else { held.take(ctx) } + }); + if let Some(held) = idle { park(held); } } @@ -334,14 +419,13 @@ fn park(held: Held) { #[cfg(all(feature = "testing", any(test, feature = "suite")))] pub(crate) mod binding_tests { - use super::{PassState, bound, hold, in_component_tree, visit, with_component_tree}; + use super::{PassState, begin_running, bound, end_running, hold, in_component_tree, release, running, with_component_tree, with_state}; + use crate::runtime::frame::PassFacts; use crate::testing::trial; - use egui::Context; + use egui::{Context, ViewportId}; fn address(ctx: &Context) -> *const PassState { - let mut address = std::ptr::null(); - visit(ctx, &mut |state| address = std::ptr::from_ref(state)); - address + with_state(ctx, std::ptr::from_ref) } #[trial] @@ -349,11 +433,14 @@ pub(crate) mod binding_tests { let outer = Context::default(); let inner = Context::default(); hold(&outer); + begin_running(&outer, PassFacts { viewport: ViewportId::ROOT, pass_nr: 7, frame_nr: 7, now: 0.0, elapsed: 0.0 }); let original = address(&outer); let unwound = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { with_component_tree(&outer, || { assert!(bound(&outer)); assert!(!bound(&inner)); + assert_eq!(running(&outer).map(|facts| facts.pass_nr), Some(7), "the tree reads its pass from the binding"); + assert!(running(&inner).is_none(), "a nested context has no pass running"); assert_ne!(address(&inner), original); assert_eq!(address(&outer), original); std::panic::resume_unwind(Box::new("component unwound")); @@ -362,5 +449,9 @@ pub(crate) mod binding_tests { assert!(unwound.is_err_and(|reason| reason.downcast_ref::<&str>() == Some(&"component unwound"))); assert!(!in_component_tree()); assert_eq!(address(&outer), original); + assert_eq!(running(&outer).map(|facts| facts.pass_nr), Some(7), "the running pass outlives the unwound tree"); + end_running(&outer); + release(&outer); + assert!(running(&outer).is_none()); } } diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index d6acf5d4f5..e4ca903c4d 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -61,6 +61,8 @@ pub use crate::runtime::measure::{ last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, last_pass_text_layouts, last_pass_tip_texts, least_runs as shrink_least_runs, row_builds, row_measures, run as measuring_run, take_effects, widest_runs, }; +#[cfg(feature = "testing")] +pub use crate::runtime::pass_state::unbound_reads as unbound_pass_state_reads; pub use craft_ui_macros::{story, trial}; pub use fixture::{Fixture, Impure, Room, Target}; pub use frames::Frames; diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index 5c0ba16b23..f2e45c04c2 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -59,11 +59,14 @@ fn one_press_per_pass_and_a_discard_pass_gets_no_held_events() { assert_eq!(run(&mut frames, vec![], false), vec![Vec::<&str>::new()]); } -/// Pass-local state: inside a pass the pipeline looks up no service in context data per run, so a settled pass of -/// forty leaves makes as many lookups as one of ten. +/// Pass-local state: inside a pass the pipeline looks up no service in context data per run, and each run reaches the +/// pass state and the pass's facts through its component tree's binding, so a settled pass of forty command-bound +/// leaves (each registers the command it shows, a per-viewport record) makes as many lookups and unbound reads as one +/// of ten. #[trial] fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() { use craft_ui::runtime::egui::memory::service_lookups; + use craft_ui::testing::unbound_pass_state_reads; use craft_ui_test_kit::contract::Panel; let settled_lookups = |leaves: usize| { let mut frames = Frames::new(); @@ -71,19 +74,20 @@ fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() { Panel::new().id_salt("leaves").show(ui, |ui, _| { for at in 0..leaves { let seen = std::cell::RefCell::new(Seen::default()); - Probe::new(&seen).label(format!("Leaf {at}")).show(ui); + Probe::new(&seen).label(format!("Leaf {at}")).command(Shown::Apply).show(ui); } }); }; for _ in 0..3 { frames.frame(vec![], &mut show); } - let before = service_lookups(); + let (lookups, unbound) = (service_lookups(), unbound_pass_state_reads()); frames.frame(vec![], &mut show); - service_lookups() - before + (service_lookups() - lookups, unbound_pass_state_reads() - unbound) }; - let (ten, forty) = (settled_lookups(10), settled_lookups(40)); + let ((ten, ten_unbound), (forty, forty_unbound)) = (settled_lookups(10), settled_lookups(40)); assert_eq!(ten, forty, "context-data lookups grow with the runs: {ten} for ten leaves, {forty} for forty"); + assert_eq!(ten_unbound, forty_unbound, "unbound pass-state reads grow with the runs: {ten_unbound} for ten leaves, {forty_unbound} for forty"); } /// The app command the settled view's probe is bound to; its modal rule is the default one, `Blocked`. From a9adb36c6aced37b6a892bb1935e0125dcc1e90f Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 00:48:00 +0000 Subject: [PATCH 2/4] ui-contract: a run reads its place from the env its parent installed A run takes the env its parent installed for its Ui from its caller (or one Env::of where app code shows it) and keeps it as its place env: Begun, Pass and Measuring carry it, the shape hooks' sized and extent take it, and every layout/body.rs helper takes the env its Ui's children are placed under instead of walking the Ui stack again. MeasureCx keeps the env it views for column_room. Lazy and memoized views, the label step, collections and bodies pass the env they hold. A testing counter (env_walks) pins at most one walk per run. --- crates/ui-contract/src/contract/body/hooks.rs | 58 ++-- crates/ui-contract/src/contract/body/size.rs | 22 +- crates/ui-contract/src/contract/cx/body.rs | 11 +- crates/ui-contract/src/contract/cx/measure.rs | 5 +- .../ui-contract/src/contract/items/hooks.rs | 18 +- .../ui-contract/src/contract/items/measure.rs | 29 +- crates/ui-contract/src/contract/label/step.rs | 59 ++-- crates/ui-contract/src/contract/lazy.rs | 65 ++-- crates/ui-contract/src/contract/memo_view.rs | 13 +- crates/ui-contract/src/contract/mod.rs | 22 +- crates/ui-contract/src/contract/pages.rs | 4 +- crates/ui-contract/src/contract/paint_ui.rs | 5 +- crates/ui-contract/src/contract/run.rs | 119 ++++--- crates/ui-contract/src/contract/run/typed.rs | 30 +- .../ui-contract/src/contract/steps/measure.rs | 1 + .../ui-contract/src/contract/steps/place.rs | 13 +- crates/ui-contract/src/contract/text.rs | 12 +- crates/ui-contract/src/layout/arrange.rs | 5 +- crates/ui-contract/src/layout/body.rs | 316 ++++++++---------- crates/ui-contract/src/layout/mod.rs | 2 +- crates/ui-contract/src/runtime/env.rs | 14 + crates/ui-contract/src/testing/mod.rs | 2 + crates/ui-contract/src/testing/stage.rs | 10 +- crates/ui-contract/tests/it/runtime/frame.rs | 33 ++ 24 files changed, 480 insertions(+), 388 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 8de6334818..3398c31500 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -302,18 +302,17 @@ impl ShapeHooks for BodyHooks<'_> { self.overflow } - fn extent(&mut self, comp: &C, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { + fn extent(&mut self, comp: &C, ui: &Ui, env: &Env, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { let props = comp.props(Internal::new()); - self.room = self.mount_room(props, ui, id, at, scx.tokens); - let env = Env::of(ui); - self.given = self.given_axes(props, &env, at); + self.room = self.mount_room(props, (ui, env), id, at, scx.tokens); + self.given = self.given_axes(props, env, at); self.fixed_height = self.fixed_height(props, at); - self.passes = self.passes_width(props, &env, at); - self.held = self.held(props, &env); + self.passes = self.passes_width(props, env, at); + self.held = self.held(props, env); self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); - self.in_column = label::in_column(ui); + self.in_column = label::in_column(ui, env); self.egui_cell = env.egui_cell; - self.given.1 |= self.given_room(props, &env, at, ui.ctx(), id); + self.given.1 |= self.given_room(props, env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; let room = self.room.x - 2.0 * self.pads(props, scx.tokens).x; @@ -382,10 +381,10 @@ impl ShapeHooks for BodyHooks<'_> { self.measured_footer = props.footer.as_ref().and_then(|_| took(sub(id, "footer"))).unwrap_or(Vec2::ZERO); self.measured_end = props.end.as_ref().and_then(|_| took(sub(id, "end"))); self.measured_controls = took(sub(id, "controls")); - self.extent(comp, at.ui, at.at, id, at.scx) + self.extent(comp, at.ui, at.place, at.at, id, at.scx) } - fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { + fn sized(&self, comp: &C, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { let props = comp.props(Internal::new()); match self.sizing(props) { Sizing::Fill => { @@ -393,32 +392,32 @@ impl ShapeHooks for BodyHooks<'_> { // The available rect, not at least it: a fill child that took the whole room in an earlier pass (a // content-sized layer offers its whole room before the footer is known) must not keep its remembered // size once the room is less. - let room = crate::layout::flow_room(ui); + let room = crate::layout::flow_room(ui, place); let (x, y) = ( - crate::layout::fill_size(ui, id, Axis::X, size.x, room.x, self.given.0), - crate::layout::fill_size(ui, id, Axis::Y, size.y, room.y, self.given.1), + crate::layout::fill_size(ui, place, id, Axis::X, size.x, room.x, self.given.0), + crate::layout::fill_size(ui, place, id, Axis::Y, size.y, room.y, self.given.1), ); Vec2::new(x, y) } Sizing::FillWidth => { - let room = crate::layout::flow_fill_room(ui).x; + let room = crate::layout::flow_fill_room(ui, place).x; // A fill-width child held in a content column is not given the width (it never sets the column's // width) but shows across the column. It widens to the column it is held in, never past it, and only // where it is shown: its measure never sets the column's width. - let held = !self.given.0 && self.held(props, &Env::of(ui)); - let room = if held { room.min(crate::layout::flow_room(ui).x) } else { room }; + let held = !self.given.0 && self.held(props, place); + let room = if held { room.min(crate::layout::flow_room(ui, place).x) } else { room }; // Given the height of the row line it sits on, it fills that line (`given_axes`). let height = if self.given.1 { - crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, crate::layout::flow_room(ui).y, true) + crate::layout::fill_size(ui, place, id, craft_behavior::Axis::Y, size.y, crate::layout::flow_room(ui, place).y, true) } else { size.y }; - Vec2::new(crate::layout::fill_size(ui, id, craft_behavior::Axis::X, size.x, room, self.given.0 || held), height) + Vec2::new(crate::layout::fill_size(ui, place, id, craft_behavior::Axis::X, size.x, room, self.given.0 || held), height) } // Its content's width, and the height as `Fill` takes it. Sizing::FillHeight => { - let room = crate::layout::flow_room(ui); - Vec2::new(size.x, crate::layout::fill_size(ui, id, craft_behavior::Axis::Y, size.y, room.y, self.given.1)) + let room = crate::layout::flow_room(ui, place); + Vec2::new(size.x, crate::layout::fill_size(ui, place, id, craft_behavior::Axis::Y, size.y, room.y, self.given.1)) } Sizing::Content => size, } @@ -523,7 +522,7 @@ impl ShapeHooks for BodyHooks<'_> { .vertical(vertical) .horizontal(horizontal) .scrolls(true) - .gated(crate::runtime::env::Env::of(pcx.ui).wheel == crate::runtime::env::WheelScope::Gated) + .gated(pcx.measure.scope.wheel == crate::runtime::env::WheelScope::Gated) .notch(notch) .room(WheelRoom::new(positive, negative)), ); @@ -1892,7 +1891,7 @@ impl BodyHooks<'_> { _ => false, }; if !flows && at.ui.is_sizing_pass() { - return Err(self.extent(comp, at.ui, at.at, cx.core.id, at.scx)); + return Err(self.extent(comp, at.ui, at.place, at.at, cx.core.id, at.scx)); } let id = cx.core.id; let open = if self.open_given { self.open } else { open_now(comp, &mut *cx.core.memory, id, props) }; @@ -1925,7 +1924,7 @@ impl BodyHooks<'_> { self.least_width = least_of(&at.env.tokens, props.least_width); self.room = match at.width { Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)), - None => self.mount_room(&props, at.ui, id, at.at, at.scx.tokens), + None => self.mount_room(&props, (at.ui, at.place), id, at.at, at.scx.tokens), }; self.given = self.given_axes(&props, at.env, at.at); self.given.1 |= self.given_room(&props, at.env, at.at, at.ui.ctx(), id); @@ -1937,27 +1936,28 @@ impl BodyHooks<'_> { if let Some(ColumnSweep::Column(_, width)) = at.env.column.filter(|_| self.across && at.width.is_none()) { self.room.x = width; } - self.in_column = label::in_column(at.ui); + self.in_column = label::in_column(at.ui, at.place); self.egui_cell = at.env.egui_cell; // A body that fills the main axis of the body it sits in is measured and shown at its share of it. The first // sweep of that body's measuring run only counts it: its contents run in the second sweep, at the share. let (x, y) = (craft_behavior::Axis::X, craft_behavior::Axis::Y); // Along an axis the flow does not bound it fills nothing (`sized`): it measures its content there. In a `Stack` // body that scrolls along y it shares what the view shows. - let bounded = crate::layout::flow_room(at.ui); - let scrolled_y = !bounded.y.is_finite() && crate::layout::shares_y(at.ui) && crate::layout::view_room(at.ui, y).is_some(); + let bounded = crate::layout::flow_room(at.ui, at.place); + let scrolled_y = !bounded.y.is_finite() && crate::layout::shares_y(at.place) && crate::layout::view_room(at.ui, at.place, y).is_some(); let (fills_x, fills_y) = (self.given.0 && bounded.x.is_finite(), self.given.1 && (bounded.y.is_finite() || scrolled_y)); if flows && at.ui.is_sizing_pass() - && ((fills_x && crate::layout::counting_fills(at.ui, x)) || (fills_y && crate::layout::counting_fills(at.ui, y))) + && ((fills_x && crate::layout::counting_fills(at.ui.ctx(), at.place, x)) + || (fills_y && crate::layout::counting_fills(at.ui.ctx(), at.place, y))) { return Err(Vec2::ZERO); } - if let Some(share) = crate::layout::fill_share(at.ui, x).filter(|_| flows && self.given.0) { + if let Some(share) = crate::layout::fill_share(at.place, x).filter(|_| flows && self.given.0) { self.room.x = share; } let mut scrolled_share = false; - if let Some(share) = crate::layout::fill_share(at.ui, y).filter(|_| flows && self.given.1) { + if let Some(share) = crate::layout::fill_share(at.place, y).filter(|_| flows && self.given.1) { self.room.y = share; scrolled_share = scrolled_y; } diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index b4d946fb53..efc844dd43 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -305,13 +305,13 @@ impl<'b> BodyHooks<'b> { /// The room the mount offers: a layer's room, unless the host gives it a rect of its own size, else the rect the /// container is shown at, else the room of the flow. `tokens` are the container's own, as its token scope sets them: - /// the layer keeps the inset from the screen edge the host places it with. - pub(super) fn mount_room(&self, props: &ContainerProps, ui: &Ui, id: Id, at: ShowAt, tokens: &UiTokens) -> Vec2 { + /// the layer keeps the inset from the screen edge the host places it with. `env` is the env `ui`'s children are + /// placed under. + pub(super) fn mount_room(&self, props: &ContainerProps, (ui, env): (&Ui, &Env), id: Id, at: ShowAt, tokens: &UiTokens) -> Vec2 { match (overlay_of(props), self.fixed) { (Some(overlay), false) => { - let env = Env::of(ui); - let overlay = &overlay.opened_in(&env); - let room = Self::layer_room(ui.ctx(), &env, overlay).size(); + let overlay = &overlay.opened_in(env); + let room = Self::layer_room(ui.ctx(), env, overlay).size(); // An anchored layer's body runs in the room the anchor leaves on the side it takes, as the host // offers it: a body taller than that scrolls instead of covering the anchor. let ctx = ui.ctx(); @@ -319,7 +319,7 @@ impl<'b> BodyHooks<'b> { let rtl = env.layer_direction().is_rtl(); match crate::contract::overlay::measuring_room( ctx, - &env, + env, id, overlay, own, @@ -336,20 +336,20 @@ impl<'b> BodyHooks<'b> { (Mount::Pane(ShellPane { at: Some(rect), content_extent: true, .. }), _) => rect.size(), (_, ShowAt::Rect(rect)) => rect.size(), (_, ShowAt::Flow) => { - let room = crate::layout::flow_room(ui); + let room = crate::layout::flow_room(ui, env); // A row that shrinks its children to fit gives a body among them a width: it measures and shows // in that room. A body that fills a bounded row takes the rest of it instead. let fills = !self.sizing(props).content_width() && room.x.is_finite(); - let cap = match Env::of(ui).shrink { + let cap = match env.shrink { Some(crate::layout::Shrink::Apply(row)) if !fills => crate::layout::shrink_cap(ui.ctx(), row, id).map(|cap| cap.width), _ => None, }; // A body that fills the height of a `Stack` body that scrolls along y takes a share of what the view // shows (`layout::view_room`): it runs in that room, bounded like a body in a room that does not scroll. - let shares_view = !room.y.is_finite() && self.sizing(props).fills_height() && crate::layout::shares_y(ui); - let y = shares_view.then(|| crate::layout::view_room(ui, craft_behavior::Axis::Y)).flatten().unwrap_or(room.y); + let shares_view = !room.y.is_finite() && self.sizing(props).fills_height() && crate::layout::shares_y(env); + let y = shares_view.then(|| crate::layout::view_room(ui, env, craft_behavior::Axis::Y)).flatten().unwrap_or(room.y); // A body that fills the height of the row line it stands on runs in that line. - let y = self.line_height(props, &Env::of(ui), at).unwrap_or(y); + let y = self.line_height(props, env, at).unwrap_or(y); Vec2::new(cap.map_or(room.x, |cap| room.x.min(cap)), props.room_height.unwrap_or(y)) } }, diff --git a/crates/ui-contract/src/contract/cx/body.rs b/crates/ui-contract/src/contract/cx/body.rs index 4705042554..f776e87dd4 100644 --- a/crates/ui-contract/src/contract/cx/body.rs +++ b/crates/ui-contract/src/contract/cx/body.rs @@ -2,7 +2,7 @@ use crate::contract::label; use crate::contract::{Container, Resolved, Show, SideLabel}; -use crate::runtime::env::{EnvView, Label, Message}; +use crate::runtime::env::{Env, EnvView, Label, Message}; use crate::runtime::memory::{MemoryStage, StageAccess, sealed}; use crate::runtime::overlay::CloseReason; use egui::{Id, Rect, Ui}; @@ -132,7 +132,8 @@ impl<'a> BodyCx<'a> { /// the placement measured: the child (plus the label line when the label stacks), and the label when it is taller. /// `ui` is the body's `Ui`; `key` makes the child's id. pub fn labelled(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C) -> C::Output { - label::flow_leaf(ui, (self.id.with(key), self.resolved.id), (self.resolved.enabled, self.resolved.size), label, side, child, None) + let env = Env::of(ui); + label::flow_leaf((ui, env), (self.id.with(key), self.resolved.id), (self.resolved.enabled, self.resolved.size), label, side, child, None) } /// `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). The @@ -160,14 +161,16 @@ impl<'a> BodyCx<'a> { Some(&super::Under::new(under.0, under.1)), ); let show = Box::new(move |ui: &mut Ui, rect: Rect| { + let place = Env::of(ui); let _ = crate::contract::run::show_leaf( &mut Some(crate::contract::Props::id(content, content_id)), ui, - crate::contract::run::ShowAt::Rect(rect), + (crate::contract::run::ShowAt::Rect(rect), place), None, ); }); - label::flow_leaf(ui, (id, self.resolved.id), under, label, side, child, Some(label::Trailing { size, show })) + let env = Env::of(ui); + label::flow_leaf((ui, env), (id, self.resolved.id), under, label, side, child, Some(label::Trailing { size, show })) } } diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index 338156873e..3181fc29fd 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -16,6 +16,9 @@ use std::hash::Hash; pub struct MeasureCx<'a, C: Component> { /// What the inherited context holds that component code may read. pub env: EnvView<'a>, + /// The env `env` views: the env installed for `ui`, in the component's own scope, so its layout facts are those of + /// the place `ui`'s children are shown in. + pub(crate) scope: &'a crate::runtime::env::Env, /// The component's cached style. pub style: &'a C::Style, /// `Common` after step 1. @@ -73,7 +76,7 @@ impl MeasureCx<'_, C> { // The column is an input of this measure call besides its room (step 5 opens the call), and of the calls // around it that measure it. let ctx = self.ui.ctx(); - let width = crate::layout::row_alone_room(self.ui).unwrap_or_else(|| crate::layout::flow_room(self.ui).x); + let width = crate::layout::row_alone_room(self.scope).unwrap_or_else(|| crate::layout::flow_room(self.ui, self.scope).x); let width = layout_memory::read_input(ctx, layout_memory::calls_from(ctx), self.id.with("column_room"), width); Some(width).filter(|width| width.is_finite()) }); diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index 22b9e01cb6..e226a33a5e 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -187,13 +187,13 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { Self::props_pad(comp, tokens) } - fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { + fn sized(&self, comp: &C, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { let sizing = comp.props(Internal::new()).sizing; // A collection that measured its width from its content takes that width; the column it sits in holds it. let width = if self.content_sized(comp) || self.from_content.0 { size.x } else { - crate::layout::body::fill_size(ui, id, Axis::X, size.x, self.room.x, true) + crate::layout::body::fill_size(ui, place, id, Axis::X, size.x, self.room.x, true) }; let height = match (self.scrolls && self.room.y.is_finite(), sizing) { (true, Sizing::Fill | Sizing::FillHeight) if !self.from_content.1 && !self.capped => self.room.y, @@ -1133,12 +1133,11 @@ impl ItemsHooks<'_, '_, C> { /// Step 5 in both runs: what the rows take in the room `measuring` gives. The auto rows in view are measured /// first (`measure_ahead`), so the collection takes its size, and places its rows, by this pass's measure. fn items_extent(&mut self, comp: &C, measuring: &Measuring<'_, '_>, id: Id) -> Vec2 { - let (ui, scx) = (measuring.ui, measuring.scx); + let (ui, env, scx) = (measuring.ui, measuring.place, measuring.scx); let room = match measuring.at { ShowAt::Rect(rect) => rect.size(), - ShowAt::Flow => crate::layout::flow_room(ui), + ShowAt::Flow => crate::layout::flow_room(ui, env), }; - let env = Env::of(ui); // The layout reads the component's own motion memory (`StyleCx::exiting`): an item leaving its source keeps // its room until its exit ends. let scx = &scx.measured_by(ui).owned_by(id, env.motion); @@ -1148,7 +1147,7 @@ impl ItemsHooks<'_, '_, C> { // Where the enclosing body does not give the width, the collection takes its width from its content, whether // it fills or fills the width, as a container does. Held in a content-sized column it measures so, and shows // across the width the column settles on. - let held = env.content_column || crate::layout::in_grid_content_column(ui); + let held = env.content_column || crate::layout::in_grid_content_column(ui.ctx(), env); self.from_content = (!env.gives_width() && (crate::runtime::measure::active(ui.ctx()) || !held), env.content.1); self.header.measure(scx); self.header.read_content(ui.ctx(), id); @@ -1157,7 +1156,7 @@ impl ItemsHooks<'_, '_, C> { // Under a body that does not give the width, the measuring run lays the rows out at the width the collection // asks for, so the height it reports is the one it has at that width (a grid's rows at its columns). let from_content = self.from_content.0 && !self.content_sized(comp); - let asked = (from_content && !self.source.is_empty()).then(|| self.width_from_content(comp, ui, id, room, item, scx)); + let asked = (from_content && !self.source.is_empty()).then(|| self.width_from_content(comp, (ui, env), id, room, item, scx)); let width = match (bounded, self.content_sized(comp)) { (true, false) => asked.unwrap_or(room.x), // No rows: the empty state has no ideal width, so it takes the room, or none where the room is unbounded. @@ -1220,14 +1219,15 @@ impl ItemsHooks<'_, '_, C> { let rows = self.content.y.max(empty).max(floor); let height = cap.map_or(rows, |cap| rows.min(cap)) + self.header.height; if !(self.scrolls && room.y.is_finite()) { - let wide = if from_content { asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) } else { self.content.x }; + let wide = + if from_content { asked.unwrap_or_else(|| self.width_from_content(comp, (ui, env), id, room, item, scx)) } else { self.content.x }; return Vec2::new(wide, height); } // A scrolling collection in a bounded room: `Content` takes its rows up to the room, `Fill` the room. let wide = if self.content_sized(comp) { self.content.x } else if from_content { - asked.unwrap_or_else(|| self.width_from_content(comp, ui, id, room, item, scx)) + asked.unwrap_or_else(|| self.width_from_content(comp, (ui, env), id, room, item, scx)) } else { 0.0 }; diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index d6f44a3e69..cd75ee16dc 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -40,17 +40,17 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { /// sized from its content: the header's least width, else its largest row's, at least the width it asks for /// (`Collection::ideal_width`), up to `room`. The column it sits in holds it at that width and shows it across /// the width the column settles on. - pub(super) fn width_from_content(&mut self, comp: &C, ui: &Ui, id: Id, room: Vec2, item: Option, scx: &StyleCx<'_>) -> f32 { - let rows = if self.header.has_columns() { self.header.least_width() } else { self.largest_in(comp, ui, id, room).x }; + pub(super) fn width_from_content(&mut self, comp: &C, at: (&Ui, &Env), id: Id, room: Vec2, item: Option, scx: &StyleCx<'_>) -> f32 { + let rows = if self.header.has_columns() { self.header.least_width() } else { self.largest_in(comp, at, id, room).x }; rows.max(comp.ideal_width(item, self.source.len(), scx)).min(room.x) } /// The largest ideal size of the rows in this pass, the sum of their ideal widths, and the widest cell each column's /// items reported: each row is built as `content` builds it, with its column cells at the widths the header /// resolves with no room to share (a fixed or toggle column at its own width), and measured without allocating. - fn largest_row(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { + fn largest_row(&mut self, comp: &C, (ui, env): (&Ui, &Env), id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { let ctx = ui.ctx().clone(); - crate::contract::steps::measuring(&ctx, || self.largest_row_in(comp, ui, id)) + crate::contract::steps::measuring(&ctx, || self.largest_row_in(comp, (ui, env), id)) } /// Builds the rows once to measure the largest and records it under `sub(id, "largest")` for `extent`, when this @@ -58,7 +58,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { pub(super) fn record_largest(&mut self, comp: &C, at: &Measuring<'_, '_>, id: Id) { let room = match at.at { ShowAt::Rect(rect) => rect.size(), - ShowAt::Flow => crate::layout::flow_room(at.ui), + ShowAt::Flow => crate::layout::flow_room(at.ui, at.place), }; let room = Self::inner_room(comp, &at.env.tokens, room); if self.source.is_empty() || (room.x.is_finite() && !self.content_sized(comp) && !comp.measures_items() && !self.header.has_content_columns()) @@ -66,14 +66,15 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { return; } self.header.measure(at.scx); - self.largest_in(comp, at.ui, id, room); + self.largest_in(comp, (at.ui, at.place), id, room); } /// The largest row in the room `room`: what a record of this pass under `sub(id, "largest")` found when it serves /// the room (`Measured::serves`), else what the measure kept from an earlier pass gives while the items' inputs /// hold, else the rows built and measured now, recorded there and kept. The widest cell of each `Content` column, /// or its header label when wider, is recorded with it (`header::content_id`). The caller measures the header first. - pub(super) fn largest_in(&mut self, comp: &C, ui: &Ui, id: Id, room: Vec2) -> Vec2 { + /// `env` is the env `ui`'s children are placed under. + pub(super) fn largest_in(&mut self, comp: &C, (ui, env): (&Ui, &Env), id: Id, room: Vec2) -> Vec2 { let ctx = ui.ctx().clone(); let key = sub(id, "largest"); let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); @@ -85,7 +86,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { return found.took; } // A kept measure serves only the outermost measuring run, which this opens when none is open. - let inputs = self.items_inputs(comp, ui, room); + let inputs = self.items_inputs(comp, env, room); if let Some(inputs) = &inputs && crate::runtime::measure::measuring(&ctx, || layout_memory::kept_serves(&ctx, key, inputs)) && let Some(found) = found(&ctx) @@ -98,10 +99,9 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { if inputs.is_some() { layout_memory::begin_measure(&ctx, key); } - let (largest, run, cells) = self.largest_row(comp, ui, id); + let (largest, run, cells) = self.largest_row(comp, (ui, env), id); layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(room, largest)); layout_memory::emit_record(&ctx, run_id(id), layout_memory::Measured::new(room, Vec2::new(run, 0.0))); - let env = Env::of(ui); let content: Vec<(usize, craft_behavior::ColumnKey)> = self.header.content_columns().map(|(at, key)| (at, key.clone())).collect(); for (at, column) in content { let widest = cells.iter().find(|(held, _)| *held == column).map_or(0.0, |(_, width)| *width); @@ -118,14 +118,14 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { /// What the items' measure reads besides the rows' content: the room, the item count, the env and what `dress` /// reads of the collection. `None` when the source declares no content version (rows stamp or revision): the rows /// may change unseen, so every pass measures them. - fn items_inputs(&self, comp: &C, ui: &Ui, room: Vec2) -> Option { + fn items_inputs(&self, comp: &C, env: &Env, room: Vec2) -> Option { let content = (comp.items().rows_stamp, self.source.revision()); (content.0.is_some() || content.1.is_some()).then(|| ItemsInputs { room, count: self.source.len(), content, dress: comp.dress_inputs(), - env: EnvFacts::of(&Env::of(ui)), + env: EnvFacts::of(env), }) } @@ -138,9 +138,8 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { .map_or(0.0, |found| found.took.x) } - fn largest_row_in(&mut self, comp: &C, ui: &Ui, id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { + fn largest_row_in(&mut self, comp: &C, (ui, env): (&Ui, &Env), id: Id) -> (Vec2, f32, Vec<(craft_behavior::ColumnKey, f32)>) { let ctx = ui.ctx().clone(); - let env = Env::of(ui); let mut memory = MemoryStage::open_peek(&ctx, id); let cells: Vec<(craft_behavior::ColumnKey, Rect)> = self.header.columns(0.0).into_iter().map(|(key, width)| (key, Rect::from_min_size(Pos2::ZERO, Vec2::new(width, 0.0)))).collect(); @@ -152,7 +151,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { continue; } let row = RowMeasure::new(at, Rect::ZERO, cells.clone()); - let (size, cells) = self.measure_row(comp, ui, (id, env.view(), &env), &mut memory, row, |measure, _, _| measure(Proposal::Ideal)); + let (size, cells) = self.measure_row(comp, ui, (id, env.view(), env), &mut memory, row, |measure, _, _| measure(Proposal::Ideal)); largest = largest.max(size); run += size.x; for (column, width) in cells { diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index 77fb0a901f..91f25fe60a 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -125,7 +125,7 @@ impl LeafPlaced { /// and calls `LeafPlaced::finish`. pub(crate) fn decide_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided { // Read before the child measures: nothing it does there may count as a child placed in flow. - let in_column = in_column(ui); + let in_column = in_column(ui, env); // An egui grid's cell is as wide as the row takes, and the control shows at its ideal width there. let proposal = if at.egui_cell { craft_behavior::Proposal::Ideal } else { craft_behavior::Proposal::Min }; let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), proposal, Some(at.under)).x; @@ -335,13 +335,13 @@ fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: /// Whether a row shown in `flow` is a row of a vertical flow, not a member of a row's line. The first child of an /// unwrapped row that is itself a row of a vertical flow (`Scoped::column_row`) starts where that flow's rows start, -/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls. -pub(crate) fn in_column(flow: &Ui) -> bool { +/// so it counts as one of them: a check box that starts a row of a form lines up with the form's controls. `env` is the +/// env `flow`'s children are placed under. +pub(crate) fn in_column(flow: &Ui, env: &Env) -> bool { if !flow.layout().is_horizontal() { return true; } - let env = Env::of(flow); - env.column_row && crate::layout::at_flow_start(flow.ctx(), &env) + env.column_row && crate::layout::at_flow_start(flow.ctx(), env) } /// A control with its label after it that the label step moved into the control column (its `control` starts past @@ -361,7 +361,7 @@ pub(crate) fn report_after_reach(ctx: &egui::Context, env: &Env, side: &SideLabe /// child's id, `owner` the component whose eviction takes the label scope's facts, and `under` the enabled state and /// size the child inherits. `trailing` is content shown inside the label, after its text. pub(crate) fn flow_leaf( - ui: &mut Ui, + (ui, env): (&mut Ui, Env), (id, owner): (Id, Id), under: (bool, craft_theme::ControlSize), label: Label, @@ -371,28 +371,26 @@ pub(crate) fn flow_leaf( ) -> C::Output { // In a grid the row is the grid's next cell, read under its column's group, as `run` shows any other cell: the // room before the row is the whole grid's, and a row placed there would stand under the one before it. - match crate::layout::grid_cell(ui) { - Some((grid, column, sized)) => { - let ctx = ui.ctx().clone(); - crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || flow_leaf_row(ui, (id, owner), under, label, side, child, trailing, true)) - } - None => flow_leaf_row(ui, (id, owner), under, label, side, child, trailing, false), + let ctx = ui.ctx().clone(); + match crate::layout::grid_cell(&ctx, &env) { + Some((grid, column, sized)) => crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || { + flow_leaf_row((ui, env), (id, owner), under, label, side, child, (trailing, true)) + }), + None => flow_leaf_row((ui, env), (id, owner), under, label, side, child, (trailing, false)), } } -/// `flow_leaf` for a row in the flow of `ui`; `in_cell`: the row is the next cell of the grid around it. -#[expect(clippy::too_many_arguments, reason = "flow_leaf's arguments and whether its row is a grid cell")] +/// `flow_leaf` for a row in the flow of `ui`, whose children are placed under `env`; `in_cell`: the row is the next +/// cell of the grid around it. fn flow_leaf_row( - ui: &mut Ui, + (ui, env): (&mut Ui, Env), (id, owner): (Id, Id), under: (bool, craft_theme::ControlSize), label: Label, side: SideLabel, child: C, - trailing: Option>, - in_cell: bool, + (trailing, in_cell): (Option>, bool), ) -> C::Output { - let env = Env::of(ui); let mut child = child; let under = leaf_under(&env, &side, &child, under); let ideal = crate::contract::run::measure_under(&mut child, &*ui, Some(id), craft_behavior::Proposal::Ideal, Some(&under)); @@ -401,7 +399,7 @@ fn flow_leaf_row( } // A grid's cell; a probe offers it unbounded room, and the row then spans the grid's flow so it has an end edge. let flow = ui.available_rect_before_wrap(); - let avail = match crate::layout::flow_region(ui) { + let avail = match crate::layout::flow_region(ui, &env) { region if in_cell && region.width().is_finite() => region, region if in_cell => Rect::from_min_size(region.min, Vec2::new(flow.width(), region.height())), _ => flow, @@ -438,7 +436,8 @@ fn flow_leaf_row( // below it. let height = (decided_control.bottom().max(decided_label.bottom()) - row.top()).max(ideal.y); let first = decided_control.top() - row.top() + ideal.y / 2.0; - let took = crate::layout::place_in_cell(ui, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true }); + let took = + crate::layout::place_in_cell(ui, &env, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true }); let placed = show_leaf(ui, &env, &at, decided, took.top() - row.top(), trailing); let control = span(placed.control); // A control beside its label in a content-sized column reports how far it reaches past the label column, so @@ -451,10 +450,8 @@ fn flow_leaf_row( report_after_reach(ui.ctx(), &env, &side, (avail, control), extent); } // The child runs under the inside label its measures saw. - let installed = under - .inside - .clone() - .map(|inside| Env::install_for(ui, env.derive_local(|scoped| scoped.inside_label = Some(inside as crate::runtime::env::Held)))); + let inside = under.inside.clone().map(|inside| env.derive_local(|scoped| scoped.inside_label = Some(inside as crate::runtime::env::Held))); + let installed = inside.clone().map(|inside| Env::install_for(ui, inside)); // The control and its label are one member of a bar's line: judged together, and hidden together, as the label // step hid the label. let shown_clip = ui.clip_rect(); @@ -462,8 +459,13 @@ fn flow_leaf_row( if cut { ui.set_clip_rect(Rect::NOTHING); } - let output = - crate::contract::run::show_leaf(&mut Some(crate::contract::Props::id(child, id)), ui, crate::contract::run::ShowAt::Rect(control), None); + let place = inside.unwrap_or_else(|| env.clone()); + let output = crate::contract::run::show_leaf( + &mut Some(crate::contract::Props::id(child, id)), + ui, + (crate::contract::run::ShowAt::Rect(control), place), + None, + ); if cut { ui.set_clip_rect(shown_clip); } @@ -515,7 +517,7 @@ pub(crate) fn show_leaf_in_flow(mut child: C, ui: &mut Ui) -> C::Output let named_by_scope = env.arena.is_none() && scope::in_label(ui.ctx()); let shows = C::LABELLED_AFTER && child.shows_label() && child.common(crate::contract::Internal::new()).label != Label::Empty && !named_by_scope; if !shows { - return crate::contract::run::show_leaf(&mut Some(child), ui, crate::contract::run::ShowAt::Flow, None); + return crate::contract::run::show_leaf(&mut Some(child), ui, (crate::contract::run::ShowAt::Flow, env), None); } let label = std::mem::take(&mut child.common_mut(crate::contract::Internal::new()).label); let facts = crate::contract::run::TypeFacts::of::(); @@ -525,5 +527,6 @@ pub(crate) fn show_leaf_in_flow(mut child: C, ui: &mut Ui) -> C::Output Some(detail) => side.detail(detail), None => side, }; - flow_leaf(ui, (id, id), (env.enabled, env.size), label, side, child, None) + let under = (env.enabled, env.size); + flow_leaf((ui, env), (id, id), under, label, side, child, None) } diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 328fb86710..6d3552d61e 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -62,27 +62,29 @@ impl Lazy { /// Runs `add` in a child `Ui` placed in flow in `ui`, or takes the remembered extent there; `None` when it did not /// run. pub fn show(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option { - match self.run_keyed(ui, "Lazy", Key::None, |ui, _| add(ui)) { + let env = Env::of(ui); + match self.run_keyed((ui, env), "Lazy", Key::None, |ui, _| add(ui)) { Shown::Ran(out) => Some(out), Shown::Replayed(..) | Shown::OutOfView => None, } } - /// The id of the child in `ui`: under its scroll area, or under `ui`'s scope outside every scroll area. - pub(super) fn id(&self, ui: &Ui) -> egui::Id { - match Env::of(ui).view().lazy_view() { + /// The id of the child in `ui`, whose children are placed under `env`: under its scroll area, or under `ui`'s scope + /// outside every scroll area. + pub(super) fn id(&self, ui: &Ui, env: &Env) -> egui::Id { + match env.view().lazy_view() { Some(view) => sub(view.owner, ("lazy", self.key)), None => sub(ui.scope_id(), ("lazy", self.key)), } } /// The one runner of a `Lazy` child and a memoized view (`MemoView`), named `name` in the count trials: runs `add`, - /// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view. - pub(super) fn run_keyed(self, ui: &mut Ui, name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown { + /// replays the kept run of a memoized view keyed `key`, or takes the extent of a child out of view. `env` is the + /// env installed for `ui`. + pub(super) fn run_keyed(self, (ui, env): (&mut Ui, Env), name: &'static str, key: Key, add: impl FnOnce(&mut Ui, &mut Run) -> R) -> Shown { let ctx = ui.ctx().clone(); - let env = Env::of(ui); let view = env.view().lazy_view(); - let id = self.id(ui); + let id = self.id(ui, &env); let rtl = ui.layout().prefer_right_to_left(); let memo = matches!(key, Key::Memo(_)); let sizing = ui.is_sizing_pass(); @@ -94,7 +96,7 @@ impl Lazy { let share = env .shares() .filter(|axis| memo && real && lazy::fills(&ctx, id, sizing) == Some(*axis)) - .and_then(|axis| crate::layout::fill_share(ui, axis).map(|share| (axis, share))); + .and_then(|axis| crate::layout::fill_share(&env, axis).map(|share| (axis, share))); // A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a @@ -106,10 +108,10 @@ impl Lazy { _ => None, }; let available = match share { - Some((axis, share)) => share_of(flow_region(ui), rtl, axis, share), - None => cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)), + Some((axis, share)) => share_of(flow_region(ui, &env), rtl, axis, share), + None => cap.map_or_else(|| flow_region(ui, &env), |cap| at_most(flow_region(ui, &env), rtl, cap.width)), }; - let available = if memo { on_row_line(ui, id, available) } else { available }; + let available = if memo { on_row_line(ui, &env, id, available) } else { available }; let owner = view.map(|view| view.owner); // A run around this one that is replayed later keeps the child's entry. replay::journal(&ctx, || (owner, id), |ctx, &(owner, id)| lazy::keep(ctx, owner, id)); @@ -122,7 +124,7 @@ impl Lazy { crate::contract::queue_child_reveal(&ctx, view.owner, id); } if let Decision::Skip(size) = lazy::decide(&ctx, id, &view, at, sizing, estimate) { - let (took, _) = take_in_flow(ui, size); + let (took, _) = take_in_flow(ui, &env, size); if real { layout_memory::backstop(&ctx, id, size); lazy::replay(&ctx, id); @@ -164,7 +166,7 @@ impl Lazy { // A real replay is where the run's content went, moved with the room. let rect = if real { ran_at } else { Rect::from_min_size(at_start(available, rtl, size), size) }; let fills = if memo && !real { lazy::fills(&ctx, id, sizing) } else { None }; - let took = place_unit(ui, (shrink, fills), id, rect, rtl); + let took = place_unit(ui, &env, (shrink, fills), id, rect, rtl); let kept = if real { layout_memory::backstop(&ctx, id, size); let kept = lazy::replay_settled(&ctx, id, &shift); @@ -200,14 +202,14 @@ impl Lazy { // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. The // content runs in the env of `ui`, as the direct children of the body around it: a plain `Lazy` keeps their // line, cells and shrink step, and a memoized view starts its own room on top of it. - let out = layout_memory::boundary(&ctx, false, || Env::run_in(&mut child, env, |child| add(child, &mut run))); + let out = layout_memory::boundary(&ctx, false, || Env::run_in(&mut child, env.clone(), |child| add(child, &mut run))); let rect = child.min_rect(); // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); let fills = if memo { crate::layout::take_view_fill(&ctx, id) } else { None }; let record = run.recording.then(|| replay::close(&ctx, place.layer)); if let Some(shift) = audited { - return place_audit_run(ui, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run); + return place_audit_run(ui, &env, Audited { name, id, view, rect, record: record.as_ref(), shift }, out, &run); } #[cfg(feature = "testing")] if let Some(record) = &record @@ -219,9 +221,9 @@ impl Lazy { layout_memory::backstop(&ctx, id, rect.size()); } if memo { - place_unit(ui, (shrink, fills.filter(|_| !real)), id, rect, rtl); + place_unit(ui, &env, (shrink, fills.filter(|_| !real)), id, rect, rtl); } else { - crate::layout::close_flow_start_in(ui); + crate::layout::close_flow_start(&ctx, &env); alloc::advance_past(ui, rect); } if view.is_some() || memo { @@ -251,11 +253,11 @@ impl Lazy { /// Places the audit run of a view that would have replayed, as a replay places it, and compares the run with the kept /// run replayed at the place `shift` names (`runtime::audit`). It keeps the kept run: every later pass compares with /// what a replay adds. -fn place_audit_run(ui: &mut Ui, audited: Audited<'_>, out: R, run: &Run) -> Shown { +fn place_audit_run(ui: &mut Ui, env: &Env, audited: Audited<'_>, out: R, run: &Run) -> Shown { let Audited { name, id, view, rect, record, shift } = audited; let ctx = ui.ctx().clone(); layout_memory::backstop(&ctx, id, rect.size()); - place_view(ui, rect); + place_view(ui, env, rect); if let Some(view) = view { lazy::place(&ctx, &view, id, rect); } @@ -334,11 +336,10 @@ fn share_of(region: Rect, rtl: bool, axis: Axis, share: f32) -> Rect { /// Any other view reports its extent to the shrinking row around it: what it takes, in the row's counting sweep, and /// its least, in the sweep that asks the row's body units for theirs. Like a body unit, it narrows from what it takes /// in no room down to what it takes with every leaf at its least. -fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: egui::Id, rect: Rect, rtl: bool) -> Rect { +fn place_unit(ui: &mut Ui, env: &Env, (shrink, fills): (Option, Option), id: egui::Id, rect: Rect, rtl: bool) -> Rect { let ctx = ui.ctx().clone(); - let env = Env::of(ui); let Some(axis) = fills.filter(|axis| env.shares() == Some(*axis)) else { - let took = place_view(ui, rect); + let took = place_view(ui, env, rect); match shrink { Some(Shrink::Count(row)) => crate::layout::report_shrink(&ctx, row, id, rect.width(), rect.width(), None, (false, None)), Some(Shrink::Least(row)) => crate::layout::report_least(&ctx, row, id, rect.width()), @@ -347,10 +348,10 @@ fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: return took; }; let content = rect.size(); - let along = match crate::layout::fill_share(ui, axis) { + let along = match crate::layout::fill_share(env, axis) { Some(share) => Some(share), - None if crate::layout::counting_fills(ui, axis) && !env.least => { - crate::layout::count_fill_view(ui); + None if crate::layout::counting_fills(&ctx, env, axis) && !env.least => { + crate::layout::count_fill_view(&ctx, env); Some(0.0) } None => None, @@ -360,7 +361,7 @@ fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: (_, Some(along)) => Vec2::new(content.x, along), (_, None) => content, }; - let took = place_view(ui, Rect::from_min_size(at_start(rect, rtl, size), size)); + let took = place_view(ui, env, Rect::from_min_size(at_start(rect, rtl, size), size)); if let (Axis::X, Some(Shrink::Count(row))) = (axis, shrink) { crate::layout::report_shrink(&ctx, row, id, size.x, size.x, Some((size.x, size.x)), (false, None)); } @@ -370,9 +371,9 @@ fn place_unit(ui: &mut Ui, (shrink, fills): (Option, Option), id: /// Places a memoized view's extent `rect` in flow in `ui`, as its run and its replay both do, and returns `rect`: in the /// `Grid` or spread `Row` body that encloses `ui` directly the view takes the next cell at its extent, as its content /// starts a layout room of its own and takes none; elsewhere the flow moves past `rect`. -fn place_view(ui: &mut Ui, rect: Rect) -> Rect { - if take_cell(ui, rect.size()).is_none() { - crate::layout::close_flow_start_in(ui); +fn place_view(ui: &mut Ui, env: &Env, rect: Rect) -> Rect { + if take_cell(ui, env, rect.size()).is_none() { + crate::layout::close_flow_start(ui.ctx(), env); alloc::advance_past(ui, rect); } rect @@ -384,8 +385,8 @@ fn place_view(ui: &mut Ui, rect: Rect) -> Rect { /// whole pixels that put the centre of the extent it took (in this pass's measuring run, else its last run) there. A /// view taller than that reaches, and a view no run showed yet, stays at the row's top. The room keeps its size, so a /// kept run replays moved with it. -fn on_row_line(ui: &Ui, id: egui::Id, room: Rect) -> Rect { - let Some(centre) = Env::of(ui).row_line.and_then(|line| line.centre) else { +fn on_row_line(ui: &Ui, env: &Env, id: egui::Id, room: Rect) -> Rect { + let Some(centre) = env.row_line.and_then(|line| line.centre) else { return room; }; let Some(size) = lazy::last_extent(ui.ctx(), id) else { diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index 46a1150b02..e0fb246ab9 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -124,12 +124,17 @@ impl MemoVie let MemoView { lazy, mut props, show } = self; let ctx = ui.ctx().clone(); // In the counting sweep of a shrinking row the view reports what it takes in no room, as a leaf there does. - let counting = matches!(Env::of(ui).shrink, Some(Shrink::Count(_))); - let unbounded = counting.then(|| Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.unbounded.0 = true))); let env = Env::of(ui); - let id = lazy.id(ui); + let (env, unbounded) = if matches!(env.shrink, Some(Shrink::Count(_))) { + let env = env.derive_local(|scoped| scoped.unbounded.0 = true); + let installed = Env::install_for(ui, env.clone()); + (env, Some(installed)) + } else { + (env, None) + }; + let id = lazy.id(ui, &env); let key = Self::key(&ctx, &env, &props, show); - let shown = lazy.run_keyed(ui, std::any::type_name::

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { + let shown = lazy.run_keyed((ui, env.clone()), std::any::type_name::

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how // that body sizes from its content, whether its leaves fit their room and which axis it shares among the // children that fill it (`Scoped::start_view_room`), so the view takes what its content used there, as the diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 7ac5003818..b5890342b4 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -116,6 +116,7 @@ pub use settle::SettleCx; pub use text::EDIT_MENU; pub use values::{Bind, BindCheck, BindMut, EditResponse, Hover, ItemOutput, NoValue, Outcome, Validity, ValueOf, clicked, pressed, response_of}; +use crate::runtime::env::Env; use crate::runtime::memory::sub; use crate::runtime::overlay::CloseReason; use crate::style::{ComponentStyle, Flags, StyleCx, StyleKey}; @@ -787,17 +788,20 @@ pub trait Show: Component + Meta + sealed::Show { /// Shows the component at `rect`, with no allocation. fn show_at(self, ui: &mut Ui, rect: Rect) -> Self::Output { - run::show_leaf(&mut Some(self), ui, ShowAt::Rect(rect), None) + let place = Env::of(ui); + run::show_leaf(&mut Some(self), ui, (ShowAt::Rect(rect), place), None) } /// Shows the component with rich tooltip content from the same call. fn show_with_tip(self, ui: &mut Ui, tip: impl FnOnce(&mut Ui)) -> Self::Output { - run::show_leaf(&mut Some(self), ui, ShowAt::Flow, Some(Box::new(tip))) + let place = Env::of(ui); + run::show_leaf(&mut Some(self), ui, (ShowAt::Flow, place), Some(Box::new(tip))) } /// Shows the component at `rect` with rich tooltip content. fn show_at_with_tip(self, ui: &mut Ui, rect: Rect, tip: impl FnOnce(&mut Ui)) -> Self::Output { - run::show_leaf(&mut Some(self), ui, ShowAt::Rect(rect), Some(Box::new(tip))) + let place = Env::of(ui); + run::show_leaf(&mut Some(self), ui, (ShowAt::Rect(rect), place), Some(Box::new(tip))) } /// Measures without allocating: steps 1 to 5 under the id `show` would use next. It registers no id, opens no @@ -811,12 +815,14 @@ pub trait Show: Component + Meta + sealed::Show { pub trait ShowContainer: Container + sealed::ShowContainer { /// Shows the container in the flow of `ui`. fn show(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Flow, &mut body, None) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Flow, place), &mut body, None) } /// Shows the container at `rect`, with no allocation: a frame over a split or a layer the parent places. fn show_at(self, ui: &mut Ui, rect: Rect, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), &mut body, None) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Rect(rect), place), &mut body, None) } /// Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies @@ -834,7 +840,8 @@ pub trait ShowContainer: Container + sealed::ShowContainer { /// Shows the container with rich tooltip content. fn show_with_tip(self, ui: &mut Ui, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Flow, &mut body, Some(Box::new(tip))) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Flow, place), &mut body, Some(Box::new(tip))) } /// Shows the container at `rect` with rich tooltip content. @@ -845,7 +852,8 @@ pub trait ShowContainer: Container + sealed::ShowContainer { mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui), ) -> Inner { - run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), &mut body, Some(Box::new(tip))) + let place = Env::of(ui); + run::show_container(&mut Some(self), ui, (ShowAt::Rect(rect), place), &mut body, Some(Box::new(tip))) } } diff --git a/crates/ui-contract/src/contract/pages.rs b/crates/ui-contract/src/contract/pages.rs index 5ab8b28c67..d11d5f79f7 100644 --- a/crates/ui-contract/src/contract/pages.rs +++ b/crates/ui-contract/src/contract/pages.rs @@ -41,10 +41,10 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { pub fn show(self, ui: &mut Ui, mut page: impl FnMut(&mut Ui, &K) -> R) -> R { let ctx = ui.ctx().clone(); let base = sub(ui.scope_id(), ("pages", self.salt)); - let region = flow_region(ui); - let layout = *ui.layout(); // Each page runs in the env of `ui`, as the direct children of the body around it. let env = Env::of(ui); + let region = flow_region(ui, &env); + let layout = *ui.layout(); let hidden = self.pages.iter().filter(|key| *key != self.current).fold(Vec2::ZERO, |largest, key| { let id = sub(base, hash(key)); let kept = lazy::measured(&ctx, id).map(|(size, reads)| { diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 0605417b82..a0a7b6b922 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -211,10 +211,11 @@ impl PaintUi<'_> { } None => env, }; - let installed = Env::install_for(kids, env); + let installed = Env::install_for(kids, env.clone()); // 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, || run::show_leaf(&mut Some(super::Props::id(child, id)), kids, (ShowAt::Rect(rect), env), 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 bd30301c91..b198445a7b 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -85,6 +85,8 @@ pub(crate) struct Measuring<'a, 's> { pub at: ShowAt, /// The width a `Proposal::Width` sets: the room is that wide and unbounded in height. pub width: Option, + /// The env the component's parent installed for `ui`, under which `ui`'s children are placed. + pub place: &'a Env, pub env: &'a Env, pub scx: &'a StyleCx<'s>, pub resolved: &'a Resolved<'s>, @@ -126,8 +128,9 @@ pub(crate) trait ShapeHooks { } /// The size step 6 allocates, from the measured `size`: a body that fills reads the available rect of `ui`: the - /// parent's at step 5, and the host's at step 6 when the host runs the pass in a `Ui` of its own. - fn sized(&self, _comp: &C, _ui: &Ui, _id: Id, size: Vec2) -> Vec2 { + /// parent's at step 5, and the host's at step 6 when the host runs the pass in a `Ui` of its own. `place` is the + /// env `ui`'s children are placed under. + fn sized(&self, _comp: &C, _ui: &Ui, _place: &Env, _id: Id, size: Vec2) -> Vec2 { size } @@ -210,8 +213,9 @@ pub(crate) trait ShapeHooks { 0.0 } - /// What the shape adds to the content size at step 5, before padding and `min_size`. - fn extent(&mut self, _comp: &C, _ui: &Ui, _at: ShowAt, _id: Id, _scx: &StyleCx<'_>) -> Vec2 { + /// What the shape adds to the content size at step 5, before padding and `min_size`. `place` is the env the parent + /// `ui`'s children are placed under. + fn extent(&mut self, _comp: &C, _ui: &Ui, _place: &Env, _at: ShowAt, _id: Id, _scx: &StyleCx<'_>) -> Vec2 { Vec2::ZERO } @@ -219,13 +223,13 @@ pub(crate) trait ShapeHooks { /// inputs only: a body runs its regions in an invisible sizing pass and measures what they took. The default is /// `extent`. fn measured_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Vec2 { - self.extent(comp, at.ui, at.at, cx.core.id, at.scx) + self.extent(comp, at.ui, at.place, at.at, cx.core.id, at.scx) } /// A real pass's step 5 for a body or an item shape: what the shape adds to the content size, from a measuring run /// of its contents in this pass (or the record one left in this pass). The default is `extent`. fn pass_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, _style: &C::Style, _shown: Option>>) -> Vec2 { - self.extent(comp, at.ui, at.at, at.resolved.id, at.scx) + self.extent(comp, at.ui, at.place, at.at, at.resolved.id, at.scx) } /// The width by which the shape's content wants to be wider than the size it measured to, because the room cut @@ -327,15 +331,15 @@ impl ShapeHooks for LeafHooks { (scope != crate::runtime::focus::FocusPolicy::NONE).then_some(scope) } - fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { + fn sized(&self, comp: &C, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { use craft_behavior::Axis; - let room = crate::layout::leaf_fill_room(ui); + let room = crate::layout::leaf_fill_room(ui, place); // A leaf is given an axis its enclosing body does not size from its content: there it fills, elsewhere it keeps // its measured size, so it never sets that size. - let content = Env::of(ui).content; + let content = place.content; let fill = |measured: f32, offered: f32, along: Axis| { let given = if along == Axis::X { !content.0 } else { !content.1 }; - crate::layout::fill_size(ui, id, along, measured, offered, given) + crate::layout::fill_size(ui, place, id, along, measured, offered, given) }; // The control beside an inspector's label fills the cell the label leaves, unless its caller sized it to its // content. @@ -343,7 +347,7 @@ impl ShapeHooks for LeafHooks { if sizing == Some(super::Sizing::Fill) { return Vec2::new(fill(size.x, room.x, Axis::X), fill(size.y, room.y, Axis::Y)); } - let in_cell = Env::of(ui).cell_fills && sizing != Some(super::Sizing::Content); + let in_cell = place.cell_fills && sizing != Some(super::Sizing::Content); match comp.fills().or(in_cell.then_some(Axis::X)) { Some(Axis::X) => Vec2::new(fill(size.x, room.x, Axis::X), size.y), Some(Axis::Y) => Vec2::new(size.x, fill(size.y, room.y, Axis::Y)), @@ -535,9 +539,9 @@ pub(crate) trait Erased { fn fills_width(&self) -> bool; /// How much wider than the size it measured to the shape's content wants to be (`ShapeHooks::overflow`). fn overflow(&self) -> f32; - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2; + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2; fn arena(&self) -> bool; - fn extent(&mut self, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2; + fn extent(&mut self, ui: &Ui, place: &Env, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2; fn pad(&self, tokens: &UiTokens) -> f32; fn host(&mut self, at: HostCx<'_>) -> Box; fn record(&mut self, stage: &mut MemoryStage, ctx: &Context, id: Id); @@ -598,7 +602,7 @@ pub(crate) trait ErasedPass<'a> { fn in_flow(&self) -> bool; fn regions(&self, id: Id) -> Vec<(Id, Vec2)>; fn focus(&self) -> Option; - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2; + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2; fn fills_width(&self) -> bool; fn first_line(&self, ctx: &Context, id: Id, height: f32) -> Option; fn first_is_row_line(&self) -> bool; @@ -656,6 +660,8 @@ struct Pass<'p, 'r, 'a> { p: &'p mut dyn ErasedPass<'a>, facts: &'r TypeFacts, env: &'r Env, + /// The env the parent installed for the parent `Ui`. + place: &'r Env, style: &'r dyn StyleView, resolved: &'r Resolved<'r>, trace: Trace<'r>, @@ -834,8 +840,9 @@ fn sense_root(ui: &Ui, member: Option, spec: RootS } } -/// Step 6: the rect the root takes in `ui`, and whether it is a fill-width root held at its measured width. -fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Vec2, inert: bool, rtl: bool) -> (Rect, bool) { +/// Step 6: the rect the root takes in `ui`, whose children are placed under `place`, and whether it is a fill-width +/// root held at its measured width. +fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, (at, place): (ShowAt, &Env), env: &Env, size: Vec2, inert: bool, rtl: bool) -> (Rect, bool) { let (ctx, id) = (ui.ctx().clone(), p.resolved.id); if p.dropped { return (Rect::from_min_size(ui.cursor().min, Vec2::ZERO), false); @@ -845,16 +852,16 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve // the column settles on, so it never sets that width. let held = !inert && matches!(at, ShowAt::Flow) - && ((env.content_column && p.p.fills_width()) || (crate::layout::in_grid_content_column(ui) && p.p.fills_width_only())); + && ((env.content_column && p.p.fills_width()) || (crate::layout::in_grid_content_column(&ctx, place) && p.p.fills_width_only())); let rect = if held { // The column's settled width, read before the child takes its place in it. A sizing or measuring run has no // settled width yet: there the child shows at its own size. let column = (!ui.is_sizing_pass() && !crate::runtime::measure::active(ui.ctx())) - .then(|| crate::layout::flow_room(ui).x) + .then(|| crate::layout::flow_room(ui, place).x) .filter(|width| width.is_finite()) .unwrap_or(0.0); let line = p.p.first_is_row_line(); - let flowed = steps::place(ui, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y), line }); + let flowed = steps::place(ui, place, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y), line }); // The column's first sweep learns which of its held children measured narrower than it settles on. if let Some(ColumnSweep::Count(column)) = env.column { crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Fill, flowed.width()); @@ -864,7 +871,7 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve } else { let fill = p.p.fills_width() && !p.p.fills_width_only(); let size = if inert { Vec2::ZERO } else { size }; - let placed = steps::place(ui, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }); + let placed = steps::place(ui, place, at, size, InFlow { fill, first: first(size.y), line: p.p.first_is_row_line() }); // A picture its measure held (`MeasureCx::picture_size`) reports its placed width, padding included. if let Some(ColumnSweep::Count(column)) = env.column && crate::layout::held_kind(&ctx, column, id) == Some(crate::layout::HeldKind::Picture) @@ -897,7 +904,9 @@ fn create_node(ctx: &Context, ui: &Ui, id: Id, member: bool, role: Role) -> bool fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, host_env: Option<&Env>) { let scope = enter_scope(p, ui); let env = host_env.unwrap_or(p.env); - if let Some(mut h) = sense_steps(p, ui, host_at, env) { + // A host that runs the pass in a `Ui` of its own installs the env it gives for it; else the pass runs in the parent. + let place = host_env.unwrap_or(p.place); + if let Some(mut h) = sense_steps(p, ui, (host_at, place), env) { update_steps(p, env, &h); overlay_step(p, ui, env, &h); state_steps(p, ui, env, &h); @@ -955,15 +964,15 @@ struct HostStep { /// inert component. // 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 sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, env: &Env) -> Option> { +fn sense_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, (host_at, place): (Option, &Env), env: &Env) -> Option> { let ctx = p.p.core_ref().ctx.clone(); let (id, rtl) = (p.resolved.id, p.env.direction.is_rtl()); let (resolved, inert, facts) = (p.resolved, p.inert, p.facts); // 6 place let at = host_at.unwrap_or(p.at); // A root that fills takes the room of the `Ui` its host runs it in: a pane's or a layer's own, not its parent's. - let size = if ui.scope_id() == p.parent { p.size } else { p.p.sized(ui, id, p.measured) }; - let (rect, held) = place_root(p, ui, at, env, size, inert, rtl); + let size = if ui.scope_id() == p.parent { p.size } else { p.p.sized(ui, place, id, p.measured) }; + let (rect, held) = place_root(p, ui, (at, place), env, size, inert, rtl); p.trace.mark(Step::Place); // What the content wants past the room counts where the root's width comes from its content: a content-sized // root, or a fill-width one held at its measured width. A root that fills the flow keeps to the room it fills, and @@ -1475,30 +1484,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) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { +/// Runs `t` in `ui`, whose children are placed under `place`: the env its parent installed for it, which every step +/// of the run reads the place from. +pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, place: Env) { if crate::runtime::pass_state::in_component_tree() { - return run_in_context(t, ui, at, tip); + return run_in_context(t, ui, at, tip, place); } let ctx = ui.ctx().clone(); - crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip)); + crate::runtime::pass_state::with_component_tree(&ctx, || run_in_context(t, ui, at, tip, place)); } -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(); +fn run_in_context(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, place: Env) { + let ctx = ui.ctx().clone(); + let cell = (matches!(at, ShowAt::Flow) && t.in_flow()).then(|| crate::layout::grid_cell(&ctx, &place)).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)); - } - None => run_steps(t, ui, at, tip), + Some((grid, column, sized)) => crate::layout::ColumnGroup::cell(&ctx, grid, column, sized, || run_steps(t, ui, at, tip, place)), + None => run_steps(t, ui, at, tip, place), } } /// Steps 1 to 17 of `run`. A component's children run inside step 5 (a body's measuring run) and inside the passes /// of steps 6 to 16, so the frames on that path keep only what the run reads after them: each step runs in its own /// function, and `run_steps` holds what steps 1 to 5 found. -fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { - let begun = begin(t, ui); +fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>, place: Env) { + let begun = begin(t, ui, place); let mut stage = begun.open_stage(t); let mixed = value_step(t, &begun, &mut stage); let resolved = begun.resolved(t); @@ -1525,7 +1534,9 @@ struct Begun { sizing: bool, /// The inspector records this run; read once per run. recording: bool, - /// The env of the parent `Ui`, which the style reads. + /// The env the parent installed for the parent `Ui`, under which the run is placed. + place: Env, + /// The place env in the component's token scope, which the style reads. env: Env, /// The env with the component's own command instance, when it has one. own_env: Option, @@ -1564,7 +1575,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) -> Box { +fn begin(t: &mut dyn Erased, ui: &Ui, place: Env) -> Box { let ctx = ui.ctx().clone(); let facts = t.facts(); crate::runtime::measure::count_run(&ctx, facts.name); @@ -1579,7 +1590,7 @@ fn begin(t: &mut dyn Erased, ui: &Ui) -> Box { let recording = !sizing && inspect::recording(&ctx); // 1 env: `Common` moves out of the component; `Resolved` borrows it. A themed component resolves its own look in its // scope, and everything it shows inherits it. - let env = scoped_env(&ctx, Env::of(ui), t.theme_scope()); + let env = scoped_env(&ctx, place.clone(), t.theme_scope()); let common: Common = t.take_common(); let step1 = steps::env(&ctx, &env, &common, t.variants(common.variant, &env)); // 2 style @@ -1595,7 +1606,7 @@ fn begin(t: &mut dyn Erased, ui: &Ui) -> Box { } // The command instance the component is, which steps 4 to 17 run under. let own_env = t.instance_scope().map(|scope| env.derive_local(|scoped| scoped.inherited_mut().commands = scoped.commands.pushed(scope, id))); - Box::new(Begun { ctx, facts, shape, sizing, recording, env, own_env, common, step1, style, id }) + Box::new(Begun { ctx, facts, shape, sizing, recording, place, env, own_env, common, step1, style, id }) } /// Step 4, value: returns whether the binding holds a mixed value. A sizing pass reads the cancel and ends nothing: @@ -1647,7 +1658,7 @@ fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { { Some(width) } - _ => Some(crate::layout::flow_room(ui).x) + _ => Some(crate::layout::flow_room(ui, &begun.place).x) .filter(|width| width.is_finite() && !(env.content_column && crate::runtime::measure::active(ctx))), }, }; @@ -1656,7 +1667,7 @@ fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { // room (`mount_room`). A body that fills the width of a bounded room takes the room or its share of it (`sized`), // so it is no unit. let in_flow = matches!(at, ShowAt::Flow) && t.fills().is_none(); - let fill_body = shape == ShapeKind::Body && in_flow && t.in_flow() && t.fills_width() && crate::layout::flow_room(ui).x.is_finite(); + let fill_body = shape == ShapeKind::Body && in_flow && t.in_flow() && t.fills_width() && crate::layout::flow_room(ui, &begun.place).x.is_finite(); let shrink = env.shrink.filter(|_| in_flow && (shape == ShapeKind::Leaf || (shape == ShapeKind::Body && t.in_flow() && !fill_body))); let given = match shrink { Some(crate::layout::Shrink::Apply(row)) => crate::layout::shrink_cap(ctx, row, id), @@ -1693,10 +1704,10 @@ fn extent_step( } let scx = steps::style_cx(ctx, &begun.env, &begun.step1); if sizing || matches!(shape, ShapeKind::Body | ShapeKind::Item) { - let measuring = Measuring { ui, at, width: None, env, scx: &scx, resolved, command: begun.step1.command.clone(), mixed }; + let measuring = Measuring { ui, at, width: None, place: &begun.place, env, scx: &scx, resolved, command: begun.step1.command.clone(), mixed }; if sizing { t.measured_extent(&measuring, stage) } else { t.pass_extent(&measuring) } } else { - t.extent(ui, at, id, &scx) + t.extent(ui, &begun.place, at, id, &scx) } } @@ -1729,7 +1740,9 @@ fn measure_step( let fills = |axis: craft_behavior::Axis| t.fills() == Some(axis) || begun.common.sizing == Some(super::Sizing::Fill); 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)); + && [craft_behavior::Axis::X, craft_behavior::Axis::Y] + .into_iter() + .any(|axis| fills(axis) && crate::layout::counting_fills(ctx, &begun.place, 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 } @@ -1777,8 +1790,9 @@ fn measure_step( } false => cap, }; - let fit_room = - (leaf_in_flow && shrink == Some(crate::layout::Shrink::Fit)).then(|| crate::layout::flow_room(ui).x).filter(|room| room.is_finite()); + let fit_room = (leaf_in_flow && shrink == Some(crate::layout::Shrink::Fit)) + .then(|| crate::layout::flow_room(ui, &begun.place).x) + .filter(|room| room.is_finite()); let cap = match fit_room.filter(|room| size.x > *room) { Some(room) => Some(cap.map_or(room, |cap| cap.min(room)).max(least(&mut *t))), None => cap, @@ -1788,7 +1802,7 @@ fn measure_step( let measured = size; // A component on a layer or in a window of its own takes no room in the parent's flow: the parent neither sizes it // nor counts it among the children that share its room. Its host sizes it in its own `Ui`. - let size = if t.in_flow() { t.sized(ui, id, size) } else { size }; + let size = if t.in_flow() { t.sized(ui, &begun.place, id, size) } else { size }; match shrink { 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. @@ -1873,6 +1887,7 @@ fn passes<'a>( p: e, facts: &begun.facts, env: begun.env(), + place: &begun.place, style: &*begun.style, resolved, trace: begun.trace(), @@ -1948,9 +1963,11 @@ pub(super) fn measure_shape( purpose: MeasureFor, ) -> Vec2 { let facts = t.facts(); + // The one walk of a measure: what follows reads the place from it. + let place = Env::of(ui); let env = match under { - Some(under) => super::cx::child_env(&Env::of(ui), under), - None => Env::of(ui), + Some(under) => super::cx::child_env(&place, under), + None => place.clone(), }; let env = scoped_env(ui.ctx(), env, t.theme_scope()); let id = id.unwrap_or_else(|| steps::id(ui, &t.common().id, false, false, facts.style_key, facts.name)); @@ -1971,7 +1988,7 @@ pub(super) fn measure_shape( Vec2::ZERO } else { let mut stage = MemoryStage::open_peek(ui.ctx(), id); - let measuring = Measuring { ui, at, width, env: &env, scx: &scx, resolved: &resolved, command: step1.command.clone(), mixed }; + let measuring = Measuring { ui, at, width, place: &place, env: &env, scx: &scx, resolved: &resolved, command: step1.command.clone(), mixed }; t.measured_extent(&measuring, &mut stage) }; let ask = |t: &mut dyn Erased, proposal: Proposal| measured(t, &MeasureIn { ui, env: &env, proposal, room: None }, &*style, &resolved, extent); diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index c3e9e325e1..1682cdee01 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -234,16 +234,16 @@ impl Erased for Typed<'_, '_, C> { self.hooks.overflow() } - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2 { - self.hooks.sized(self.comp.get_ref(), ui, id, size) + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { + self.hooks.sized(self.comp.get_ref(), ui, place, id, size) } fn arena(&self) -> bool { self.hooks.arena(self.comp.get_ref()) } - fn extent(&mut self, ui: &Ui, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { - self.hooks.extent(self.comp.get_ref(), ui, at, id, scx) + fn extent(&mut self, ui: &Ui, place: &Env, at: ShowAt, id: Id, scx: &StyleCx<'_>) -> Vec2 { + self.hooks.extent(self.comp.get_ref(), ui, place, at, id, scx) } fn pad(&self, tokens: &UiTokens) -> f32 { @@ -448,8 +448,8 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { self.hooks.focus(self.comp) } - fn sized(&self, ui: &Ui, id: Id, size: Vec2) -> Vec2 { - self.hooks.sized(self.comp, ui, id, size) + fn sized(&self, ui: &Ui, place: &Env, id: Id, size: Vec2) -> Vec2 { + self.hooks.sized(self.comp, ui, place, id, size) } fn fills_width(&self) -> bool { @@ -541,15 +541,16 @@ fn measure_shape( super::measure_shape(&mut Typed::new(Held::Lent(comp), hooks), ui, id, proposal, under, purpose) } +/// Shows a leaf in `ui`, whose children are placed under `place` (the env installed for it). pub(crate) fn show_leaf>( slot: &mut Option, ui: &mut Ui, - at: ShowAt, + (at, place): (ShowAt, Env), tip: Option>, ) -> C::Output { let mut hooks = LeafHooks { scope: held(slot).common(Internal::new()).command_scope }; let mut typed = Typed::owned(slot, &mut hooks); - super::run(&mut typed, ui, at, tip); + super::run(&mut typed, ui, at, tip, place); typed.output() } @@ -561,16 +562,18 @@ pub(crate) fn show_container_taking( rect: Rect, body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, ) -> Inner { - let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None); - crate::layout::close_flow_start_in(ui); + let place = Env::of(ui); + let shown = show_container(slot, ui, (ShowAt::Rect(rect), place.clone()), body, None); + crate::layout::close_flow_start(ui.ctx(), &place); crate::runtime::egui::alloc::advance_past(ui, rect); shown } +/// Shows a container in `ui`, whose children are placed under `place` (the env installed for it). pub(crate) fn show_container( slot: &mut Option, ui: &mut Ui, - at: ShowAt, + (at, place): (ShowAt, Env), body: &mut dyn FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: Option>, ) -> Inner { @@ -586,7 +589,7 @@ pub(crate) fn show_container( }; let mut hooks = crate::contract::body::BodyHooks::of(held(slot), &mut call); let mut typed = Typed::owned(slot, &mut *hooks); - super::run(&mut typed, ui, at, tip); + super::run(&mut typed, ui, at, tip, place); let output = typed.output(); let id = crate::contract::Outcome::response(&output).id; let settle = ran.then(|| crate::contract::settle::SettleAt { ctx: ui.ctx().clone(), body: sub(id, "body"), owner: id }); @@ -638,7 +641,8 @@ pub(crate) fn show_items<'r, C: Collection>( ) -> C::Output { let mut hooks = crate::contract::items::ItemsHooks::::new(source, item); let mut typed = Typed::owned(slot, &mut hooks); - super::run(&mut typed, ui, ShowAt::Flow, None); + let place = Env::of(ui); + super::run(&mut typed, ui, ShowAt::Flow, None, place); typed.output() } diff --git a/crates/ui-contract/src/contract/steps/measure.rs b/crates/ui-contract/src/contract/steps/measure.rs index 6ccec0dbf7..3d0fd033fe 100644 --- a/crates/ui-contract/src/contract/steps/measure.rs +++ b/crates/ui-contract/src/contract/steps/measure.rs @@ -78,6 +78,7 @@ pub(crate) fn measure_cx<'a, C: Component>( let padding = padding(ComponentStyle::metrics(style).padding, resolved.pad); MeasureCx { env: input.env.view(), + scope: input.env, style, resolved, proposal: input.proposal, diff --git a/crates/ui-contract/src/contract/steps/place.rs b/crates/ui-contract/src/contract/steps/place.rs index c6df925f75..cfdc257fd1 100644 --- a/crates/ui-contract/src/contract/steps/place.rs +++ b/crates/ui-contract/src/contract/steps/place.rs @@ -2,10 +2,17 @@ use egui::{Rect, Ui, Vec2}; -/// Step 6, place: in flow one allocation with no widget, at a rect none. -pub(crate) fn place(ui: &mut Ui, at: crate::contract::run::ShowAt, size: Vec2, child: crate::layout::InFlow) -> Rect { +/// Step 6, place: in flow one allocation with no widget, at a rect none. `place` is the env `ui`'s children are placed +/// under. +pub(crate) fn place( + ui: &mut Ui, + place: &crate::runtime::env::Env, + at: crate::contract::run::ShowAt, + size: Vec2, + child: crate::layout::InFlow, +) -> Rect { match at { - crate::contract::run::ShowAt::Flow => crate::layout::place_in_cell(ui, size, child), + crate::contract::run::ShowAt::Flow => crate::layout::place_in_cell(ui, place, size, child), crate::contract::run::ShowAt::Rect(rect) => rect, } } diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index 5a855c7f06..5b24f0a2db 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -458,8 +458,16 @@ fn prepare(core: &mut CxCore<'_>, ui: &mut Ui, decl: &TextPart, state: &mut Text let pointer = !scrubs || in_edit_before || (focused && !core.press.phase.is_drag()); core.text_takes_pointer = pointer; let read_only = core.resolved.read_only || !enabled; - let ink = decl.options.ink.map_or(ink, |own| crate::style::ink_color(&crate::runtime::env::Env::of(ui).tokens, own)); - let ink = if enabled { ink } else { crate::style::rgba_color(crate::runtime::env::Env::of(ui).tokens.color.text.disabled) }; + // The tokens of the place the field is shown in, read only for an ink of its own or a disabled field. + let place = (decl.options.ink.is_some() || !enabled).then(|| crate::runtime::env::Env::of(ui)); + let ink = match (decl.options.ink, &place) { + (Some(own), Some(place)) => crate::style::ink_color(&place.tokens, own), + _ => ink, + }; + let ink = match &place { + Some(place) if !enabled => crate::style::rgba_color(place.tokens.color.text.disabled), + _ => ink, + }; let held = core.popup(EDIT_MENU).is_open_in(core); // The text the part shows now: its resting text while it is idle and has one, else the value's own. let current = decl.options.resting.as_deref().filter(|_| !focused && !held && state.draft.is_none()).unwrap_or(&decl.shown); diff --git a/crates/ui-contract/src/layout/arrange.rs b/crates/ui-contract/src/layout/arrange.rs index 8a6b9b1704..c90c8bce25 100644 --- a/crates/ui-contract/src/layout/arrange.rs +++ b/crates/ui-contract/src/layout/arrange.rs @@ -59,7 +59,8 @@ impl<'c> Placed<'c> { /// is mirrored through the env's direction when the layout mirrors, so no arrangement reads the direction. /// Returns the rect the placement took. pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_>]) -> Rect { - let rtl = Env::of(ui).direction.is_rtl(); + let env = Env::of(ui); + let rtl = env.direction.is_rtl(); let room = ui.available_rect_before_wrap(); let base = ui.scope_id(); let ids: Vec = children.iter().map(|placed| (placed.id)(base)).collect(); @@ -71,7 +72,7 @@ pub fn arrange(ui: &mut Ui, layout: &dyn Arrangement, children: &mut [Placed<'_> placed.response = Some(placed.child.show_at(ui, *id, flow.to_physical(*rect))); } let whole = flow.to_physical(Rect::from_min_size(room.min, taken)); - super::close_flow_start_in(ui); + super::close_flow_start(ui.ctx(), &env); alloc::advance_past(ui, whole); whole } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index b9732e0fb3..01dcf2d469 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -350,11 +350,6 @@ pub(crate) fn close_flow_start(ctx: &egui::Context, env: &Env) { } } -/// `close_flow_start` for a child placed in the flow of `ui` outside `place_in_cell` and `take_in_flow`. -pub(crate) fn close_flow_start_in(ui: &Ui) { - close_flow_start(ui.ctx(), &Env::of(ui)); -} - /// What the labelled rows of a bracketed `Row` (`ContainerProps::bracket`) reported of their controls in the sweep or /// run under way, and the rect of the row's last child in flow, by the row's layout id. #[derive(Default)] @@ -415,9 +410,8 @@ enum MainFill { /// /// `given` is the caller's own fact: whether the child is given `axis` (a leaf where its body does not size from its /// content, a container given the axis or held across its column, a collection where it fills). `offered` is the room -/// the flow offers it along `axis`, `measured` what it measured. -pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32, given: bool) -> f32 { - let env = Env::of(ui); +/// the flow offers it along `axis`, `measured` what it measured. `env` is the env `ui`'s children are placed under. +pub(crate) fn fill_size(ui: &Ui, env: &Env, id: Id, axis: Axis, measured: f32, offered: f32, given: bool) -> f32 { // Across an unwrapped row's content-height line a child that fills is shown across the line the row settled on in // its measuring run, where the child measured at its own size. if axis == Axis::Y @@ -434,8 +428,8 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 } // In a body that shares the axis and scrolls along it, a share never cuts the child's content: what is past the // view scrolls. - if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, axis).is_some() { - return match main_fill(ui, id, axis) { + if env.fill_body.is_some_and(|(_, along)| along == axis) && view_room(ui, env, axis).is_some() { + return match main_fill(ui, env, id, axis) { MainFill::Measuring => 0.0, MainFill::Share(share, _) => measured.max(share), MainFill::Room(_) => measured, @@ -444,7 +438,7 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 if !offered.is_finite() { return measured; } - match main_fill(ui, id, axis) { + match main_fill(ui, env, id, axis) { MainFill::Measuring => 0.0, MainFill::Share(share, least) => least.max(share), MainFill::Room(least) => least.max(offered), @@ -453,8 +447,7 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 /// What the child `id` of `ui`'s body that fills along `axis` takes there, with its least along it /// (`layout_memory::fill_least`). Called once per such child and run. -fn main_fill(ui: &Ui, id: Id, axis: Axis) -> MainFill { - let env = Env::of(ui); +fn main_fill(ui: &Ui, env: &Env, id: Id, axis: Axis) -> MainFill { let Some((body, _)) = env.fill_body.filter(|(_, along)| *along == axis) else { return MainFill::Room(0.0) }; layout_memory::leaf_fill(ui.ctx(), id, body, axis); if let Some(share) = env.fill_share { @@ -472,11 +465,12 @@ fn count_fill(ctx: &egui::Context, body: Id) { pass_state::with::(ctx, |counts| *counts.0.entry(body).or_insert(0) += 1); } -/// Counts the memoized view whose content fills the main axis of `ui`'s sharing body as one child that fills it, in the -/// first sweep of the body's measuring run (`counting_fills`), as a child shown there directly is counted. -pub(crate) fn count_fill_view(ui: &Ui) { - if let Some((body, _)) = Env::of(ui).fill_body { - count_fill(ui.ctx(), body); +/// Counts the memoized view whose content fills the main axis of the sharing body that places children under `env` as +/// one child that fills it, in the first sweep of the body's measuring run (`counting_fills`), as a child shown there +/// directly is counted. +pub(crate) fn count_fill_view(ctx: &egui::Context, env: &Env) { + if let Some((body, _)) = env.fill_body { + count_fill(ctx, body); } } @@ -491,18 +485,16 @@ pub(crate) fn take_view_fill(ctx: &egui::Context, view: Id) -> Option { pass_state::with::(ctx, |fills| fills.0.remove(&view)) } -/// The share a child of `ui`'s body that fills along `axis` takes there, once its body knows it: the room the child -/// is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike. -pub(crate) fn fill_share(ui: &Ui, axis: Axis) -> Option { - let env = Env::of(ui); +/// The share a child placed under `env` that fills its body along `axis` takes there, once its body knows it: the room +/// the child is measured and shown in along that axis, in the measuring run's second sweep and in the real run alike. +pub(crate) fn fill_share(env: &Env, axis: Axis) -> Option { env.fill_body.filter(|(_, along)| *along == axis).and(env.fill_share) } -/// Whether `ui` runs the first sweep of a measuring run of a body that shares its main axis: a child that fills along -/// `axis` is only counted there, and its contents run in the second sweep, at its share. -pub(crate) fn counting_fills(ui: &Ui, axis: Axis) -> bool { - let env = Env::of(ui); - measure::active(ui.ctx()) && env.fill_body.is_some_and(|(_, along)| along == axis) && env.fill_share.is_none() +/// Whether the children placed under `env` run in the first sweep of a measuring run of a body that shares its main +/// axis: a child that fills along `axis` is only counted there, and its contents run in the second sweep, at its share. +pub(crate) fn counting_fills(ctx: &egui::Context, env: &Env, axis: Axis) -> bool { + measure::active(ctx) && env.fill_body.is_some_and(|(_, along)| along == axis) && env.fill_share.is_none() } /// What a unit of a shrinking row reported in the first sweep: its id, the width it took there, the width it asks for @@ -653,17 +645,18 @@ pub fn plan_levels(units: &[Vec], room: f32) -> Vec { /// centred row in it centres across its column, not in the view the row scrolls in. pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(&mut Ui, usize)) { let ctx = ui.ctx().clone(); - let shrink = Env::of(ui).shrink; + let env = Env::of(ui); + let shrink = env.shrink; + let rtl = env.direction.is_rtl(); // The unit's content is no unit of the row: it runs in a room of its own, on the row's line only to fill it. Its // children take no slots on the line and report nothing to the row: the unit's block is what stands in the row. - let line = Env::of(ui).row_line.map(|line| RowLine { places: false, ..line }); - let own_room = Env::of(ui).derive_local(|scoped| { + let line = env.row_line.map(|line| RowLine { places: false, ..line }); + let own_room = env.derive_local(|scoped| { scoped.start_room(); scoped.row_line = line; }); match shrink { Some(Shrink::Count(row)) => { - let rtl = Env::of(ui).direction.is_rtl(); let mut widths = Vec::with_capacity(levels); let mut widest = Vec2::ZERO; // Each level measures at what it takes in no room: unbounded along x, in a region as wide as the row's, @@ -698,7 +691,6 @@ pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(& let level = level.min(levels.saturating_sub(1)); match width { Some(width) => { - let rtl = Env::of(ui).direction.is_rtl(); let bounded = own_room.derive_local(|scoped| scoped.unbounded.0 = false); // Half a pixel past the width the level measured at, as a bounded re-run of a measured body is given: // content that took exactly that width lays out the same here, never wrapping on a rounding. @@ -932,11 +924,12 @@ fn shrink_widths_in_turn(units: &[ShrinkUnit], first: &[bool], fixed: f32, room: /// the bodies' leasts. It records the width `shrink_in_turns` gives each unit for the rest of the pass, and when a unit /// took another width there, or the row probed, it sweeps them again at those widths. The real run shows each unit at /// most at its width. Every sweep runs in a child of `ui` with its layout, so the children get the same ids in each, -/// and the records a measuring run leaves are the ones the real run's children read and check. -fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> R { +/// and the records a measuring run leaves are the ones the real run's children read and check. `place` is the env +/// installed for `ui`. +fn run_shrinking(ui: &mut Ui, place: &Env, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> R { let ctx = ui.ctx().clone(); let layout = *ui.layout(); - let mut env = Env::of(ui); + let mut env = place.clone(); let inherited = (env.unbounded.0, env.least); let rank_short = env.rank_short; let mut sweep = |ui: &mut Ui, shrink: Shrink, body: &mut dyn FnMut(&mut Ui) -> R| { @@ -954,9 +947,9 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> if !measure::active(&ctx) { return child::block(ui, None, layout, |ui| sweep(ui, Shrink::Apply(id), &mut body)).0; } - let room = shrink_room(ui); - let order = if Env::of(ui).values.get::().0 { ShrinkOrder::FromEnd } else { ShrinkOrder::Even }; - let (drops, gap) = (view_room(ui, Axis::X).is_none(), ui.spacing().item_spacing.x); + let room = shrink_room(ui, place); + let order = if place.values.get::().0 { ShrinkOrder::FromEnd } else { ShrinkOrder::Even }; + let (drops, gap) = (view_room(ui, place, Axis::X).is_none(), ui.spacing().item_spacing.x); // Records the width each unit gets, and returns whether one took another width in the first sweep. The levelled // units take their levels first, in the room the continuous units leave at their least; the continuous units then // narrow by their own rule with the levelled units' widths held. A row without levelled units holds nothing more. @@ -1058,8 +1051,7 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> /// In a body that scrolls along `axis`, what its view shows along it from the start of the rest of `ui`'s layout: along /// x the width a row there shrinks to fit and a child that fills its width fills, along y the height the children that /// fill a `Stack` there share. `None` outside such a body. -pub(crate) fn view_room(ui: &Ui, axis: Axis) -> Option { - let env = Env::of(ui); +pub(crate) fn view_room(ui: &Ui, env: &Env, axis: Axis) -> Option { let scrolls = |view: &crate::runtime::lazy::View| if axis == Axis::X { env.unbounded.0 && view.axes.0 } else { env.unbounded.1 && view.axes.1 }; env.lazy.filter(scrolls).map(|view| { let start = view.start_of(ui.available_rect_before_wrap()); @@ -1071,14 +1063,14 @@ pub(crate) fn view_room(ui: &Ui, axis: Axis) -> Option { /// The width the leaves of a row in `ui` shrink to fit: the row's flow room, except in a body that scrolls along x, /// where it is what the view shows from the row's start. There the leaves narrow to their least before the body /// scrolls, and when even their least does not fit they keep their natural widths and the body scrolls. -fn shrink_room(ui: &Ui) -> f32 { - view_room(ui, Axis::X).unwrap_or_else(|| flow_room(ui).x) +fn shrink_room(ui: &Ui, env: &Env) -> f32 { + view_room(ui, env, Axis::X).unwrap_or_else(|| flow_room(ui, env).x) } /// Runs `body` as the content of the `Stack` (along y) or unwrapped `Row` (along x) body `id` in `ui`, the block /// it is placed in, when the body is given that axis. A measuring run is `measure_sharing`'s; the real run gives each -/// child that fills the share its record holds. -fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, mut body: impl FnMut(&mut Ui) -> R) -> R { +/// child that fills the share its record holds. `body` gets the env installed for the `Ui` it runs in. +fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, mut body: impl FnMut(&mut Ui, &Env) -> R) -> R { let ctx = ui.ctx().clone(); if measure::active(&ctx) { let (inner, rect) = measure_sharing(ui, env, id, axis, layout, &mut body); @@ -1086,11 +1078,11 @@ fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo return inner; } if !shares_along(env, axis) { - return child::block(ui, None, layout, |ui| Env::run_in(ui, env.clone(), body)).0; + return child::block(ui, None, layout, |ui| Env::run_in(ui, env.clone(), |ui| body(ui, env))).0; } let key = sub(id, "share"); child::block(ui, None, layout, |ui| { - let room = share_room(ui, axis); + let room = share_room(ui, env, axis); let share = layout_memory::measured(&ctx, key) .filter(|found| found.took.y >= 1.0 && room.is_finite()) .map(|found| ((room - found.took.x) / found.took.y).max(0.0)); @@ -1113,20 +1105,20 @@ fn shares_along(env: &Env, axis: Axis) -> bool { /// The room along `axis` the children that fill a body in `ui` share. In a body that scrolls along the axis they share /// what the view shows: shorter than the view, the content leaves them its rest; longer, they take their least and the /// body scrolls (`MainFill::Share`). -fn share_room(ui: &Ui, axis: Axis) -> f32 { - view_room(ui, axis).unwrap_or_else(|| { +fn share_room(ui: &Ui, env: &Env, axis: Axis) -> f32 { + view_room(ui, env, axis).unwrap_or_else(|| { let size = ui.available_rect_before_wrap().size(); if axis == Axis::Y { size.y } else { size.x } }) } /// One sweep of the children of the sharing body `id` in `ui`, each child that fills `axis` given `share`. -fn share_sweep(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option, body: &mut dyn FnMut(&mut Ui) -> R) -> R { +fn share_sweep(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option, body: &mut dyn FnMut(&mut Ui, &Env) -> R) -> R { let scoped = env.local_mut(); scoped.fill_body = Some((id, axis)); scoped.fill_share = share; let installed = Env::install_for(ui, env.clone()); - let inner = body(ui); + let inner = body(ui, env); Env::restore(ui.ctx(), installed); inner } @@ -1137,11 +1129,11 @@ fn share_sweep(ui: &mut Ui, env: &mut Env, id: Id, axis: Axis, share: Option< /// The first sweep counts the children that fill at no extent and records what the others and the gaps took with the /// number that fill. With a child that fills, a second sweep replaces it under the same ids: the others reuse what the /// first recorded, and each child that fills is measured once, at its equal share of the rest. -fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Rect) { +fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, body: &mut dyn FnMut(&mut Ui, &Env) -> R) -> (R, Rect) { let ctx = ui.ctx().clone(); - let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui) -> R| { + let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui, &Env) -> R| { let mut child = laid_out_child(ui, layout); - let inner = Env::run_in(&mut child, env.clone(), body); + let inner = Env::run_in(&mut child, env.clone(), |ui| body(ui, env)); (inner, child.min_rect()) }; if !shares_along(env, axis) { @@ -1153,7 +1145,7 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: let first = crate::contract::keeping_ids(&ctx, || { let (inner, rect, room) = { let mut first = laid_out_child(ui, layout); - let room = share_room(&first, axis); + let room = share_room(&first, env, axis); pass_state::with::(&ctx, |counts| counts.0.insert(id, 0)); let inner = share_sweep(&mut first, &mut sweep_env, id, axis, None, body); (inner, first.min_rect(), room) @@ -1165,7 +1157,7 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: ((inner, rect, share), share.is_some()) }); match first { - (_, _, Some(share)) => in_child(ui, &mut |ui| share_sweep(ui, &mut sweep_env, id, axis, Some(share), body)), + (_, _, Some(share)) => in_child(ui, &mut |ui, _| share_sweep(ui, &mut sweep_env, id, axis, Some(share), body)), (inner, rect, None) => (inner, rect), } } @@ -1185,11 +1177,11 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: // PLAN: the second sweep's need is decided once for the column, not per held container at body/hooks.rs's reuse // rule: a container that reused its content-sized record there would be laid out across in the real run under records // not made across. -fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: impl FnMut(&mut Ui) -> R) -> R { +fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: impl FnMut(&mut Ui, &Env) -> R) -> R { let ctx = ui.ctx().clone(); let key = sub(id, "column"); let column_env = |column: Option| env.derive_local(|scoped| scoped.column = column); - let sweep = |ui: &mut Ui, column: Option, body: &mut dyn FnMut(&mut Ui) -> R| { + let sweep = |ui: &mut Ui, column: Option, body: &mut dyn FnMut(&mut Ui, &Env) -> R| { let env = column_env(column); let installed = Env::install_for(ui, env.clone()); let inner = run_sharing(ui, &env, id, Axis::Y, layout, body); @@ -1198,7 +1190,7 @@ fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: }; if !measure::active(&ctx) { let across = this_pass(&ctx, false, key).is_some_and(|took| took.x > 0.0); - let column = across.then(|| ColumnSweep::Column(id, flow_room(ui).x)); + let column = across.then(|| ColumnSweep::Column(id, flow_room(ui, env).x)); return sweep(ui, column, &mut body); } let (inner, rect, again) = crate::contract::keeping_ids(&ctx, || { @@ -1353,10 +1345,10 @@ impl Spread { /// records the natural width and count, and the leasts (none for a row that fits). The real run, including one a kept /// transcript serves, builds the same cursor from those records, so each child measures in the same room in both. /// Every sweep runs in a child of `ui` with its layout, so the children get the same ids in each. -fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option) { +/// `env` is the row's env, installed for `ui`. +fn run_spread(ui: &mut Ui, env: &Env, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option) { let ctx = ui.ctx().clone(); let layout = child::row_layout(rtl, false); - let env = Env::of(ui); let sweep = |ui: &mut Ui, env: &Env, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { let flow = Flow::new(ui.available_rect_before_wrap(), rtl); pass_state::with::(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(Spread::new(flow, gap, last, leasts, probe)))); @@ -1374,13 +1366,13 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( let count = this_pass(&ctx, false, leasts_id).map_or(0, |count| count.x as usize); let leasts = (0..count).map(|i| this_pass(&ctx, false, sub(id, ("least", i))).map_or(0.0, |least| least.x)).collect(); let last = this_pass(&ctx, false, id); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, last, leasts, false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, env, last, leasts, false, body)).0; return (inner, natural(&spread)); } let room = ui.available_rect_before_wrap().size(); let ((inner, spread), rect, short) = crate::contract::keeping_ids(&ctx, || { let mut first = laid_out_child(ui, layout); - let (inner, spread) = sweep(&mut first, &env, None, Vec::new(), false, body); + let (inner, spread) = sweep(&mut first, env, None, Vec::new(), false, body); // Half a point: less than a pixel shows at any scale the box runs. let short = spread.as_ref().is_some_and(|spread| spread.count >= 2 && room.x.is_finite() && spread.natural > room.x + 0.5); (((inner, spread), first.min_rect(), short), short) @@ -1400,7 +1392,7 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( }); (leasts, true) }); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, None, leasts.clone(), false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, env, None, leasts.clone(), false, body)).0; (inner, spread, leasts) } else { ui.advance_cursor_after_rect(rect); @@ -1454,13 +1446,13 @@ fn one_line(first: Option, height: f32) -> Option { /// sits at the vertical centre of its cell. #[doc(hidden)] pub fn place_in_flow(ui: &mut Ui, size: Vec2) -> Rect { - place_in_cell(ui, size, InFlow { fill: false, first: Some(size.y / 2.0), line: false }) + let env = Env::of(ui); + place_in_cell(ui, &env, size, InFlow { fill: false, first: Some(size.y / 2.0), line: false }) } /// `place_in_flow` for a child that is `child`. In a measuring run the child reports its line to the row around it -/// and its first line to the container whose header or body it starts. -pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { - let env = Env::of(ui); +/// and its first line to the container whose header or body it starts. `env` is the env `ui`'s children are placed under. +pub(crate) fn place_in_cell(ui: &mut Ui, env: &Env, size: Vec2, child: InFlow) -> Rect { let (line, target) = (env.row_line.filter(|line| line.places), env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its @@ -1472,11 +1464,11 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); // A child of a wrapping row takes the height of its line; a one-line child sits at its middle. - let wrapped = if line.is_none() { wrap_line(ui, &env, size) } else { None }; + let wrapped = if line.is_none() { wrap_line(ui, env, size) } else { None }; let height = line.and_then(|line| line.height).or(wrapped); let slot = Vec2::new(size.x, height.map_or(above + size.y, |height| height.max(above + size.y))); - let (rect, in_cell) = take_in(ui, &env, slot); - wrap_took(ui, &env, rect); + let (rect, in_cell) = take_in_flow(ui, env, slot); + wrap_took(ui, env, rect); let placed = if child.fill && in_cell { rect } else { @@ -1508,10 +1500,15 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { placed } -/// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the -/// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. -pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { - take_in(ui, &Env::of(ui), size) +/// Takes `size` in flow in `ui`, whose children are placed under `env`: the next cell of the `Grid` or spread `Row` body +/// that encloses it directly, else the next allocation of `ui`'s layout; the body's flow start closes. Returns the rect +/// taken and whether it is a cell. +pub(crate) fn take_in_flow(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { + close_flow_start(ui.ctx(), env); + match cell_in(ui, env.grid, size) { + Some(cell) => (cell, true), + None => (alloc::space(ui, size), false), + } } /// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it. @@ -1521,27 +1518,16 @@ pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { - take_in(ui, &env, Vec2::ZERO); - } -} - -/// `take_in_flow` under `env`, `ui`'s env: the next cell of its grid, else the next allocation; the body's flow start -/// closes. -fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { - close_flow_start(ui.ctx(), env); - match cell_in(ui, env.grid, size) { - Some(cell) => (cell, true), - None => (alloc::space(ui, size), false), + take_in_flow(ui, &env, Vec2::ZERO); } } /// Takes the next cell of the `Grid` or spread `Row` body that encloses `ui` directly for a child of `size`, and returns -/// it; `None`, taking nothing, outside such a body. -pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { - let env = Env::of(ui); +/// it; `None`, taking nothing, outside such a body. `env` is the env `ui`'s children are placed under. +pub(crate) fn take_cell(ui: &mut Ui, env: &Env, size: Vec2) -> Option { let cell = cell_in(ui, env.grid, size); if cell.is_some() { - close_flow_start(ui.ctx(), &env); + close_flow_start(ui.ctx(), env); } cell } @@ -1553,31 +1539,31 @@ fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { } /// The region the next child shown in flow in `ui` measures and is placed in: that of the next cell of the `Grid` or -/// spread `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. -pub(crate) fn flow_region(ui: &Ui) -> Rect { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); +/// spread `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. `env` is the env `ui`'s children are +/// placed under, as for every helper here that takes one. +pub(crate) fn flow_region(ui: &Ui, env: &Env) -> Rect { + let cell = env.grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); cell.unwrap_or_else(|| ui.available_rect_before_wrap()) } -/// The width a child of the `Row` body that encloses `ui` directly takes alone in it: the room the row is offered, +/// The width a child placed under `env` takes alone in the `Row` body that places it: the room the row is offered, /// whatever its earlier children took, unbounded in a body that scrolls along x. `None` outside such a row. -pub(crate) fn row_alone_room(ui: &Ui) -> Option { - let env = Env::of(ui); +pub(crate) fn row_alone_room(env: &Env) -> Option { env.row_room.map(|room| if env.unbounded.0 { f32::INFINITY } else { room }) } /// The room a child shown in flow in `ui` measures and sizes in: the room of the next cell of the `Grid` or spread /// `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. -pub(crate) fn flow_room(ui: &Ui) -> Vec2 { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); - cell.unwrap_or_else(|| open_room(ui)) +pub(crate) fn flow_room(ui: &Ui, env: &Env) -> Vec2 { + let cell = env.grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); + cell.unwrap_or_else(|| open_room(ui, env)) } /// The rest of `ui`'s layout (the room offered to the container, less the earlier siblings and gaps; a whole line in a row /// that wraps); unbounded along the axes of the scrolling body that encloses it, whose region is only as large as egui /// can make it. -fn open_room(ui: &Ui) -> Vec2 { - let (x, y) = Env::of(ui).unbounded; +fn open_room(ui: &Ui, env: &Env) -> Vec2 { + let (x, y) = env.unbounded; let mut room = ui.available_size_before_wrap(); // In a row that wraps, a child that does not fit the rest of the line goes on the next one: its room is a line. let layout = ui.layout(); @@ -1586,7 +1572,6 @@ fn open_room(ui: &Ui) -> Vec2 { } // A body sized from its content offers its children the width it was offered, and a row body that placed its // block behind a lead the width of its band; either less what they took. - let env = Env::of(ui); if let Some(offered) = env.offered.or(env.row_room) { room.x += offered - ui.max_rect().width(); } @@ -1595,39 +1580,38 @@ fn open_room(ui: &Ui) -> Vec2 { /// The room a child that fills its width fills in `ui`: `flow_room`, except that in a `Content` column of a `Grid` it /// is the column's width, so the child never measures as the room and pushes the next column out of it. -pub(crate) fn flow_fill_room(ui: &Ui) -> Vec2 { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); - cell.unwrap_or_else(|| open_room(ui)) +pub(crate) fn flow_fill_room(ui: &Ui, env: &Env) -> Vec2 { + let cell = env.grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); + cell.unwrap_or_else(|| open_room(ui, env)) } /// `flow_fill_room` for a leaf that fills: along x in a body that scrolls along x it is what the view shows from the /// leaf's start, so the leaf fills the view and what is past it scrolls; along y the same in a `Stack` body that /// scrolls along y, whose children that fill share it. -pub(crate) fn leaf_fill_room(ui: &Ui) -> Vec2 { - let room = flow_fill_room(ui); - let x = view_room(ui, Axis::X).filter(|_| room.x.is_infinite()); - let y = view_room(ui, Axis::Y).filter(|_| room.y.is_infinite() && shares_y(ui)); +pub(crate) fn leaf_fill_room(ui: &Ui, env: &Env) -> Vec2 { + let room = flow_fill_room(ui, env); + let x = view_room(ui, env, Axis::X).filter(|_| room.x.is_infinite()); + let y = view_room(ui, env, Axis::Y).filter(|_| room.y.is_infinite() && shares_y(env)); Vec2::new(x.unwrap_or(room.x), y.unwrap_or(room.y)) } -/// Whether the children in flow in `ui` are the children of a `Stack` body that shares its height among those that fill. -pub(crate) fn shares_y(ui: &Ui) -> bool { - Env::of(ui).fill_body.is_some_and(|(_, along)| along == Axis::Y) +/// Whether the children placed under `env` are the children of a `Stack` body that shares its height among those that +/// fill. +pub(crate) fn shares_y(env: &Env) -> bool { + env.fill_body.is_some_and(|(_, along)| along == Axis::Y) } -/// Whether the next child shown in flow in `ui` goes in a `Content` column of the `Grid` body that encloses `ui` -/// directly: like a content-sized column, a child that fills its width is placed at its measured width there. -pub(crate) fn in_grid_content_column(ui: &Ui) -> bool { - Env::of(ui) - .grid - .is_some_and(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).is_some_and(Cursor::in_content_column))) +/// Whether the next child placed under `env` goes in a `Content` column of the `Grid` body that places it: like a +/// content-sized column, a child that fills its width is placed at its measured width there. +pub(crate) fn in_grid_content_column(ctx: &egui::Context, env: &Env) -> bool { + env.grid.is_some_and(|body| pass_state::with::(ctx, |cursors| cursors.0.get(&body).is_some_and(Cursor::in_content_column))) } -/// The cell the next child shown in flow in `ui` takes, when the body that encloses `ui` directly is a `Grid`: the -/// grid's body, the cell's column and whether the column is a `Content` one. -pub(crate) fn grid_cell(ui: &Ui) -> Option<(Id, usize, bool)> { - let grid = Env::of(ui).grid?; - pass_state::with::(ui.ctx(), |cursors| { +/// The cell the next child placed under `env` takes, when the body that places it is a `Grid`: the grid's body, the +/// cell's column and whether the column is a `Content` one. +pub(crate) fn grid_cell(ctx: &egui::Context, env: &Env) -> Option<(Id, usize, bool)> { + let grid = env.grid?; + pass_state::with::(ctx, |cursors| { let cursor = cursors.0.get(&grid)?; Some((grid, cursor.grid_column()?, cursor.in_content_column())) }) @@ -1914,8 +1898,8 @@ fn open_sweep(ctx: &egui::Context, target: Option, row: Option, least: f /// Records the line of the unwrapped `Row` body `id` from what its children took in `ui`, the block they ran in, /// with the line `shared` it shares with its container's regions; a real run records nothing. The last sweep of a /// measuring run gives the line. The block takes the row's height once its children sit on the line, and the row -/// reports its line to the target its body reports a first line to. -fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option) { +/// reports its line to `target`, the container its body reports a first line to. +fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option, target: Option) { if !sizing { return; } @@ -1933,7 +1917,7 @@ fn record_line(ui: &mut Ui, sizing: bool, id: Id, shared: Option) { } let top = ui.max_rect().top(); alloc::reach_down_to(ui, top + height); - if let Some(target) = Env::of(ui).first_line { + if let Some(target) = target { report_first_line(&ctx, target, took.centre.map(|_| top + centre)); } } @@ -2027,8 +2011,10 @@ fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> scoped.stack_gap = Some((at.id, at.gap.y)); }); let installed = Env::install_for(ui, env.clone()); + let mut body = body; + let body = move |ui: &mut Ui, _: &Env| body(ui); // A held child of a column whose own room is unbounded keeps the width it measured at. - let inner = if env.content_column && flow_room(ui).x.is_finite() { + let inner = if env.content_column && flow_room(ui, &env).x.is_finite() { run_column(ui, &env, at.id, child::column_layout(at.rtl), body) } else { run_sharing(ui, &env, at.id, Axis::Y, child::column_layout(at.rtl), body) @@ -2043,19 +2029,17 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m let RowIn { id, gap, shared, sizing, rtl } = *at; let (inner, _) = child::block(ui, None, child::row_layout(rtl, false), |ui| { let line = on_line(id, row_line(&ctx, sizing, id, shared), shared); - let installed = Env::install_for( - ui, - env.derive_local(|scoped| { - scoped.grid = Some(id); - scoped.grid_top = false; - scoped.row_line = Some(line); - scoped.first_line = None; - scoped.flow_body = Some(id); - }), - ); - let inner = run_spread(ui, id, gap.x, rtl, &mut body); + let row = env.derive_local(|scoped| { + scoped.grid = Some(id); + scoped.grid_top = false; + scoped.row_line = Some(line); + scoped.first_line = None; + scoped.flow_body = Some(id); + }); + let installed = Env::install_for(ui, row.clone()); + let inner = run_spread(ui, &row, id, gap.x, rtl, &mut body); Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared); + record_line(ui, sizing, id, shared, None); inner }); inner @@ -2067,19 +2051,17 @@ fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu let RowIn { id, shared, sizing, rtl, .. } = *at; let room = ui.available_rect_before_wrap(); let line = on_line(id, row_line(&ctx, sizing, id, shared), shared); - run_sharing(ui, env, id, Axis::X, child::row_layout(rtl, false), |ui| { - let installed = Env::install_for( - ui, - Env::of(ui).derive_local(|scoped| { - scoped.row_room = Some(room.width()); - scoped.row_line = Some(line); - scoped.first_line = None; - scoped.flow_body = Some(id); - }), - ); - let inner = run_shrinking(ui, id, &mut body); + run_sharing(ui, env, id, Axis::X, child::row_layout(rtl, false), |ui, sweep| { + let row = sweep.derive_local(|scoped| { + scoped.row_room = Some(room.width()); + scoped.row_line = Some(line); + scoped.first_line = None; + scoped.flow_body = Some(id); + }); + let installed = Env::install_for(ui, row.clone()); + let inner = run_shrinking(ui, &row, id, &mut body); Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared); + record_line(ui, sizing, id, shared, sweep.first_line); inner }) } @@ -2103,7 +2085,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign RowAlign::Center | RowAlign::End => { let last = this_pass(&ctx, sizing, id); // In a body that scrolls along x the band is the width its view shows, not the scroll region. - let band = if Env::of(ui).unbounded.0 { shrink_room(ui) } else { room.width() }; + let band = if env.unbounded.0 { shrink_room(ui, env) } else { room.width() }; // Without a measuring run, or in a band without an end, the block is placed as `Start`. last.filter(|last| band.is_finite() && last.x > 0.0 && last.x < band).map(|last| { let spare = band - last.x; @@ -2120,31 +2102,29 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign // line of its own. let block_layout = if wrap && env.least { child::column_layout(rtl) } else { child::row_layout(rtl, wrap) }; let (inner, took) = child::block(ui, rect, block_layout, |ui| { - let installed = Env::install_for( - ui, - env.derive_local(|scoped| { - scoped.row_room = Some(room.width()); - scoped.row_line = line; - scoped.flow_body = Some(id); - if line.is_some() { - scoped.first_line = None; - } - // A leaf wider than a whole line takes the line, never below its least, as in a stack. - if wrap { - scoped.shrink = Some(Shrink::Fit); - } - }), - ); + let row = env.derive_local(|scoped| { + scoped.row_room = Some(room.width()); + scoped.row_line = line; + scoped.flow_body = Some(id); + if line.is_some() { + scoped.first_line = None; + } + // A leaf wider than a whole line takes the line, never below its least, as in a stack. + if wrap { + scoped.shrink = Some(Shrink::Fit); + } + }); + let installed = Env::install_for(ui, row.clone()); if lines { open_wraps(&ctx, sizing, id); } - let inner = if wrap { body(ui) } else { run_shrinking(ui, id, &mut body) }; + let inner = if wrap { body(ui) } else { run_shrinking(ui, &row, id, &mut body) }; if lines { close_wraps(&ctx, sizing, id, room.size()); } Env::restore(&ctx, installed); if !wrap { - record_line(ui, sizing, id, shared); + record_line(ui, sizing, id, shared, None); } inner }); diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 157cfd5bf5..56f35ae858 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,7 +24,7 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start_in, count_fill_view, counting_fills, + BodyLine, BracketTook, HeldKind, InFlow, ask_shortfall, at_flow_start, close_first_line, close_flow_start, count_fill_view, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, open_view_fill, place_in_cell, report_bracket_control, report_fill_least, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, take_bracket, take_cell, take_in_flow, take_shortfall, take_view_fill, diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 0f16b57d56..90b0b15f50 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -791,6 +791,8 @@ impl Env { /// /// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`, outside sizing passes. pub fn of(ui: &Ui) -> Env { + #[cfg(feature = "testing")] + WALKS.with(|walks| walks.set(walks.get() + 1)); let ctx = ui.ctx(); let viewport = pass::current_viewport(ctx); // The root env stands for an entry above the whole stack. @@ -962,6 +964,18 @@ impl Env { } } +#[cfg(feature = "testing")] +thread_local! { + static WALKS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +/// How many times this thread walked a `Ui` stack for its env (`Env::of`). +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn env_walks() -> u64 { + WALKS.with(std::cell::Cell::get) +} + /// One viewport's env entries by the `Ui` they are installed for, and its root env. The lock is held only to /// install or look up an entry or clone an `Arc`. #[derive(Default)] diff --git a/crates/ui-contract/src/testing/mod.rs b/crates/ui-contract/src/testing/mod.rs index e4ca903c4d..42225ed3dd 100644 --- a/crates/ui-contract/src/testing/mod.rs +++ b/crates/ui-contract/src/testing/mod.rs @@ -52,6 +52,8 @@ pub use crate::contract::{Exemption, PatternKind, PatternProbe, Probe, Registrat pub use crate::fonts::document::set_budget as document_face_budget; pub use crate::runtime::audit::{in_run as in_audit_run, set as audit_replays}; #[cfg(feature = "testing")] +pub use crate::runtime::env::env_walks; +#[cfg(feature = "testing")] pub use crate::runtime::layout_memory::forget_kept as forget_measurements; #[cfg(feature = "testing")] pub use crate::runtime::layout_memory::kept_leaves as kept_measurement_leaves; diff --git a/crates/ui-contract/src/testing/stage.rs b/crates/ui-contract/src/testing/stage.rs index c295901d24..81fe0954e9 100644 --- a/crates/ui-contract/src/testing/stage.rs +++ b/crates/ui-contract/src/testing/stage.rs @@ -35,8 +35,9 @@ pub fn stage(ui: &mut Ui) -> Rect { /// The height of the room `ui` offers a story whose root has no content height and fills it (a window, a full-window /// canvas): the room its card's view gives, or the stage height where the room is unbounded. pub fn room_height(ui: &Ui) -> f32 { - let room = flow_room(ui).y; - if room.is_finite() { room } else { stage_height(&Env::of(ui).tokens) } + let env = Env::of(ui); + let room = flow_room(ui, &env).y; + if room.is_finite() { room } else { stage_height(&env.tokens) } } /// Allocates a stage as wide as [`stage`]'s and as tall as the story's content at that width, which `height` gives, @@ -49,8 +50,9 @@ pub fn stage_fitting(ui: &mut Ui, height: impl FnOnce(f32) -> f32) -> Rect { /// The width of the stage [`stage_fitting`] allocates: the width left in `ui` between the least and greatest stage /// width. A story whose content measures itself at a width (through `ui`) reads it before allocating. pub fn stage_width(ui: &Ui) -> f32 { - let tokens = &Env::of(ui).tokens; - let room = flow_room(ui).x; + let env = Env::of(ui); + let tokens = &env.tokens; + let room = flow_room(ui, &env).x; let room = if room.is_finite() { room } else { ui.available_width() }; room.clamp(least_stage_width(tokens), WIDTH_MAX_IN_CONTROLS * tokens.size.control.md) } diff --git a/crates/ui-contract/tests/it/runtime/frame.rs b/crates/ui-contract/tests/it/runtime/frame.rs index f2e45c04c2..755fee0622 100644 --- a/crates/ui-contract/tests/it/runtime/frame.rs +++ b/crates/ui-contract/tests/it/runtime/frame.rs @@ -90,6 +90,39 @@ fn a_settled_pass_looks_up_as_many_services_for_forty_leaves_as_for_ten() { assert_eq!(ten_unbound, forty_unbound, "unbound pass-state reads grow with the runs: {ten_unbound} for ten leaves, {forty_unbound} for forty"); } +/// The place env: a run takes the env its parent installed for its `Ui` from its caller, or walks the `Ui` stack for it +/// once where app code shows it, and every step and layout helper of the run reads it from there. A pass of forty +/// leaves in a panel walks no more often per run than one of ten: at most once. +#[trial] +fn a_run_walks_its_ui_stack_for_its_env_at_most_once() { + use craft_ui::testing::{env_walks, last_pass_runs}; + use craft_ui_test_kit::contract::Panel; + let walks_and_runs = |leaves: usize| { + let mut frames = Frames::new(); + let mut show = |ui: &mut egui::Ui| { + Panel::new().id_salt("leaves").show(ui, |ui, _| { + for at in 0..leaves { + let seen = std::cell::RefCell::new(Seen::default()); + Probe::new(&seen).label(format!("Leaf {at}")).show(ui); + } + }); + }; + for _ in 0..3 { + frames.frame(vec![], &mut show); + } + let walks = env_walks(); + assert_eq!(frames.frame(vec![], &mut show), 1, "the settled frame is one pass"); + let runs: u32 = last_pass_runs(&frames.ctx).iter().map(|(_, runs)| runs).sum(); + (env_walks() - walks, u64::from(runs)) + }; + let ((ten, ten_runs), (forty, forty_runs)) = (walks_and_runs(10), walks_and_runs(40)); + assert!(forty_runs > ten_runs, "the leaves run in the pass: {ten_runs} runs for ten leaves, {forty_runs} for forty"); + assert!( + forty - ten <= forty_runs - ten_runs, + "env walks grow faster than the runs: {ten} walks in {ten_runs} runs for ten leaves, {forty} in {forty_runs} for forty" + ); +} + /// The app command the settled view's probe is bound to; its modal rule is the default one, `Blocked`. #[derive(Clone, Copy, Debug, PartialEq, Eq, CommandSet)] #[command(prefix = "frameTrial")] From fdfcecf20157f4b009f983d110dfa0c7bdd7300c Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 01:09:30 +0000 Subject: [PATCH 3/4] ui-contract: the open-record count is the thread's own Records are open only around runs of a pass on the pass's own thread, so the count that lets a registration skip the pass state is a thread-local. As a process-wide atomic, a record open in another thread's pass made this thread read its pass state (outside its component tree, an unbound read), which made the settled-pass service-lookup trial flaky under parallel test threads. A close with no open record no longer wraps the count. --- crates/ui-contract/src/runtime/replay.rs | 31 +++++++++++++++--------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/crates/ui-contract/src/runtime/replay.rs b/crates/ui-contract/src/runtime/replay.rs index 68213a9c3b..994df233ba 100644 --- a/crates/ui-contract/src/runtime/replay.rs +++ b/crates/ui-contract/src/runtime/replay.rs @@ -24,10 +24,10 @@ use crate::runtime::reads::BindKey; use crate::runtime::shift::Shift; use egui::{Context, IdSet, RecordShift, Rect}; use std::any::Any; +use std::cell::Cell; use std::collections::HashSet; use std::fmt; use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; /// A registration of the recorded run: the call that makes it again and what it is called with. Two entries are equal /// when they come from the same call (the same `again` of [`journal`]) with equal arguments. @@ -108,8 +108,17 @@ impl fmt::Debug for Entry { } } -/// Records open across all contexts, so a registration made while none is open takes no lock. -static OPEN: AtomicUsize = AtomicUsize::new(0); +thread_local! { + /// The records open on this thread, so a registration made while none is open reads no pass state. Records are + /// open only around runs of a pass, on the pass's own thread: a job's thread (a finished job's wake, a progress + /// report) has none, and never takes the pass state the pass's thread holds. + static OPEN: Cell = const { Cell::new(0) }; +} + +/// Whether a record is open on this thread. +fn any_open() -> bool { + OPEN.with(Cell::get) > 0 +} /// The journal of the running pass while a record is open, and the records open around the running code. #[derive(Default)] @@ -246,7 +255,7 @@ impl Record { /// Whether a record is open around the running code. pub(crate) fn recording(ctx: &Context) -> bool { - OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| !recorder.open.is_empty()) + any_open() && pass_state::with::(ctx, |recorder| !recorder.open.is_empty()) } /// Opens a record around the real run of a region, which `close` ends. A run inside an open label scope cannot be @@ -263,7 +272,7 @@ pub(crate) fn open_in_pass(ctx: &Context) { fn push(ctx: &Context, open: Open) { pass_state::with::(ctx, |recorder| recorder.open.push(Open { from: recorder.journal.len(), ..open })); - OPEN.fetch_add(1, Ordering::AcqRel); + OPEN.with(|open| open.set(open.get() + 1)); } /// Opens a record around a run of the replay audit, which `close` ends as any other. @@ -275,13 +284,13 @@ pub(crate) fn open_audit(ctx: &Context) { /// Whether the running code is inside a run of the replay audit. #[cfg(feature = "testing")] pub(crate) fn in_audit_run(ctx: &Context) -> bool { - OPEN.load(Ordering::Acquire) > 0 && pass_state::with::(ctx, |recorder| recorder.open.iter().any(|open| open.audit)) + any_open() && pass_state::with::(ctx, |recorder| recorder.open.iter().any(|open| open.audit)) } /// Ends the innermost record, the one around a run on `layer`: paint or widgets on a layer that is neither `layer` nor /// an overlay the run showed block it. pub(crate) fn close(ctx: &Context, layer: Layer) -> Record { - OPEN.fetch_sub(1, Ordering::AcqRel); + OPEN.with(|open| open.set(open.get().saturating_sub(1))); let (open, journal) = pass_state::with::(ctx, |recorder| { // A close with no open record ends one that holds nothing and is never replayed. let open = recorder.open.pop().unwrap_or_else(|| { @@ -458,10 +467,8 @@ pub(crate) fn replay(ctx: &Context, record: &Record, shift: &RecordShift) { } fn with_open(ctx: &Context, f: impl FnOnce(&mut Facts)) { - // Records are open only around runs of a pass on its own thread. A job's thread (a finished job's wake, a progress - // report) runs no pass of `ctx`: it has no record to note into and must not take the pass state that the pass's - // thread holds. - if OPEN.load(Ordering::Acquire) > 0 && frame::running(ctx).is_some() { + // A record open on this thread is one of a running pass: of `ctx`, or of another context this thread runs. + if any_open() && frame::running(ctx).is_some() { pass_state::with::(ctx, |recorder| { if let Some(open) = recorder.open.last_mut() { f(&mut open.facts); @@ -518,7 +525,7 @@ where /// Notes that the running code read the value `key`. pub(crate) fn note_read(ctx: &Context, key: BindKey) { - if OPEN.load(Ordering::Acquire) > 0 && frame::running(ctx).is_some() { + if any_open() && frame::running(ctx).is_some() { pass_state::with::(ctx, |recorder| { if let Some(open) = recorder.open.last_mut() && (!open.kept || !matches!(key, BindKey::Place(..))) From 8f6558607658ac9dcfea427268de06859ab52fd0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 27 Nov 2026 01:09:30 +0000 Subject: [PATCH 4/4] ui-contract: an unwrapped row reports its line in every alignment A row that places its block at its end, centred or spread recorded its line but reported it to no first-line target: it read the target from its block's Ui after restoring that Ui's entry, which found none. It reports to its body's target as a row placed from its start does, so it sits on an outer row's line by its own line and a container takes it as its first line. --- crates/ui-contract/src/layout/body.rs | 6 +++--- crates/ui-contract/tests/it/layout/body.rs | 23 ++++++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 01dcf2d469..dd6e424734 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -2039,7 +2039,7 @@ fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m let installed = Env::install_for(ui, row.clone()); let inner = run_spread(ui, &row, id, gap.x, rtl, &mut body); Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared, None); + record_line(ui, sizing, id, shared, env.first_line); inner }); inner @@ -2061,7 +2061,7 @@ fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mu let installed = Env::install_for(ui, row.clone()); let inner = run_shrinking(ui, &row, id, &mut body); Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared, sweep.first_line); + record_line(ui, sizing, id, shared, env.first_line); inner }) } @@ -2124,7 +2124,7 @@ fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign } Env::restore(&ctx, installed); if !wrap { - record_line(ui, sizing, id, shared, None); + record_line(ui, sizing, id, shared, env.first_line); } inner }); diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index c9ef1431c2..71cb25390d 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -567,6 +567,29 @@ fn a_memoized_view_sits_on_the_rows_line() { } } +/// An unwrapped row in a row sits on the outer row's line by its own line, whatever its alignment: a row that places +/// its block from its start, at its end, centred or spread reports its line as its first line alike. +#[trial] +fn an_unwrapped_row_sits_on_the_outer_line_by_its_line_in_every_alignment() { + for align in [RowAlign::Start, RowAlign::SpaceBetween, RowAlign::Center, RowAlign::End] { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let shown = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + Panel::new().layout(BodyLayout::row()).id_salt("outer").show(ui, |ui, _| { + let tall = Block::new(Vec2::new(20.0, 30.0)).show(ui).rect; + let short = Panel::new().layout(BodyLayout::row().align(align)).id_salt("inner").show(ui, |ui, _| Block::new(ITEM).show(ui).rect); + if !is_measuring(ui.ctx()) { + shown.set((tall, short.inner.unwrap_or(Rect::NOTHING))); + } + }); + }); + fixture.room(Vec2::splat(400.0)).settle(); + let (tall, short) = seen.get(); + assert!(short.height() > 0.0, "{align:?}: the inner row showed its block: {short:?}"); + assert!((short.center().y - tall.center().y).abs() < SLACK, "{align:?}: the inner row's block {short:?} is off the line of {tall:?}"); + } +} + /// A Row in right-to-left holding a vertically scrolling container (content-sized, then filling its height) beside a /// probe: the container, the probe inside it and the probe beside it are finite, and the container lies in the row. #[trial]