From df2b2aa4909df18c5de6879582b656f1790ad7dc Mon Sep 17 00:00:00 2001 From: aiongg Date: Wed, 11 Nov 2026 17:00:55 +0000 Subject: [PATCH] contract: one read and one props clone per body run, props compared by value, shared inherited env - pass_extent builds the measuring run's hooks from the run's own read instead of reading again on a peek stage; the measuring run of a real pass now sees the kept scroll extent and anchor, as a sizing pass's does. - BodyHooks holds the container's props in one Arc for the run; the measure key keeps that Arc and compares the fields a body's measure reads (ContainerProps::measures_like), replacing the Debug-text fingerprint. Glyph is Sync so the props can live in layout memory. - Scoped keeps the per-scope fields and shares the rarely changed ones (tokens, platform, words, formats, app values, commands) in an Arc read through Deref; writers go through inherited_mut/extend_values. ItemFacts sits behind an Arc. - The line env derives only when it changes something; run_body, run_body_measured and run_sharing take the body's env instead of looking it up again. --- crates/ui-contract/src/contract/body.rs | 7 +- crates/ui-contract/src/contract/body/hooks.rs | 75 +++++---- .../ui-contract/src/contract/body/inherit.rs | 8 +- crates/ui-contract/src/contract/body/size.rs | 16 +- crates/ui-contract/src/contract/container.rs | 68 +++----- .../ui-contract/src/contract/items/hooks.rs | 6 +- .../ui-contract/src/contract/items/measure.rs | 2 +- .../src/contract/overlay/opener.rs | 2 +- .../ui-contract/src/contract/overlay/place.rs | 4 +- .../ui-contract/src/contract/overlay/props.rs | 2 +- crates/ui-contract/src/contract/run.rs | 9 +- crates/ui-contract/src/layout/body.rs | 24 +-- crates/ui-contract/src/primitives/icon.rs | 5 +- crates/ui-contract/src/runtime/env.rs | 151 +++++++++++------- .../ui-contract/src/runtime/env/app_values.rs | 8 +- .../ui-contract/src/runtime/env/overrides.rs | 19 ++- .../ui-contract/src/runtime/windows/spec.rs | 2 +- crates/ui-contract/src/testing/layout.rs | 5 +- crates/ui-contract/src/testing/story.rs | 6 +- 19 files changed, 239 insertions(+), 180 deletions(-) diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index 92e51d3f3..70666379d 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -1,6 +1,7 @@ //! The body step (16.3): the regions of a container (header, body with its scroll region, footer), open and //! gate state, scroll offset, move and resize, and the zoomed canvas body. +use super::ContainerProps; use super::cx::BodyCx; use super::overlay::PlacementChange; use crate::runtime::memory::SaveKey; @@ -9,6 +10,7 @@ use crate::runtime::overlay::CloseReason; use crate::runtime::windows::ResizeEdge; use craft_behavior::ScrollPos; use egui::{Rect, Ui, Vec2}; +use std::sync::Arc; mod hooks; mod inherit; @@ -39,6 +41,8 @@ struct BodyView { pub(super) struct BodyHooks<'b> { pub(super) body: &'b mut dyn FnMut(&mut Ui, &mut BodyCx<'_>), + /// The container's props, cloned once for the run: every hook and the measuring run read this copy. + props: Arc, /// The body's size from this pass's measuring run; `None` inside the measuring run itself. measured_body: Option, /// The header's size from this pass's measuring run; `None` without a header or inside the measuring run. @@ -119,9 +123,10 @@ pub(super) struct BodyHooks<'b> { } impl<'b> BodyHooks<'b> { - pub(super) fn new(body: &'b mut dyn FnMut(&mut Ui, &mut BodyCx<'_>)) -> Self { + pub(super) fn new(body: &'b mut dyn FnMut(&mut Ui, &mut BodyCx<'_>), props: Arc) -> Self { BodyHooks { body, + props, measured_body: None, measured_header: None, measured_footer: Vec2::ZERO, diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index a39fa8ae6..b22c1ab5f 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -127,8 +127,8 @@ impl ShapeHooks for BodyHooks<'_> { fn read(&mut self, comp: &mut C, stage: &mut MemoryStage, id: Id, env: &Env) { let ctx = stage.ctx().clone(); - let props = comp.props(Internal::new()).clone(); - let props = &props; + let props = Arc::clone(&self.props); + let props = &*props; let scroll = scroll_of(props); let collapse = props.collapse; let save = props.save.clone(); @@ -274,7 +274,7 @@ impl ShapeHooks for BodyHooks<'_> { /// the room. What the regions took is recorded for the rest of the pass; a record this pass already holds serves /// instead when the room still allows it (`reusable`). fn measured_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Vec2 { - let props = comp.props(Internal::new()).clone(); + let props = Arc::clone(&self.props); // A mount outside the flow takes no room in a parent's sizing pass, so its regions run only when it is // measured itself. A pane as tall as its content takes its height in the flow. let flows = match &props.mount { @@ -336,7 +336,7 @@ impl ShapeHooks for BodyHooks<'_> { let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(&ctx)); // A record a run of this pass left serves as before; a kept one serves only while the inputs it was measured // under hold. - let key = self.measure_key(&props, at.env, at.width); + let key = self.measure_key(at.env, at.width); let reused = (self.reuse || at.ui.is_sizing_pass()) .then(|| { let found = layout_memory::run_found(&ctx, id); @@ -412,22 +412,32 @@ impl ShapeHooks for BodyHooks<'_> { /// an enclosing container left when the room still allows it, else a measuring run of its own now. A closed /// layer that no longer shows runs none. fn pass_extent(&mut self, comp: &mut C, at: &Measuring<'_, '_>, style: &C::Style, shown: Option>>) -> Vec2 { - let props = comp.props(Internal::new()).clone(); + let props = Arc::clone(&self.props); let (ctx, id) = (at.ui.ctx().clone(), at.resolved.id); let layer = matches!(props.mount, Mount::Layer(_) | Mount::FullWindow | Mount::Viewport { .. }); let fading = layer && !self.open && crate::runtime::motion::layer_fading(&ctx, sub(id, "presence")); if !layer || self.open || fading { + // The measuring run starts from what this run's `read` found: the measuring run of a sizing parent reads + // the same state. let mut stage = MemoryStage::open_peek(&ctx, id); - let mut fresh = BodyHooks::new(&mut *self.body); - fresh.read(comp, &mut stage, id, at.env); - // A peek stage holds no session scroll state: the measuring run decides by the offset this pass shows. - fresh.view_offset = self.view_offset; - fresh.open = self.open; - fresh.open_at_read = self.open; - fresh.presence = self.presence; - fresh.open_given = true; - fresh.shown_closed = fading; - fresh.reuse = true; + let mut fresh = BodyHooks { + save: self.save.clone(), + layer: self.layer, + fixed: self.fixed, + open_bound: self.open_bound, + scroll_bound: self.scroll_bound, + last_extent: self.last_extent, + anchor: self.anchor, + follows_end: self.follows_end, + view_offset: self.view_offset, + open: self.open, + open_at_read: self.open, + presence: self.presence, + open_given: true, + shown_closed: fading, + reuse: true, + ..BodyHooks::new(&mut *self.body, Arc::clone(&self.props)) + }; crate::contract::run::measured_extent(comp, &mut fresh, at, &mut stage, style, shown); } let took = |key: Id| layout_memory::measured(&ctx, key).map(|measured| measured.took); @@ -496,8 +506,8 @@ impl ShapeHooks for BodyHooks<'_> { matches!(comp.props(Internal::new()).layout, layout::BodyLayout::Row { wrap: false, .. }) } - fn parts(&mut self, comp: &mut C, rect: Rect, pcx: &mut PartsCx<'_, C>) { - let props = comp.props(Internal::new()).clone(); + fn parts(&mut self, _comp: &mut C, rect: Rect, pcx: &mut PartsCx<'_, C>) { + let props = Arc::clone(&self.props); let ctx = pcx.ui.ctx().clone(); let rtl = pcx.flow.is_rtl(); let tokens = pcx.tokens; @@ -597,7 +607,7 @@ impl ShapeHooks for BodyHooks<'_> { } fn content(&mut self, comp: &mut C, ui: &mut Ui, env: &Env, cx: &mut Cx<'_, C>, values: &AppValues) { - let props = comp.props(Internal::new()).clone(); + let props = Arc::clone(&self.props); let (id, ctx, rect) = (cx.core.id, cx.core.ctx.clone(), cx.core.rect); let rtl = env.direction.is_rtl(); let node = matches!(C::ROLE, Role::Node(_)); @@ -653,15 +663,19 @@ impl ShapeHooks for BodyHooks<'_> { let enabled = gate.unwrap_or(true); // What the body and the end region share: gate, size, roving group and commands. The body adds its arena, // transform and scroll owner; the end region lies outside them. - let line_env = region_env.derive_local(|scoped| { - scoped.enabled &= enabled; - if let Some(size) = props.child_size { - scoped.size = size; - } - if props.roving.is_some() { - scoped.roving = Some(crate::contract::steps::body_group(id)); - } - }); + let line_env = if enabled && props.child_size.is_none() && props.roving.is_none() { + region_env.clone() + } else { + region_env.derive_local(|scoped| { + scoped.enabled &= enabled; + if let Some(size) = props.child_size { + scoped.size = size; + } + if props.roving.is_some() { + scoped.roving = Some(crate::contract::steps::body_group(id)); + } + }) + }; let end_frame = RegionFrame { id, rtl, node, env: &line_env }; // A footer in the end region is part of a column sized from its content: a fill-width child takes its // measured width there and shows across the column, so it never sets the column's width. @@ -787,8 +801,9 @@ impl ShapeHooks for BodyHooks<'_> { if lays_out { crate::runtime::lazy::begin(&ctx, id); } - let region_env = Env::install_for(®ion_ui, body_env.derive_local(|scoped| scoped.lazy = Some(view))); - layout::run_body(&mut region_ui, layout_id, layout, gap, |ui| { + let view_env = body_env.derive_local(|scoped| scoped.lazy = Some(view)); + let region_env = Env::install_for(®ion_ui, view_env.clone()); + layout::run_body(&mut region_ui, &view_env, layout_id, layout, gap, |ui| { shared_labels(ui, id, label_column, room.x, &mut group_extent, |ui| body(ui, bcx)) }); Env::restore(&ctx, region_env); @@ -816,7 +831,7 @@ impl ShapeHooks for BodyHooks<'_> { } // A row that places its block itself asks for its children's width, not the room it spans. None => { - let (_, natural) = layout::run_body_measured(&mut body_ui, layout_id, layout, gap, line, |ui| { + let (_, natural) = layout::run_body_measured(&mut body_ui, &body_env, layout_id, layout, gap, line, |ui| { shared_labels(ui, id, label_column, room.x, &mut group_extent, |ui| body(ui, bcx)) }); natural.map(|width| Vec2::new(width, body_ui.min_rect().height())) diff --git a/crates/ui-contract/src/contract/body/inherit.rs b/crates/ui-contract/src/contract/body/inherit.rs index 0d9ac25e3..5ddb19f6d 100644 --- a/crates/ui-contract/src/contract/body/inherit.rs +++ b/crates/ui-contract/src/contract/body/inherit.rs @@ -51,9 +51,9 @@ impl BodyHooks<'_> { // The container's own `enabled(false)` greys everything inside it, as a scope would. scoped.enabled &= cx.core.resolved.enabled; if let Some(window) = window { - scoped.commands = scoped.commands.pushed(WindowCommand::SCOPE, window); + scoped.inherited_mut().commands = scoped.commands.pushed(WindowCommand::SCOPE, window); } - scoped.values.extend(values); + scoped.extend_values(values); if cx.core.resolved.ltr_axis { scoped.direction = Direction::Ltr; } @@ -66,13 +66,13 @@ impl BodyHooks<'_> { scoped.content_column = true; } if props.header.is_some_and(|header| header.band == DragBand::Reorder) { - scoped.commands = scoped.commands.pushed(REORDER_SCOPE, id); + scoped.inherited_mut().commands = scoped.commands.pushed(REORDER_SCOPE, id); } // A host env (a layer's) does not carry the push the container's own context made. if let Some(scope) = props.command_scope && scoped.commands.innermost(scope.name()) != Some(id) { - scoped.commands = scoped.commands.pushed(scope, id); + scoped.inherited_mut().commands = scoped.commands.pushed(scope, id); } if let Some(theme) = &props.theme { theme.apply(ctx, scoped); diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 70ea5321b..bab903da8 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -10,12 +10,13 @@ use crate::runtime::env::Env; use crate::runtime::layout_memory; use crate::runtime::memory::sub; use egui::{Context, Id, Rect, Ui, Vec2}; +use std::sync::Arc; /// The inputs a body's measuring run measures under. A later pass offering the same takes the body's kept /// transcript (`layout_memory::kept_serves`); its real run checks that the content is the same. #[derive(PartialEq)] pub(super) struct MeasureKey { - props: u64, + props: MeasuredProps, room: Vec2, given: (bool, bool), width: Option, @@ -26,6 +27,15 @@ pub(super) struct MeasureKey { env: EnvFacts, } +/// The props a body was measured under, compared on the fields its measure reads. +struct MeasuredProps(Arc); + +impl PartialEq for MeasuredProps { + fn eq(&self, other: &Self) -> bool { + self.0.measures_like(&other.0) + } +} + /// What a body's measure reads of its env besides the room. #[derive(PartialEq)] struct EnvFacts { @@ -45,9 +55,9 @@ struct EnvFacts { impl<'b> BodyHooks<'b> { /// The inputs this body's measuring run measures under, once `measured_extent` has its room. - pub(super) fn measure_key(&self, props: &ContainerProps, env: &Env, width: Option) -> MeasureKey { + pub(super) fn measure_key(&self, env: &Env, width: Option) -> MeasureKey { MeasureKey { - props: props.measure_fingerprint(), + props: MeasuredProps(Arc::clone(&self.props)), room: self.room, given: self.given, width, diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 9f3b9bcec..0e951de09 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -17,7 +17,7 @@ use egui::Rect; pub use crate::runtime::env::ThemeScope; /// Where a container lives. -#[derive(Clone, Debug, Default)] +#[derive(Clone, Debug, Default, PartialEq)] #[non_exhaustive] pub enum Mount { /// In the parent's layout. @@ -607,49 +607,31 @@ impl Default for ContainerProps { } impl ContainerProps { - /// A fingerprint of the props a body's measure reads: equal props give equal fingerprints. What it leaves out - /// (focus, arena, gates, commands, live region, roving, save key, set position) does not change a size. Glyphs - /// show as `Glyph(..)`: an icon is a component of the content, which the content check asks. - pub(crate) fn measure_fingerprint(&self) -> u64 { - use std::fmt::Write as _; - /// FNV-1a over the `Debug` text, without building it: `Debug` writes every `f32` so that it reads back - /// exactly. - struct Fnv(u64); - impl std::fmt::Write for Fnv { - fn write_str(&mut self, text: &str) -> std::fmt::Result { - for byte in text.bytes() { - self.0 = (self.0 ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3); - } - Ok(()) - } - } - let mut hash = Fnv(0xcbf2_9ce4_8422_2325); - let _ = write!( - hash, - "{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}|{:?}", - self.mount, - self.surface, - self.pad, - self.sizing, - self.room_height, - self.layout, - self.header, - self.scroll, - self.footer, - self.end, - self.help, - self.collapse, - self.body_gap, - self.least_width, - self.child_size, - self.transform, - self.theme, - self.label, - self.outer_edit, - self.collection_body, - ); - hash.0 + /// Whether a body measured under `other` measures the same under these props. What it leaves out (focus, arena, + /// gates, commands, live region, roving, save key, set position) does not change a size. + pub(crate) fn measures_like(&self, other: &ContainerProps) -> bool { + self.mount == other.mount + && self.surface == other.surface + && self.pad == other.pad + && self.sizing == other.sizing + && self.room_height == other.room_height + && self.layout == other.layout + && self.header == other.header + && self.scroll == other.scroll + && self.footer == other.footer + && self.end == other.end + && self.help == other.help + && self.collapse == other.collapse + && self.body_gap == other.body_gap + && self.least_width == other.least_width + && self.child_size == other.child_size + && self.transform == other.transform + && self.theme == other.theme + && self.label == other.label + && self.outer_edit == other.outer_edit + && self.collection_body == other.collection_body } + /// Props with every field at its default. pub const fn new() -> Self { ContainerProps { diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index e025773f9..8d0a1ed5a 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -392,7 +392,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { } let child_size = comp.props(Internal::new()).child_size; let base_env = env.derive(|scoped| { - scoped.values.extend(values); + scoped.extend_values(values); scoped.arena = Some(ArenaId::new(id)); scoped.size = child_size.unwrap_or(cx.core.resolved.size); }); @@ -514,7 +514,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { base_env.derive_local(|scoped| { scoped.item = Some(item_id); scoped.row = Some(row_group); - scoped.item_facts = Some(ItemFacts { item: item_id, flags, position, columns: column_keys, toggles: toggle_keys }); + scoped.item_facts = Some(Arc::new(ItemFacts { item: item_id, flags, position, columns: column_keys, toggles: toggle_keys })); }), ); item = Props::id(item, item_id); @@ -663,7 +663,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let mut open = true; let builder = UiBuilder::new().max_rect(rect).layout(child::column_layout(rtl)).scope_id(sub(id, "empty")); let mut empty_ui = alloc::child(ui, builder); - let installed = Env::install_for(&empty_ui, env.derive(|scoped| scoped.values.extend(values))); + let installed = Env::install_for(&empty_ui, env.derive(|scoped| scoped.extend_values(values))); let (resolved, view) = (cx.core.resolved, cx.core.env); let mut bcx = BodyCx::new(sub(id, "body"), view, resolved, rect, &mut *cx.core.memory, &mut open, None); comp.empty(&mut empty_ui, &mut bcx); diff --git a/crates/ui-contract/src/contract/items/measure.rs b/crates/ui-contract/src/contract/items/measure.rs index edea9a4b4..e58d88f43 100644 --- a/crates/ui-contract/src/contract/items/measure.rs +++ b/crates/ui-contract/src/contract/items/measure.rs @@ -112,7 +112,7 @@ impl<'s, 'r, C: Collection> ItemsHooks<'s, 'r, C> { env.derive_local(|scoped| { scoped.item = Some(item_id); scoped.row = Some(rows::row_group(item_id)); - scoped.item_facts = Some(facts); + scoped.item_facts = Some(std::sync::Arc::new(facts)); }), ); widest = widest.max(item.measure_in(ui, Proposal::Ideal).x); diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index 15b7efac1..a11b26dd8 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -31,7 +31,7 @@ pub enum Trigger { /// A component that opens a free-standing popup, and how. A layer with several openers keeps the first as its /// `Overlay.opener`, which keys the layer's open state, and the others in `others`. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Opener { /// The opener's id. diff --git a/crates/ui-contract/src/contract/overlay/place.rs b/crates/ui-contract/src/contract/overlay/place.rs index f93e8840b..dfea0840a 100644 --- a/crates/ui-contract/src/contract/overlay/place.rs +++ b/crates/ui-contract/src/contract/overlay/place.rs @@ -4,7 +4,7 @@ use craft_behavior::overlay::{Align, Side}; use egui::{Align2, Pos2, Rect, Vec2}; /// Where an overlay hangs from. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum Anchor { /// A rect in the opener's layer space. @@ -40,7 +40,7 @@ impl FloatPlace { } /// Where an egui layer sits. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum Place { /// Hung from an anchor. diff --git a/crates/ui-contract/src/contract/overlay/props.rs b/crates/ui-contract/src/contract/overlay/props.rs index deaca8842..c35485dd5 100644 --- a/crates/ui-contract/src/contract/overlay/props.rs +++ b/crates/ui-contract/src/contract/overlay/props.rs @@ -87,7 +87,7 @@ impl Default for Dismiss { } /// Data describing an egui layer. Presets fill focus and dismissal; builders change single fields. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Overlay { /// Where it sits. diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index 5a52cd5fd..cc38597f7 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -927,7 +927,8 @@ fn run(mut comp: C, ui: &mut Ui, at: ShowAt, tip: Option // A sizing pass reads the cancel and ends nothing: its stage is a copy, and the real run reads the cancel again. let cancelled: Vec<_> = value.cancelled.into_iter().filter(|_| !sizing).collect(); hooks.read(&mut comp, &mut stage, id, &env); - let own_env = hooks.instance_scope(&comp).map(|scope| env.derive_local(|scoped| scoped.commands = scoped.commands.pushed(scope, id))); + let own_env = + hooks.instance_scope(&comp).map(|scope| env.derive_local(|scoped| scoped.inherited_mut().commands = scoped.commands.pushed(scope, id))); let env = own_env.as_ref().unwrap_or(&env); trace.mark(Step::Value); // 5 measure @@ -1139,7 +1140,8 @@ pub(crate) fn show_container( inner = Some(body(ui, cx)); }; let ctx = ui.ctx().clone(); - let output = run(comp, ui, at, tip, &mut super::body::BodyHooks::new(&mut call)); + let props = Arc::new(comp.props(Internal::new()).clone()); + let output = run(comp, ui, at, tip, &mut super::body::BodyHooks::new(&mut call, props)); let id = crate::contract::Outcome::response(&output).id; let settle = ran.then(|| super::settle::SettleAt { ctx, body: sub(id, "body"), owner: id }); Inner { output, inner, settle } @@ -1169,7 +1171,8 @@ pub(crate) fn measure_container( let mut call = |ui: &mut Ui, cx: &mut BodyCx<'_>| { body(ui, cx); }; - measure_shape(comp, ui, None, proposal, None, &mut super::body::BodyHooks::new(&mut call)) + let props = Arc::new(comp.props(Internal::new()).clone()); + measure_shape(comp, ui, None, proposal, None, &mut super::body::BodyHooks::new(&mut call, props)) } /// A measuring run's extent: the shape's `measured_extent` under a `Cx` that senses nothing and writes only to the diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 62f6ce6d9..ae2583195 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -227,9 +227,8 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> /// what the others and the gaps took with the number that fill. With a child that fills, it sweeps them again: the /// others reuse what the first sweep recorded, and each child that fills is measured once, at its equal share of the /// rest. The real run gives each the same share from that record. -fn run_sharing(ui: &mut Ui, id: Id, axis: Axis, layout: egui::Layout, mut body: impl FnMut(&mut Ui) -> R) -> R { +fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, mut body: impl FnMut(&mut Ui) -> R) -> R { let ctx = ui.ctx().clone(); - let env = Env::of(ui); let given = if axis == Axis::Y { !env.content.1 } else { !env.content.0 }; if !given { return child::block(ui, None, layout, body).0; @@ -239,7 +238,7 @@ fn run_sharing(ui: &mut Ui, id: Id, axis: Axis, layout: egui::Layout, mut bod let sweep = |ui: &mut Ui, share: Option, body: &mut dyn FnMut(&mut Ui) -> R| { let installed = Env::install_for( ui, - Env::of(ui).derive_local(|scoped| { + env.derive_local(|scoped| { scoped.fill_body = Some((id, axis)); scoped.fill_share = share; }), @@ -526,8 +525,8 @@ fn found(ctx: &egui::Context, sizing: bool, id: Id, room: Vec2, took: Vec2) { /// run found, `SpaceBetween` shares the room its children left there between them, and `Grid` places its cells from /// the widest child per column and tallest per row there. Without a measuring run they place as `Start`, spread at /// the gap and size columns from the cells as they come. -pub(crate) fn run_body(ui: &mut Ui, id: Id, layout: &BodyLayout, gap: Vec2, body: impl FnMut(&mut Ui) -> R) -> R { - run_body_measured(ui, id, layout, gap, None, body).0 +pub(crate) fn run_body(ui: &mut Ui, env: &Env, id: Id, layout: &BodyLayout, gap: Vec2, body: impl FnMut(&mut Ui) -> R) -> R { + run_body_measured(ui, env, id, layout, gap, None, body).0 } /// `run_body`, with the width the children take at the gap alone for a `Row` that places its block itself (`End`, @@ -535,17 +534,18 @@ pub(crate) fn run_body(ui: &mut Ui, id: Id, layout: &BodyLayout, gap: Vec2, b /// line the body shares with its container's inline header or end region: an unwrapped `Row` sets its children on it. pub(crate) fn run_body_measured( ui: &mut Ui, + env: &Env, id: Id, layout: &BodyLayout, gap: Vec2, shared: Option, mut body: impl FnMut(&mut Ui) -> R, ) -> (R, Option) { - let rtl = Env::of(ui).direction.is_rtl(); + let rtl = env.direction.is_rtl(); let ctx = ui.ctx().clone(); let sizing = measure::active(&ctx); match layout { - BodyLayout::Stack => (run_sharing(ui, id, Axis::Y, child::column_layout(rtl), body), None), + BodyLayout::Stack => (run_sharing(ui, env, id, Axis::Y, child::column_layout(rtl), body), None), BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => { let (inner, _) = child::block(ui, None, child::row_layout(rtl, false), |ui| { let flow = Flow::new(ui.available_rect_before_wrap(), rtl); @@ -554,7 +554,7 @@ pub(crate) fn run_body_measured( let line = on_line(row_line(&ctx, sizing, id), shared); let installed = Env::install_for( ui, - Env::of(ui).derive_local(|scoped| { + env.derive_local(|scoped| { scoped.grid = Some(id); scoped.row_line = line; }), @@ -576,7 +576,7 @@ pub(crate) fn run_body_measured( BodyLayout::Row { wrap: false, align: RowAlign::Start } => { let room = ui.available_rect_before_wrap(); let line = on_line(row_line(&ctx, sizing, id), shared); - let inner = run_sharing(ui, id, Axis::X, child::row_layout(rtl, false), |ui| { + let inner = 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| { @@ -610,7 +610,7 @@ pub(crate) fn run_body_measured( let (inner, took) = child::block(ui, rect, child::row_layout(rtl, *wrap), |ui| { let installed = Env::install_for( ui, - Env::of(ui).derive_local(|scoped| { + env.derive_local(|scoped| { scoped.row_room = Some(room.width()); scoped.row_line = line; }), @@ -631,7 +631,7 @@ pub(crate) fn run_body_measured( let inner = child::block(ui, None, child::column_layout(rtl), |ui| { let top = ui.available_rect_before_wrap().top(); let last = measured_tracks(&ctx, sizing, id, columns.len()); - let content_run = measure::active(&ctx) && Env::of(ui).content.0; + let content_run = measure::active(&ctx) && env.content.0; // A measuring run under a body sized from its content gives each fill column the width its cells // take, as a content column: the room it would share is not the body's to claim. let cursor = if content_run { @@ -640,7 +640,7 @@ pub(crate) fn run_body_measured( GridCursor::new(Flow::new(ui.available_rect_before_wrap(), rtl), columns, gap, &last) }; Service::::run(&ctx, |cursors| cursors.0.insert(id, Cursor::Grid(cursor))); - let installed = Env::install_for(ui, Env::of(ui).derive_local(|scoped| scoped.grid = Some(id))); + let installed = Env::install_for(ui, env.derive_local(|scoped| scoped.grid = Some(id))); let inner = body(ui); Env::restore(&ctx, installed); // Cells place from last pass's rows, so a measuring run's rows all start at the top: the grid reaches diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index 8ae8f713e..892a2c16c 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -22,8 +22,9 @@ pub enum Mirror { Never, } -/// A value glyph: an icon drawn from a value. -pub trait Glyph { +/// A value glyph: an icon drawn from a value. It is `Sync` because container props that show one are kept with a +/// body's measurement in layout memory. +pub trait Glyph: Sync { /// Whether the glyph has a reading direction (an arrow) and so flips under right-to-left. fn directional(&self) -> bool { false diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index f780fb300..213c0df8c 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -66,42 +66,13 @@ impl Deref for Env { #[derive(Clone)] #[non_exhaustive] pub struct Scoped { - /// The resolved tokens of the scope; read in `style` only. - #[doc(hidden)] - pub tokens: Arc, - /// What the tokens were resolved from (the light or dark mode among them): the app's, until a scope that - /// resolves its tokens in another mode sets them. - pub(crate) token_inputs: Arc, - /// The operating system. - #[doc(hidden)] - pub os: Os, - /// Whether the window is active. - #[doc(hidden)] - pub active: bool, - /// The platform and the running viewport's window facts. - pub(crate) shell: Arc, - /// The keyboard layout as the platform reports it and typing has shown it. - pub(crate) keyboard: Arc, + /// What a scope rarely changes, shared by the scopes below until one changes it (`inherited_mut`). + inherited: Arc, /// The text and icon ink of the surface the scope sits on, set by a container for its body. pub ink: Ink, /// The surface the scope's content sits on: the innermost container surface that paints a fill, set by that /// container for its body. The window's background at the root and where a layer starts. pub(crate) surface: SurfaceKind, - /// The built-in text of the scope. - #[doc(hidden)] - pub words: Arc, - /// How the scope writes numbers: the host's catalog format, else the system region's. - pub(crate) format: Arc, - /// How the scope writes dates: the host's catalog format, else the system region's. - pub(crate) dates: Arc, - /// Today's date as the host supplied it. - pub(crate) today: Option, - /// `RootEnv::tab_toggles_chrome`. - pub(crate) tab_toggles_chrome: bool, - /// The line height per point of text of the leading face of the interface stack, as the frame began: control - /// heights depend on it, so the key covers it. - #[doc(hidden)] - pub line_ratio: f32, /// The key of everything above that the style cache depends on. #[doc(hidden)] pub key: EnvKey, @@ -120,12 +91,8 @@ pub struct Scoped { /// The paragraph direction of text: the interface's, which a container that keeps its axis order leaves alone. /// The bidi order inside a label follows its script. pub text_direction: Direction, - /// The motion mode in effect. - pub motion: MotionPolicy, /// False inside the body of a component with an `Auto` id. pub ids_stable: bool, - /// Root and viewport only: the pixels per point, read back once per pass. - pub scale: Scale, /// The innermost arena: components shown under it join it. pub arena: Option, /// The roving group of the innermost body with `ContainerProps.roving`: components shown under it put @@ -176,7 +143,49 @@ pub struct Scoped { /// Tab leaves the collection and Forward enters the row (17.5). pub(crate) row: Option, /// What the collection's item step recorded for the item it shows this pass. - pub(crate) item_facts: Option, + pub(crate) item_facts: Option>, +} + +/// The values of an env that a scope rarely changes: the resolved tokens, the platform, the language and the app's +/// values. `Scoped` reads them through `Deref`. +#[derive(Clone)] +#[non_exhaustive] +pub struct Inherited { + /// The resolved tokens of the scope; read in `style` only. + #[doc(hidden)] + pub tokens: Arc, + /// What the tokens were resolved from (the light or dark mode among them): the app's, until a scope that + /// resolves its tokens in another mode sets them. + pub(crate) token_inputs: Arc, + /// The operating system. + #[doc(hidden)] + pub os: Os, + /// Whether the window is active. + #[doc(hidden)] + pub active: bool, + /// The platform and the running viewport's window facts. + pub(crate) shell: Arc, + /// The keyboard layout as the platform reports it and typing has shown it. + pub(crate) keyboard: Arc, + /// The built-in text of the scope. + #[doc(hidden)] + pub words: Arc, + /// How the scope writes numbers: the host's catalog format, else the system region's. + pub(crate) format: Arc, + /// How the scope writes dates: the host's catalog format, else the system region's. + pub(crate) dates: Arc, + /// Today's date as the host supplied it. + pub(crate) today: Option, + /// `RootEnv::tab_toggles_chrome`. + pub(crate) tab_toggles_chrome: bool, + /// The line height per point of text of the leading face of the interface stack, as the frame began: control + /// heights depend on it, so the key covers it. + #[doc(hidden)] + pub line_ratio: f32, + /// The motion mode in effect. + pub motion: MotionPolicy, + /// Root and viewport only: the pixels per point, read back once per pass. + pub scale: Scale, /// The container instances above that receive scoped commands. pub(crate) commands: CommandChain, pub(crate) host: Option>, @@ -184,6 +193,14 @@ pub struct Scoped { pub values: AppValues, } +impl Deref for Scoped { + type Target = Inherited; + + fn deref(&self) -> &Inherited { + &self.inherited + } +} + /// The shrink step of an unwrapped `Row` body, as its direct leaf children shown in flow see it. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) enum Shrink { @@ -230,7 +247,19 @@ impl Scoped { /// The facts the collection recorded for the item `id`. pub(crate) fn facts_of(&self, id: Id) -> Option<&ItemFacts> { - self.item_facts.as_ref().filter(|facts| facts.item == id) + self.item_facts.as_deref().filter(|facts| facts.item == id) + } + + /// The inherited values, to change: shared with no other scope from here on. + pub(crate) fn inherited_mut(&mut self) -> &mut Inherited { + Arc::make_mut(&mut self.inherited) + } + + /// Adds `values` over the scope's app values. + pub(crate) fn extend_values(&mut self, values: &AppValues) { + if !values.is_empty() { + self.inherited_mut().values.extend(values); + } } } @@ -288,16 +317,29 @@ impl Env { let shell = Arc::new(windows::shell_of(ctx, pass::current_viewport(ctx))); let active = shell.window.active; let keyboard = Arc::new(crate::runtime::keys::layout_of(ctx)); + let key = EnvKey::new(tokens.key(), root.direction, scale, os, active, root.values.style_hash()).with_line(line_ratio); Env { scoped: Arc::new(Scoped { - key: EnvKey::new(tokens.key(), root.direction, scale, os, active, root.values.style_hash()).with_line(line_ratio), - line_ratio, - tokens, - token_inputs: Arc::new(inputs), - os, - active, - shell, - keyboard, + inherited: Arc::new(Inherited { + line_ratio, + tokens, + token_inputs: Arc::new(inputs), + os, + active, + shell, + keyboard, + motion, + scale, + commands: CommandChain::default(), + words: host_words(ctx, host.as_ref()), + format: host_format(ctx, host.as_ref()), + dates: host_dates(ctx, host.as_ref()), + today: root.today, + tab_toggles_chrome: root.tab_toggles_chrome, + host, + values: root.values.clone(), + }), + key, ink: Ink::default(), surface: SurfaceKind::Background, size: ControlSize::Md, @@ -306,9 +348,7 @@ impl Env { wheel_gated: false, direction: root.direction, text_direction: root.direction, - motion, ids_stable: true, - scale, arena: None, roving: None, transform: None, @@ -327,14 +367,6 @@ impl Env { item: None, row: None, item_facts: None, - commands: CommandChain::default(), - words: host_words(ctx, host.as_ref()), - format: host_format(ctx, host.as_ref()), - dates: host_dates(ctx, host.as_ref()), - today: root.today, - tab_toggles_chrome: root.tab_toggles_chrome, - host, - values: root.values.clone(), }), } } @@ -425,10 +457,11 @@ impl Env { /// active state, window facts and OS are the viewport's, everything else stays. pub(crate) fn rebase(&self, root: &Env) -> Env { self.derive(|s| { - s.scale = root.scale; - s.active = root.active; - s.shell = root.shell.clone(); - s.os = root.os; + let inherited = s.inherited_mut(); + inherited.scale = root.scale; + inherited.active = root.active; + inherited.shell = root.shell.clone(); + inherited.os = root.os; }) } diff --git a/crates/ui-contract/src/runtime/env/app_values.rs b/crates/ui-contract/src/runtime/env/app_values.rs index 3401d5cd7..35e0f58a4 100644 --- a/crates/ui-contract/src/runtime/env/app_values.rs +++ b/crates/ui-contract/src/runtime/env/app_values.rs @@ -82,11 +82,13 @@ impl AppValues { self.entries.map.get(&TypeId::of::()).and_then(|value| value.downcast_ref::()).cloned().unwrap_or_else(T::root) } + /// Whether no value is set. + pub(crate) fn is_empty(&self) -> bool { + self.entries.map.is_empty() + } + /// Takes every value `other` sets over this set's. pub(crate) fn extend(&mut self, other: &AppValues) { - if other.entries.map.is_empty() { - return; - } let entries = Arc::make_mut(&mut self.entries); for (ty, value) in &other.entries.map { entries.map.insert(*ty, Arc::clone(value)); diff --git a/crates/ui-contract/src/runtime/env/overrides.rs b/crates/ui-contract/src/runtime/env/overrides.rs index c23b1d623..319603e16 100644 --- a/crates/ui-contract/src/runtime/env/overrides.rs +++ b/crates/ui-contract/src/runtime/env/overrides.rs @@ -13,7 +13,7 @@ use std::sync::Arc; /// Token-changing values for a container's body: the body and everything under it resolve their styles from the /// inherited theme in another mode. -#[derive(Clone)] +#[derive(Clone, PartialEq)] pub struct ThemeScope { mode: Mode, } @@ -28,8 +28,9 @@ impl ThemeScope { /// Puts the scope's tokens into `scoped`. pub(crate) fn apply(&self, ctx: &Context, scoped: &mut Scoped) { let inputs = TokenInputs { mode: self.mode, ..(*scoped.token_inputs).clone() }; - scoped.tokens = tokens_for(ctx, &inputs); - scoped.token_inputs = Arc::new(inputs); + let inherited = scoped.inherited_mut(); + inherited.tokens = tokens_for(ctx, &inputs); + inherited.token_inputs = Arc::new(inputs); } } @@ -86,18 +87,22 @@ impl Overrides { scoped.wheel_gated = true; } if let Some(motion) = self.motion { - scoped.motion.mode = scoped.motion.mode.lowered_by(motion); + let inherited = scoped.inherited_mut(); + inherited.motion.mode = inherited.motion.mode.lowered_by(motion); } if let Some(direction) = self.direction { scoped.direction = direction; scoped.text_direction = direction; } match self.words { - Some(WordsOverride::Replace(words)) => scoped.words = words, - Some(WordsOverride::Overlay(rows)) => scoped.words = overlaid_words(ctx, &scoped.words, rows), + Some(WordsOverride::Replace(words)) => scoped.inherited_mut().words = words, + Some(WordsOverride::Overlay(rows)) => { + let words = overlaid_words(ctx, &scoped.words, rows); + scoped.inherited_mut().words = words; + } None => {} } - scoped.values.extend(&self.values); + scoped.extend_values(&self.values); } } diff --git a/crates/ui-contract/src/runtime/windows/spec.rs b/crates/ui-contract/src/runtime/windows/spec.rs index 085aebf4f..974765230 100644 --- a/crates/ui-contract/src/runtime/windows/spec.rs +++ b/crates/ui-contract/src/runtime/windows/spec.rs @@ -41,7 +41,7 @@ impl WindowLevel { /// /// A chrome or caption layout the spec leaves unset is the installed decision's for the window's kind /// (`InstallSpec::frame`); with no decision installed the window has the OS's frame. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct WindowSpec { /// What the window is for. diff --git a/crates/ui-contract/src/testing/layout.rs b/crates/ui-contract/src/testing/layout.rs index 89340a838..977bda43f 100644 --- a/crates/ui-contract/src/testing/layout.rs +++ b/crates/ui-contract/src/testing/layout.rs @@ -18,8 +18,9 @@ pub fn body(ui: &mut Ui, key: &'static str, layout: &BodyLayout, sizes: &[Vec2]) let id = sub(ui.scope_id(), key); let place = |ui: &mut Ui| sizes.iter().map(|size| place_in_flow(ui, *size)).collect::>(); let builder = egui::UiBuilder::new().max_rect(ui.available_rect_before_wrap()).sizing_pass().invisible(); - crate::runtime::measure::run(&ui.ctx().clone(), || ui.scope_builder(builder, |ui| run_body(ui, id, layout, Vec2::ZERO, place))); - run_body(ui, id, layout, Vec2::ZERO, place) + let env = crate::runtime::env::Env::of(ui); + crate::runtime::measure::run(&ui.ctx().clone(), || ui.scope_builder(builder, |ui| run_body(ui, &env, id, layout, Vec2::ZERO, place))); + run_body(ui, &env, id, layout, Vec2::ZERO, place) } /// A block that placed itself from `key`'s entry of last pass and measured `real` this pass. Returns the size diff --git a/crates/ui-contract/src/testing/story.rs b/crates/ui-contract/src/testing/story.rs index dac65fa02..01ef3a2a6 100644 --- a/crates/ui-contract/src/testing/story.rs +++ b/crates/ui-contract/src/testing/story.rs @@ -506,8 +506,10 @@ where columns: Vec::new(), toggles: Vec::new(), }; - let installed = - crate::runtime::env::Env::install_for(ui, crate::runtime::env::Env::of(ui).derive_local(|scoped| scoped.item_facts = Some(facts))); + let installed = crate::runtime::env::Env::install_for( + ui, + crate::runtime::env::Env::of(ui).derive_local(|scoped| scoped.item_facts = Some(std::sync::Arc::new(facts))), + ); let shown = row.id(id).show(ui); crate::runtime::env::Env::restore(ui.ctx(), installed); shown