diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index d984f7b64..ab1d798f2 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -165,6 +165,11 @@ pub(super) struct BodyHooks<'b> { } impl<'b> BodyHooks<'b> { + /// The hooks of `comp`'s run, over its props as they are now. + pub(super) fn of(comp: &C, body: &'b mut dyn FnMut(&mut Ui, &mut BodyCx<'_>)) -> Self { + Self::new(body, Arc::new(comp.props(super::Internal::new()).clone())) + } + pub(super) fn new(body: &'b mut dyn FnMut(&mut Ui, &mut BodyCx<'_>), props: Arc) -> Self { BodyHooks { body, diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index d420f42cb..10af8ca0c 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -4,8 +4,8 @@ use super::inherit::{BodyScope, register_instances}; use super::open::open_now; use super::placement::{Placement, measure_layer, overlay_of, shown_placement}; use super::regions::{ - LabelColumns, LabelsFound, RegionFrame, RegionSizes, RuleBands, end_full_height, footer_in_end, footer_rule_under, gap_of, header_gap_of, - label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, + LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_end, footer_rule_under, gap_of, + header_gap_of, label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line, }; use super::reorder::REORDER_BAND; use super::scroll::{ @@ -15,17 +15,17 @@ use super::scroll::{ use super::size::MeasureKey; use super::window::{WindowMode, os_window, window_instance}; use super::{BodyHooks, BodyView}; -use crate::contract::cx::{BodyCx, BodyOwner}; +use crate::contract::cx::{BodyCx, BodyOwner, RegionShare}; use crate::contract::label::{self, LabelIn}; use crate::contract::run::{Measuring, ShapeHooks, ShowAt}; -use crate::contract::{Container, Cx, DragBand, Gap, Internal, Mount, PartsCx, SetPosition, Sizing, ValueOf}; +use crate::contract::{Container, ContainerProps, Cx, DragBand, Gap, Internal, Mount, PartsCx, Resolved, Scroll, SetPosition, Sizing, ValueOf}; use crate::layout::{self}; use crate::primitives::SurfaceSlot; use crate::runtime::access::scope; use crate::runtime::access::{self, Politeness, Role}; use crate::runtime::commands; use crate::runtime::egui::{alloc, areas, child, repaint, response, style}; -use crate::runtime::env::{AppValues, ArenaId, ColumnSweep, Env, RowLine}; +use crate::runtime::env::{AppValues, ArenaId, ColumnSweep, Env, Installed, Message, RowLine}; use crate::runtime::focus::FocusPolicy; use crate::runtime::memory::{MemoryStage, sub}; use crate::runtime::motion::{Driver, Presence, spec}; @@ -36,6 +36,8 @@ use crate::style::ComponentStyle as _; use crate::style::{StyleCx, SurfaceKind, band_color, scroll_bar_look, surface_style}; use craft_behavior::layout_memory::measure_tolerance; use craft_behavior::{CancelRule, CursorIcon, EditEvent, KeyRole, Mixed, Roving, ScrollPos, ScrollSpan, WheelRoom, WheelTaker}; +use craft_theme::variant::Tone; +use egui::layers::ShapeIdx; use egui::{Context, CornerRadius, Id, Pos2, Rect, Shape, Ui, UiBuilder, Vec2}; use std::any::Any; use std::sync::Arc; @@ -302,141 +304,25 @@ 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 = 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 { - Mount::Inline => true, - Mount::Pane(pane) => pane.content_height, - _ => false, + let scrolled_share = match self.measure_room(comp, at, cx) { + Ok(scrolled_share) => scrolled_share, + Err(extent) => return extent, }; - if !flows && at.ui.is_sizing_pass() { - return self.extent(comp, at.ui, at.at, cx.core.id, at.scx); - } - let (id, ctx) = (cx.core.id, at.ui.ctx().clone()); - let open = if self.open_given { self.open } else { open_now(comp, &mut *cx.core.memory, id, &props) }; - self.open = open || self.shown_closed; - self.open_at_read = self.open; - // An animated collapse shows a share of the full body height, so the body is measured while any of it shows. - let shows = self.open || (props.collapse.is_some_and(|collapse| collapse.animated) && self.presence.visible); - self.presence = Presence { t: f32::from(u8::from(shows)), visible: shows, exiting: false }; - self.measured_body = None; - self.measured_header = None; - self.measured_footer = Vec2::ZERO; - self.measured_end = None; - self.measured_controls = None; - // The measuring run lays a scrolling body's content out at the width the real run of this pass gives it: beside - // the bars the kept content extent asks for, so the records it leaves serve that run. - self.last = BodyView::default(); - self.offset = ScrollPos::default(); - self.region_gap = gap_of(&at.env.tokens, Gap::Tight); - self.end_gap = gap_of(&at.env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); - self.header_gap = header_gap_of(&props, &at.env.tokens); - self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx())); - 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), - }; - self.given = self.given_axes(&props, at.env, at.at); - self.fixed_height = self.fixed_height(&props, at.at); - self.passes = self.passes_width(&props, at.env, at.at); - self.held = self.held(&props, at.env); - self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(_))); - // A held container across its column measures at the column's width. - 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); - // 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); - // A container placed at an explicit rect, or mounted on a layer or in a window, is no flow child of that body: - // it takes its own room, not a share. - let flows = matches!(at.at, ShowAt::Flow) && self.in_flow(comp); - // 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 (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))) - { - return Vec2::ZERO; - } - if let Some(share) = crate::layout::fill_share(at.ui, 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) { - self.room.y = share; - scrolled_share = scrolled_y; - } - // A body that fills both axes its parent gives it takes the room, whatever its contents take: a parent's - // measuring run does not run them. It measures them in its own real run. A share of a scrolling view is the - // least of what it takes: its content may be taller. - if at.ui.is_sizing_pass() && self.given == (true, true) && self.room.is_finite() && !scrolled_share { - return self.room; - } - let pad = 2.0 * self.pads(&props, at.scx.tokens); - let vertical = scroll_of(&props).is_some_and(|scroll| scroll.vertical_on()); - 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(at.env, at.width); - // In its column's second sweep a held container measures across the column: its first-sweep record is - // content-sized. - let reused = ((self.reuse || at.ui.is_sizing_pass()) && !(self.across && at.ui.is_sizing_pass())) - .then(|| { - let found = layout_memory::run_found(&ctx, id); - let serves = found || layout_memory::kept_serves(&ctx, id, &key); - serves.then(|| self.reusable(&props, &ctx, id, pad, tolerance)).flatten().map(|took| (took, found)) - }) - .flatten(); - let took = match reused { - Some((took, found)) => { - if found { - layout_memory::kept_also_under(&ctx, id, key); - } - // A capped body whose content outgrew its room was laid out as given it: the record of its content says so. - if self.over_room(&props, at.env, at.at, &ctx, id) { - self.given.1 = true; - } - took - } + let plan = self.measure_plan(at, cx.core.id, scrolled_share); + let vertical = plan.vertical; + let took = match plan.reused { + Some(reused) => self.take_reused(at, plan, reused), // A share of a scrolling view is laid out as given while the content fits it, so the children that fill // share it; taller, the body takes its content height (the children that fill at their least) and the view // scrolls. - None if scrolled_share => { - let fits = self.room.y + tolerance; - self.given.1 = false; - let (content, kept) = crate::contract::draft(&ctx, || self.measure_run(comp, at, cx, key.clone(), None), |took| took.y > fits); - self.given.1 = true; - if kept { content } else { self.measure_run(comp, at, cx, key, None) } - } + None if plan.scrolled_share => self.measure_share(comp, at, cx, plan), // A capped body takes its content height while that fits its room. Taller, the run is taken back and the body // is laid out as given the room, at the footer and header this run measured, so the children that fill share // it; its record of the content height lets later runs of the pass and kept transcripts lay it out the same. - None if self.capped(&props, at.env, at.at) => { - let fits = self.room.y + tolerance; - let (content, kept) = crate::contract::draft(&ctx, || self.measure_run(comp, at, cx, key.clone(), None), |took| took.y <= fits); - if kept { - content - } else { - self.given.1 = true; - self.measured_footer = self.footer_size.unwrap_or(Vec2::ZERO); - self.measure_run(comp, at, cx, key, Some(content)) - } - } - None => self.measure_run(comp, at, cx, key, None), + None if self.capped(&self.props, at.env, at.at) => self.measure_capped(comp, at, cx, plan), + None => self.measure_run(comp, at, cx, plan.key, None), }; - // A layer hung from an opener or a rect is at least as wide as its overlay asks for, in the measuring run too, - // so the rows of a content-sized list inside it are placed at that width. - let took = Vec2::new(overlay_of(&props).map_or(took.x, |overlay| took.x.max(crate::contract::overlay::anchor_floor(overlay))), took.y); - self.overflow = (took.x - self.room.x).max(0.0); - // A body wider than the room overflows it, or scrolls along it; either way the container keeps to the room. - Vec2::new(took.x.min(self.room.x), if vertical { took.y.min(self.room.y) } else { took.y }) + self.measured_took(took, vertical) } /// A real pass places the container by what its measuring run in this pass found: the record a measuring run of @@ -451,26 +337,7 @@ impl ShapeHooks for BodyHooks<'_> { // 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 { - 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, - strip: self.strip, - row: self.row, - 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)) - }; + let mut fresh = self.measuring_hooks(fading); crate::contract::run::measured_extent(comp, &mut fresh, at, &mut stage, style, shown); // The strips show in the pass whose content first overflows: the measuring run's content decides them. if let Some(extent) = fresh.extent.filter(|_| scroll_of(&props).is_some_and(|scroll| scroll.has_strips())) { @@ -689,459 +556,43 @@ impl ShapeHooks for BodyHooks<'_> { } } - #[expect( - clippy::cognitive_complexity, - reason = "the body step of the pass: its sub-steps share locals and run in one order, so a split would pass them all through" - )] + /// The body step. The children of the header, the body, the end region and the footer run inside their own step + /// functions; between them this frame holds only the `BodyPlan` the regions share. fn content(&mut self, comp: &mut C, ui: &mut Ui, env: &Env, cx: &mut Cx<'_, C>, values: &AppValues) { 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(_)); - let scroll = scroll_of(&props); - let pad = self.pads(&props, &env.tokens); - let inner = cx.core.content_rect.shrink2(pad); - let room = self.room_size(rect, inner); - let mut regions = self.regions(&props, inner, pad, room, rtl, self.measured_sizes()); - let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_))); - let band_slot = ui.painter().add(Shape::Noop); - // A measuring run lays out and measures: it registers no instance, focus body, scroll region or body layer, - // and claims no room in a parent flow. - let real = !ui.is_sizing_pass(); - // Only a container that declares its value a gate (a group box) gates its content; a radio group whose value - // is a bool does not. - // A mixed gate reads as off, and its check box shows the mixed face. - self.gate = cx.shown.as_deref().filter(|_| props.gates).and_then(|value| (value as &dyn Any).downcast_ref::()).copied(); - let gate_mixed = props.gates && cx.mixed; - self.gate = self.gate.or(gate_mixed.then_some(false)); - self.gate_at_read = self.gate; - let window = window_instance(&props, id).filter(|window| *window != id); - if real { - register_instances(&ctx, &props, id, window); - } - let region_env = env.derive(|scoped| self.scope_regions(scoped, &props, cx, window, values, real)); - // The size and glyph role the container gives its children reach every region: header, body, end region and - // footer. - let region_env = if props.child_size.is_none() && props.child_glyphs.is_none() { - region_env - } else { - region_env.derive_local(|scoped| { - if let Some(size) = props.child_size { - scoped.size = size; - } - if let Some(role) = props.child_glyphs { - scoped.glyphs = role; - } - }) - }; - let body_id = sub(id, "body"); - let gap = Vec2::splat(gap_of(&env.tokens, props.body_gap)); - let owner = BodyOwner::new(cx.style, gap.y); - let frame = RegionFrame { id, rtl, node, env: ®ion_env, gap }; - let (resolved, env_view) = (cx.core.resolved, region_env.view()); - let mut open = self.open; - let mut gate = self.gate; - let mut close: Option = None; - let field_message = if props.label.is_some() { scope::last_message(&ctx, id) } else { None }; - // A measuring run finds the container's first line: the first child its header or body places in flow reports - // it (`layout::FirstLines`). - let (first_header, first_body) = (sub(id, "first_header"), sub(id, "first_body")); - if !real { - layout::open_first_lines(&ctx, &[first_header, first_body]); - } + let mut plan = self.plan_content(&props, ui, env, cx, values); // B1 header if props.header.is_some() { - let header_parts = Self::header_parts(comp, ui, env, cx); - // The stops of the parts at the header's end edge come after the header's children. - let after_header = std::mem::take(&mut cx.core.header_stops); - let mut bcx = BodyCx::new(body_id, env_view, resolved, regions.header, &mut *cx.core.memory, &mut open, gate.as_mut()) - .with_gate_mixed(gate_mixed) - .with_field_message(field_message.clone()) - .with_owner(owner); - let trailing = props.header.is_some_and(|header| header.trailing); - let inset = props.header.map_or(0.0, |header| pad_of(&env.tokens, header.inset)); - let header_env = (!real).then(|| region_env.derive_local(|scoped| scoped.first_line = Some(first_header))); - let header_frame = RegionFrame { env: header_env.as_ref().unwrap_or(®ion_env), ..frame }; - close = close.or(self.header_region(comp, ui, &mut bcx, &header_frame, regions.header, (trailing, inset, header_parts))); - for stop in after_header { - crate::runtime::focus::register_stop(&ctx, stop); - } + self.header_step(comp, ui, env, cx, &mut plan); } - let animated = props.collapse.is_some_and(|collapse| collapse.animated); - let is_open = open || (animated && self.presence.visible); - let enabled = gate.unwrap_or(true); - // What the body and the end region share: gate, roving group and commands. The body adds its arena, - // transform and scroll owner; the end region lies outside them. - let line_env = if enabled && props.roving.is_none() { - region_env.clone() - } else { - region_env.derive_local(|scoped| { - scoped.enabled &= enabled; - if props.roving.is_some() { - scoped.roving = Some(crate::contract::steps::body_group(id)); - } - }) - }; - let end_frame = RegionFrame { id, rtl, node, env: &line_env, gap }; - // 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. - let footer_env = if footer_in_end(&props) { region_env.derive_local(|scoped| scoped.content_column = true) } else { region_env.clone() }; - if real { - crate::runtime::focus::begin_body(&ctx); - } - // A stack is a content column where its width comes from its content: a content-sized stack in flow, or a - // held fill-width container. A stack given its width (a rect it is shown at, or a column's width it passes - // on) is a given column, so the width reaches down through nested stacks. - let content_column = !self.wide() && matches!(props.layout, layout::BodyLayout::Stack); - let layout_id = sub(id, "layout"); + self.line_step(&mut plan); // The body is measured in the line the real run gives it: what the header and the end region leave. The // measuring run places it once both have measured, so its end region runs first (its content never depends // on the body); the real run places it from what they took and keeps reading order. - if !real && is_open && props.end.is_some() { - let mut end_cx = BodyCx::new(body_id, line_env.view(), resolved, regions.end, &mut *cx.core.memory, &mut open, gate.as_mut()) - .with_field_message(field_message.clone()) - .with_owner(owner); - close = close.or(self.end_region(comp, ui, &mut end_cx, &end_frame, &props, regions.end, None)); + if !plan.real && plan.is_open && props.end.is_some() { + self.end_step(comp, ui, cx, &mut plan); } - let beside = - if real { self.measured_sizes() } else { RegionSizes { header: self.header_size, footer: self.measured_footer, end: self.end_size } }; - if !real { - let placed = self.regions(&props, inner, pad, room, rtl, beside); - (regions.body, regions.beside) = (placed.body, placed.beside); - } - let line = shared_line(&props, beside); - // A row given its height sets its line at the middle of its band: the line is as high as the band. - let line = if self.centres_line(&props) { Some(line.unwrap_or(0.0).max(regions.body.height())) } else { line }; // B2 label: the control gets the rect the label leaves; the label column adds to the container's extent. - let mut body_rect = regions.body; - let mut label_rect = Rect::NOTHING; - let mut label_input = None; - let mut caption = 0.0; - if let Some(side) = props.label.as_ref() { - let resolved = cx.core.resolved; - let input = LabelIn { - scope: id, - owner: id, - parent: node.then_some(id), - row: regions.body, - room: if self.sizing(&props) == Sizing::Content { - layout::ambient_room(&ctx).map_or(room.x, |offered| room.x.max(offered)) - } else { - regions.body.width() - }, - content_row: false, - text: resolved.label_value, - side, - help: props.help.as_ref(), - enabled: resolved.enabled, - size: resolved.size, - control_min: scope::measured_control_min(&ctx, id), - leaf: false, - in_column: self.in_column, - claims: false, - status: props.footer.is_some_and(|footer| footer.status), - trailing: Vec2::ZERO, - }; - let placed = label::run(ui, env, &input, None); - (body_rect, label_rect, caption) = (placed.control, placed.label, placed.caption); - label_input = Some(input); - } - // Where the body runs; a measuring run may move it once the control reported its minimum width. - let ran_top = body_rect.min.y; - let label_extra = label_extra_of(regions.body, body_rect, label_rect, rtl); - // The body's control shows an inside label in its slot, in the measuring run and the real run alike. - let inside = props.label.as_ref().and_then(|side| label::inside(env.view(), side, cx.core.resolved.enabled)); - // In an inspector the control beside its label fills the width the label leaves. - let cell_fills = props.label.as_ref().is_some_and(|side| side.layout == label::FieldLayout::Beside) - && env.values.get::() == label::LabelScheme::Inspector; - let body_env = line_env.derive_local(|scoped| { - let label_width = label_extra.x; - self.scope_body(scoped, &props, id, BodyScope { room, real, content_column, scroll, label_width, beside: regions.beside }); - scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held); - scoped.cell_fills = cell_fills; - // A scrolling body shows its first child wherever the view is: the container has no first line there. - scoped.first_line = (!real && scroll.is_none()).then_some(first_body); - }); + self.label_step(ui, env, cx, &mut plan); // B3 body, if open, under the body env; the gate is read after the header changed it. - if is_open { - let mut bcx = BodyCx::new(body_id, body_env.view(), resolved, body_rect, &mut *cx.core.memory, &mut open, gate.as_mut()) - .with_field_message(field_message.clone()) - .with_owner(owner); - // While the body opens or closes, it shows only the part of its last height that the presence reaches. - let reveal_clip = (animated && self.presence.t < 1.0).then(|| { - Rect::from_min_max( - body_rect.min, - Pos2::new(body_rect.max.x, body_rect.min.y + self.measured_body.map_or(0.0, |size| size.y) * self.presence.t), - ) - }); - let wide = self.wide(); - let columns = LabelColumns::of(&props, !wide && !self.held(&props, env)); - let (layout, body) = (&props.layout, &mut *self.body); - // The room a scrolling body's bars take under or beside its content this run: no part of the line. - let mut bars_inset = Vec2::ZERO; - let mut run = |parent: &mut Ui, at: Rect, bcx: &mut BodyCx<'_>| -> Option { - let mut body_ui = alloc::child(parent, { - let builder = UiBuilder::new().max_rect(at).layout(child::column_layout(rtl)).scope_id(body_id); - if node { access::with_parent(builder, id) } else { builder } - }); - style::set_item_spacing(&mut body_ui, gap); - if let Some(clip) = reveal_clip { - body_ui.set_clip_rect(clip.intersect(body_ui.clip_rect())); - } - let installed = Env::install_for(&body_ui, body_env.clone()); - let mut labels = LabelsFound::default(); - // The size the body took: a scrolling body takes the visible part of its content, since its region - // is a child that allocates nothing in `body_ui`. - let took = match scroll { - Some(scroll) => { - let off = self.offset; - let big = crate::contract::MAX_EXTENT; - let bar = scroll_bar_look(&body_env.tokens).thickness; - let last = Vec2::new(self.last_extent.0, self.last_extent.1); - let inset = overflow_inset(scroll, last, at.size(), bar); - let shows = view_within(scroll, last, at, self.strip); - let seen = Rect::from_min_max( - Pos2::new(if rtl { shows.min.x + inset.x } else { shows.min.x }, shows.min.y), - Pos2::new(if rtl { shows.max.x } else { shows.max.x - inset.x }, shows.max.y - inset.y), - ); - let (width, height) = - (if scroll.horizontal_on() { big } else { seen.width() }, if scroll.vertical_on() { big } else { seen.height() }); - let x = if scroll.horizontal_on() { off.x as f32 } else { 0.0 }; - let min_x = if rtl { seen.max.x - width + x } else { seen.min.x - x }; - let max = Rect::from_min_size(Pos2::new(min_x, seen.min.y - off.y as f32), Vec2::new(width, height)); - let layout_of = *body_ui.layout(); - let mut region_ui = - alloc::child(&mut body_ui, UiBuilder::new().scope_id(sub(id, "scroll_region")).layout(layout_of).max_rect(max)); - region_ui.set_clip_rect(shows.intersect(body_ui.clip_rect())); - // The view this pass shows, where this run lays the content out. - let shown = self.view_offset; - let shift = Vec2::new( - if scroll.horizontal_on() { (shown.x - off.x) as f32 * if rtl { -1.0 } else { 1.0 } } else { 0.0 }, - if scroll.vertical_on() { (shown.y - off.y) as f32 } else { 0.0 }, - ); - let view = crate::runtime::lazy::View { - owner: id, - rect: seen.translate(shift), - content: max, - axes: (scroll.horizontal_on(), scroll.vertical_on()), - rtl, - anchor: self.anchor.map(|anchor| anchor.child), - reveal: self.glide.map(|glide| glide.child), - }; - // Only the run that lays the content out for the view places its children; a measure lays it - // out for its own question. - let lays_out = real && !crate::runtime::measure::active(&ctx); - if lays_out { - crate::runtime::lazy::begin(&ctx, id); - } - 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_measured(&mut region_ui, &view_env, layout_id, layout, gap, line, |ui| { - shared_labels(ui, id, columns, room.x, self.settle.clone(), &mut labels, |ui| body(ui, bcx)) - }); - Env::restore(&ctx, region_env); - if lays_out { - crate::contract::run::close_bar_line(&ctx, id); - } - let extent = region_ui.min_rect().size(); - if lays_out { - let placed = crate::runtime::lazy::placed(&ctx, id); - let keeps = !self.scroll_bound && !self.follows_end; - follow_anchor( - &ctx, - (&placed, scroll, keeps), - (extent, seen.size()), - (&mut self.offset, self.offset_at_read), - &mut self.anchor, - ); - aim_glide(&mut self.glide, placed.reveal, shown, (extent, seen.size()), scroll); - if self.glide.is_some_and(|glide| glide.to != Some(Vec2::new(shown.x as f32, shown.y as f32))) { - repaint::request(&ctx); - } - } - if real { - crate::runtime::egui::widgets::note_scroll_region(&ctx, region_ui.clip_rect(), region_ui.min_rect().intersect(max)); - } - self.extent = Some(extent); - // Along an axis it scrolls the body took what the view shows; along the other it took its content. - bars_inset = overflow_inset(scroll, extent, at.size(), bar); - // Strips take their height from the view: a body that overflows takes all of its room. - let strips = strips_of(scroll, extent, at, self.strip).map_or(0.0, |(back, forward)| back.height() + forward.height()); - let took = extent + bars_inset + Vec2::new(0.0, strips); - Some(Vec2::new( - if scroll.horizontal_on() { took.x.min(at.width()) } else { took.x }, - if scroll.vertical_on() { took.y.min(at.height()) } else { took.y }, - )) - } - // 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, &body_env, layout_id, layout, gap, line, |ui| { - shared_labels(ui, id, columns, room.x, self.settle.clone(), &mut labels, |ui| body(ui, bcx)) - }); - natural.map(|width| Vec2::new(width, body_ui.min_rect().height())) - } - }; - Env::restore(&ctx, installed); - let took = took.unwrap_or_else(|| body_ui.min_rect().size()); - // A content-sized column of rows takes, in a measuring run, the width they take at its group's widest - // label: the rows measured before the widest one measured against a narrower column. - let stacked = matches!(layout, layout::BodyLayout::Stack) && !wide; - let took = match labels.extent.filter(|_| stacked && !real) { - Some(width) => Vec2::new(took.x.max(width), took.y), - None => took, - }; - // A content-sized body hands its rows' reaches on to the group around once its measure is known. - if !real && !wide { - self.reached = labels.reached.map(|reached| (reached, !matches!(layout, layout::BodyLayout::Stack))); - } - if !real { - self.unsettled = labels.unsettled; - } - Some(took) - }; - self.body_size = match props.transform { - // The measuring run lays the body out on the layer the real run shows it on. - Some(_) if !real => { - let builder = UiBuilder::new().layer_id(areas::body_layer(ui.layer_id(), id)).max_rect(body_rect); - run(&mut alloc::child(ui, builder), body_rect, &mut bcx) - } - Some(transform) => { - let parent = ui.layer_id(); - let layer = areas::body_layer(parent, id); - let tf = areas::body_transform(body_rect.min, transform.scale, transform.offset); - if props.arena { - crate::primitives::sensing::set_layer(&ctx, ArenaId::new(id), layer); - } - let forward = areas::Forward { root: id, sense: response::to_egui(cx.core.root_sense), rect: rect.intersect(ui.clip_rect()) }; - let body_layer = areas::BodyLayer { - parent, - layer, - transform: tf, - at: body_rect.min, - clip: body_rect.intersect(ui.clip_rect()), - forward: Some(forward), - }; - areas::show_body_layer(&ctx, body_layer, |area_ui| run(area_ui, body_rect, &mut bcx)) - } - None => run(ui, body_rect, &mut bcx), - }; - close = close.or(bcx.close_requested()); - // A measuring run decided the label before the control reported its minimum width: it decides again - // from the minimum this run recorded, so the extent it measures is the one the real run lays out. - let mut label_extra = label_extra; - if let (false, Some(input)) = (real, label_input.as_mut()) { - input.control_min = scope::open_control_min(&ctx, id); - // The footer starts under the control column this decision gives, not the one before the control - // reported its minimum. - let placed = label::control_after(ui, env, input); - (body_rect, label_rect, caption) = (placed.control, placed.label, placed.caption); - label_extra = label_extra_of(regions.body, body_rect, label_rect, rtl); - } - if let Some(size) = &mut self.body_size { - // A body beside its label in a content-sized column of rows reports how far it reaches past the label - // column, so that column's container measures its rows at the widest label. - let beside = |side: &&label::SideLabel| side.layout != label::FieldLayout::After && label_extra.x > 0.0 && label_extra.y <= 0.0; - if let (false, true, Some(side)) = (real, env.content.0, props.label.as_ref().filter(beside)) { - let column = if matches!(side.kind, label::LabelKind::Glyph(_)) { layout::GLYPHS } else { layout::LABELS }; - layout::report_beyond(&ctx, std::slice::from_ref(&column), label::label_gap(env) + size.x); - } - *size += label_extra; - // A caption above the control counts whole toward the container's width, so a row never narrows the - // field below it. - size.x = size.x.max(caption); - if let (false, true, Some(side)) = (real, env.content.0, props.label.as_ref()) { - label::report_after_reach(&ctx, env, side, (regions.body, body_rect), size.x); - } - } - self.view = Some(body_rect); - if real && props.end.is_some() { - let mut end_cx = BodyCx::new(body_id, line_env.view(), resolved, regions.end, &mut *cx.core.memory, &mut open, gate.as_mut()) - .with_field_message(field_message.clone()) - .with_owner(owner); - // The end region shares the body's line, above a scroll bar under the body: its children sit on the - // members' line, from the body's top (a label may stand above the body). - let mut end = regions.end; - let mut line = None; - if !end_full_height(&props) { - end.max.y = (end.max.y - bars_inset.y).max(end.min.y); - let down = body_rect.min.y - end.min.y; - line = layout::members_line(&ctx, layout_id).map(|line| RowLine { - centre: line.centre.map(|centre| centre + down), - height: line.height.map(|height| height + down), - ..line - }); - } - close = close.or(self.end_region(comp, ui, &mut end_cx, &end_frame, &props, end, line)); + if plan.is_open { + self.body_step(ui, env, cx, &mut plan); + self.after_body(ui, env, &mut plan); + if plan.real && props.end.is_some() { + self.end_step(comp, ui, cx, &mut plan); } } else { // A collapsed body keeps its last full size in layout memory, so opening it again places by that size // and asks for no discard pass. self.body_size = if props.collapse.is_some() { None } else { Some(Vec2::ZERO) }; } - // The label scope covers the body only: footer controls are not the field's controls. - // A measuring run registers no control, so it leaves the facts the real run records alone. - if props.label.is_some() { - if real { - scope::finish(&ctx, id, None); - } else { - scope::discard(&ctx, id); - } - } - if !real { - self.first_line = first_line_found(&ctx, (first_header, first_body), rect.min.y, body_rect.min.y - ran_top); - } + self.close_label(&mut plan); // B4 footer: under the control column of a label-scoped container, which starts where the label step put // the control. if props.footer.is_some() { - let (mut footer_rect, offset) = self.place_footer(&props, &mut regions, inner, body_rect, rtl); - // The region's size counts the rule's band, the gap and the inset (they are part of what the footer took), so - // the content starts below the band and the gap and stays the inset away from the sides and the foot. - let lead = props.footer.and_then(|footer| footer.gap).map_or(0.0, |gap| gap_of(&env.tokens, gap)); - let inset = props.footer.map_or(0.0, |footer| pad_of(&env.tokens, footer.inset)); - let (rule_over, rule_under) = if footer_rule_under(&props) { (0.0, self.rules.footer) } else { (self.rules.footer, 0.0) }; - footer_rect.min.y += rule_over + lead; - footer_rect.max.y = (footer_rect.max.y - inset - rule_under).max(footer_rect.min.y); - footer_rect.min.x += inset; - footer_rect.max.x = (footer_rect.max.x - inset).max(footer_rect.min.x); - let mut bcx = BodyCx::new(body_id, env_view, resolved, footer_rect, &mut *cx.core.memory, &mut open, gate.as_mut()) - .with_field_message(field_message) - .with_owner(owner); - let mut footer_ui = frame.region(ui, "footer", footer_rect); - let installed = Env::install_for(&footer_ui, footer_env); - comp.footer(&mut footer_ui, &mut bcx); - Env::restore(&ctx, installed); - close = close.or(bcx.close_requested()); - let mut took = self.region_size(&footer_ui); - // The footer's width counts from the container's edge, past the column it starts after. - if took.x > 0.0 { - took.x += offset + 2.0 * inset; - } - if took.y > 0.0 { - took.y += lead + inset; - } - took.y += self.rules.footer; - self.footer_size = Some(took); + self.footer_step(comp, ui, env, cx, &mut plan); } - self.open = open; - self.gate = gate; - if close.is_some() { - self.close = true; - self.reason = self.reason.or(close); - } - if is_open && scroll.is_some() { - self.paint_scroll_bars(ui, cx, &props, rtl, env); - } - // The surface at the final rect, then the rules. - if let Some(kind) = props.surface { - surface_slot.paint(&env.tokens, kind, rect, env.direction); - } - if let Some(fill) = props.header.and_then(|header| header.fill) { - let style = surface_style(&env.tokens, props.surface.unwrap_or(SurfaceKind::Panel)); - let radius = CornerRadius { sw: 0, se: 0, ..style.radius }; - ui.painter().set(band_slot, Shape::rect_filled(regions.header, radius, band_color(&env.tokens, fill))); - } - paint_rules(ui, env, ®ions); - paint_edge_rule(ui, &props, env, rect); + self.finish_content(ui, env, cx, &plan); } fn settle(&mut self, comp: &mut C, cx: &mut Cx<'_, C>) { @@ -1271,12 +722,40 @@ impl BodyHooks<'_> { key: MeasureKey, content: Option, ) -> Vec2 { - let props = Arc::clone(&self.props); - let (id, ctx) = (cx.core.id, at.ui.ctx().clone()); - let pad = 2.0 * self.pads(&props, at.scx.tokens); + let (layer, rect) = self.begin_measure_run(at, cx); + let mut values = AppValues::default(); + comp.content_env(cx, &mut values); + // A label group settles its columns before a measure inside stands: when a row of a body that shows at its + // measured width read a column narrower than the group's widest, the sweep is taken back and the content runs + // once more with the group opened at the widths the first sweep found. + if self.props.label_column { + let ctx = at.ui.ctx().clone(); + let (unsettled, _) = crate::contract::draft( + &ctx, + || { + self.sweep(comp, at, cx, (layer, rect), &values); + self.unsettled.take() + }, + Option::is_none, + ); + if let Some(widths) = unsettled { + (self.settle, self.reached) = (Some(widths), None); + self.sweep(comp, at, cx, (layer, rect), &values); + (self.settle, self.unsettled) = (None, None); + } + } else { + self.sweep(comp, at, cx, (layer, rect), &values); + } + self.end_measure_run(at, cx.core.id, key, content) + } + + /// Opens the measuring run of `cx`'s container: its rect at the room's start edge, which `cx` takes, and the layer + /// the run lays the regions out on. + fn begin_measure_run(&mut self, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> (areas::LayerKey, Rect) { + let (id, ctx) = (cx.core.id, at.ui.ctx()); #[cfg(feature = "testing")] - crate::runtime::measure::count_body(&ctx, id); - layout_memory::begin_measure(&ctx, id); + crate::runtime::measure::count_body(ctx, id); + layout_memory::begin_measure(ctx, id); self.reached = None; let available = match at.at { ShowAt::Rect(rect) => rect, @@ -1296,39 +775,34 @@ impl BodyHooks<'_> { cx.core.rect = rect; cx.core.flow = craft_behavior::Flow::new(rect, at.env.direction.is_rtl()); cx.core.content_rect = cx.core.flow.inset(cx.style.metrics().padding); - let layer = measure_layer(&props, id, at.ui); - let mut values = AppValues::default(); - comp.content_env(cx, &mut values); - let sweep = |hooks: &mut Self, comp: &mut C, cx: &mut Cx<'_, C>| { - let builder = UiBuilder::new().layer_id(layer).max_rect(rect).sizing_pass().invisible(); - // The regions take explicit scope ids under `id`, so every component in them gets the id the real run - // gives it and the records it leaves match. - let mut measure_ui = Ui::new(ctx.clone(), sub(id, "measure"), builder); - let installed = Env::install_for(&measure_ui, at.env.clone()); - >::content(hooks, comp, &mut measure_ui, at.env, cx, &values); - Env::restore(&ctx, installed); - }; - // A label group settles its columns before a measure inside stands: when a row of a body that shows at its - // measured width read a column narrower than the group's widest, the sweep is taken back and the content runs - // once more with the group opened at the widths the first sweep found. - if props.label_column { - let (unsettled, _) = crate::contract::draft( - &ctx, - || { - sweep(self, comp, cx); - self.unsettled.take() - }, - Option::is_none, - ); - if let Some(widths) = unsettled { - (self.settle, self.reached) = (Some(widths), None); - sweep(self, comp, cx); - (self.settle, self.unsettled) = (None, None); - } - } else { - sweep(self, comp, cx); - } - let record = |key: Id, took: Vec2| layout_memory::emit_record(&ctx, key, layout_memory::Measured::new(self.room, took)); + (measure_layer(&self.props, id, at.ui), rect) + } + + /// One sweep of the measuring run: the regions in an invisible sizing pass at `rect` on `layer`, as `content` runs + /// them. The regions take explicit scope ids under the container's id, so every component in them gets the id the + /// real run gives it and the records it leaves match. + fn sweep( + &mut self, + comp: &mut C, + at: &Measuring<'_, '_>, + cx: &mut Cx<'_, C>, + (layer, rect): (areas::LayerKey, Rect), + values: &AppValues, + ) { + let ctx = at.ui.ctx(); + let mut measure_ui = measure_ui(ctx, cx.core.id, layer, rect); + let installed = Env::install_for(&measure_ui, at.env.clone()); + >::content(self, comp, &mut measure_ui, at.env, cx, values); + Env::restore(ctx, installed); + } + + /// Closes the measuring run: the records of what the regions took, the reach of a content-sized body's rows, and + /// the regions' size with the padding. + fn end_measure_run(&mut self, at: &Measuring<'_, '_>, id: Id, key: MeasureKey, content: Option) -> Vec2 { + let props = Arc::clone(&self.props); + let ctx = at.ui.ctx(); + let pad = 2.0 * self.pads(&props, at.scx.tokens); + let record = |key: Id, took: Vec2| layout_memory::emit_record(ctx, key, layout_memory::Measured::new(self.room, took)); record(id, self.body_size.unwrap_or(Vec2::ZERO)); if let Some(first) = self.first_line { record(sub(id, "first"), Vec2::new(0.0, first)); @@ -1348,12 +822,927 @@ impl BodyHooks<'_> { let (body, [header, footer, end]) = (self.body_size.unwrap_or(Vec2::ZERO), [self.header_size, self.footer_size, self.end_size].map(Option::unwrap_or_default)); let outer = (self.regions_size(&props, body, header, footer, end) + pad).x; - reached.forward(&ctx, |columns, past| if row { outer - columns } else { past + outer - body.x }); + reached.forward(ctx, |columns, past| if row { outer - columns } else { past + outer - body.x }); } - layout_memory::end_measure(&ctx, id, key); + layout_memory::end_measure(ctx, id, key); let body = if self.open { self.body_size.unwrap_or(Vec2::ZERO) } else { Vec2::ZERO }; let (header, footer, end) = (self.header_size.unwrap_or(Vec2::ZERO), self.footer_size.unwrap_or(Vec2::ZERO), self.end_size.unwrap_or(Vec2::ZERO)); self.regions_size(&props, body, header, footer, end) + pad } } + +/// What the regions of one body step share: where they lie, the envs they run under and the label step's placement. +/// `content` holds it while the regions' children run. +struct BodyPlan<'p> { + props: &'p ContainerProps, + resolved: &'p Resolved<'p>, + owner: BodyOwner<'p>, + ctx: Context, + id: Id, + body_id: Id, + layout_id: Id, + rect: Rect, + rtl: bool, + node: bool, + /// Not a measuring run. + real: bool, + scroll: Option, + pad: Vec2, + inner: Rect, + room: Vec2, + gap: Vec2, + regions: Regions, + surface_slot: SurfaceSlot, + band_slot: ShapeIdx, + region_env: Env, + /// What the body and the end region share: gate, roving group and commands. + line_env: Env, + footer_env: Env, + body_env: Option, + open: bool, + gate: Option, + gate_mixed: bool, + close: Option, + field_message: Option<(Message, Tone)>, + /// The ids the measuring run's first lines of the header and the body report under. + first: (Id, Id), + animated: bool, + is_open: bool, + content_column: bool, + /// The body's shared line. + line: Option, + body_rect: Rect, + label_rect: Rect, + label_input: Option>, + caption: f32, + /// Where the body runs; a measuring run may move it once the control reported its minimum width. + ran_top: f32, + label_extra: Vec2, + /// The room a scrolling body's bars take under or beside its content this run: no part of the line. + bars_inset: Vec2, +} + +impl<'p> BodyPlan<'p> { + /// What a region's `BodyCx` takes of the container; `gate` for the header, whose gate check box shows the mixed state. + fn share(&self, gate: bool) -> RegionShare<'p> { + RegionShare { gate_mixed: gate && self.gate_mixed, field_message: self.field_message.clone(), owner: self.owner } + } + + fn frame(&self) -> RegionFrame<'_> { + RegionFrame { id: self.id, rtl: self.rtl, node: self.node, env: &self.region_env, gap: self.gap } + } +} + +/// What the body region's run reads of the plan, apart from the gate and open state its `BodyCx` holds. +struct BodyRun<'r> { + ctx: &'r Context, + id: Id, + body_id: Id, + layout_id: Id, + rtl: bool, + node: bool, + real: bool, + gap: Vec2, + room_x: f32, + scroll: Option, + layout: &'r layout::BodyLayout, + line: Option, + columns: LabelColumns, + env: &'r Env, + /// While the body opens or closes, it shows only the part of its last height that the presence reaches. + reveal_clip: Option, +} + +/// The region a scrolling body's content runs in, and what its run reads after the content. +struct ScrollRegion { + ui: Ui, + /// The env the content runs under, with the view, and the one it replaced in the region. + env: Env, + installed: Installed, + /// The part of the body the view shows, beside the bars. + seen: Rect, + /// The region's rect, as large as the scrolling axes allow. + max: Rect, + /// The view this pass shows. + shown: ScrollPos, + /// The bars' thickness. + bar: f32, + /// The run lays the content out for the view. + lays_out: bool, +} + +/// The `Ui` a measuring run lays a transformed body out in: on the body layer the real run shows it on. +fn measure_layer_ui(ui: &mut Ui, id: Id, body_rect: Rect) -> Ui { + alloc::child(ui, UiBuilder::new().layer_id(areas::body_layer(ui.layer_id(), id)).max_rect(body_rect)) +} + +/// The body region's `Ui` at `at` in `parent`, with the gap between its children and the clip of an opening body. +fn body_ui(run: &BodyRun<'_>, parent: &mut Ui, at: Rect) -> Ui { + let builder = UiBuilder::new().max_rect(at).layout(child::column_layout(run.rtl)).scope_id(run.body_id); + let mut body_ui = alloc::child(parent, if run.node { access::with_parent(builder, run.id) } else { builder }); + style::set_item_spacing(&mut body_ui, run.gap); + if let Some(clip) = run.reveal_clip { + body_ui.set_clip_rect(clip.intersect(body_ui.clip_rect())); + } + body_ui +} + +impl BodyHooks<'_> { + /// The regions and the envs the body step runs them under; registers the container's command instances. + // 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 plan_content<'p, 'a: 'p, C: Container>( + &mut self, + props: &'p ContainerProps, + ui: &mut Ui, + env: &Env, + cx: &mut Cx<'a, C>, + values: &AppValues, + ) -> BodyPlan<'p> { + 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(_)); + let scroll = scroll_of(props); + let pad = self.pads(props, &env.tokens); + let inner = cx.core.content_rect.shrink2(pad); + let room = self.room_size(rect, inner); + let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes()); + let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_))); + let band_slot = ui.painter().add(Shape::Noop); + // A measuring run lays out and measures: it registers no instance, focus body, scroll region or body layer, + // and claims no room in a parent flow. + let real = !ui.is_sizing_pass(); + // Only a container that declares its value a gate (a group box) gates its content; a radio group whose value + // is a bool does not. + // A mixed gate reads as off, and its check box shows the mixed face. + self.gate = cx.shown.as_deref().filter(|_| props.gates).and_then(|value| (value as &dyn Any).downcast_ref::()).copied(); + let gate_mixed = props.gates && cx.mixed; + self.gate = self.gate.or(gate_mixed.then_some(false)); + self.gate_at_read = self.gate; + let window = window_instance(props, id).filter(|window| *window != id); + if real { + register_instances(&ctx, props, id, window); + } + let region_env = env.derive(|scoped| self.scope_regions(scoped, props, cx, window, values, real)); + // The size and glyph role the container gives its children reach every region: header, body, end region and + // footer. + let region_env = if props.child_size.is_none() && props.child_glyphs.is_none() { + region_env + } else { + region_env.derive_local(|scoped| { + if let Some(size) = props.child_size { + scoped.size = size; + } + if let Some(role) = props.child_glyphs { + scoped.glyphs = role; + } + }) + }; + let gap = Vec2::splat(gap_of(&env.tokens, props.body_gap)); + let field_message = if props.label.is_some() { scope::last_message(&ctx, id) } else { None }; + // A measuring run finds the container's first line: the first child its header or body places in flow reports + // it (`layout::FirstLines`). + let first = (sub(id, "first_header"), sub(id, "first_body")); + if !real { + layout::open_first_lines(&ctx, &[first.0, first.1]); + } + BodyPlan { + props, + resolved: cx.core.resolved, + owner: BodyOwner::new(cx.style, gap.y), + id, + body_id: sub(id, "body"), + layout_id: sub(id, "layout"), + rect, + rtl, + node, + real, + scroll, + pad, + inner, + room, + gap, + regions, + surface_slot, + band_slot, + line_env: region_env.clone(), + footer_env: region_env.clone(), + region_env, + body_env: None, + open: self.open, + gate: self.gate, + gate_mixed, + close: None, + field_message, + first, + animated: false, + is_open: false, + content_column: false, + line: None, + body_rect: Rect::NOTHING, + label_rect: Rect::NOTHING, + label_input: None, + caption: 0.0, + ran_top: 0.0, + label_extra: Vec2::ZERO, + bars_inset: Vec2::ZERO, + ctx, + } + } + + /// B1: the header region, with the container's own header parts beside it. + fn header_step(&mut self, comp: &mut C, ui: &mut Ui, env: &Env, cx: &mut Cx<'_, C>, plan: &mut BodyPlan<'_>) { + let props = plan.props; + let header_parts = Self::header_parts(comp, ui, env, cx); + // The stops of the parts at the header's end edge come after the header's children. + let after_header = std::mem::take(&mut cx.core.header_stops); + let share = plan.share(true); + let mut bcx = BodyCx::new( + plan.body_id, + plan.region_env.view(), + plan.resolved, + plan.regions.header, + &mut *cx.core.memory, + &mut plan.open, + plan.gate.as_mut(), + Some(share), + ); + let trailing = props.header.is_some_and(|header| header.trailing); + let inset = props.header.map_or(0.0, |header| pad_of(&env.tokens, header.inset)); + let header_env = (!plan.real).then(|| plan.region_env.derive_local(|scoped| scoped.first_line = Some(plan.first.0))); + let frame = RegionFrame { id: plan.id, rtl: plan.rtl, node: plan.node, env: header_env.as_ref().unwrap_or(&plan.region_env), gap: plan.gap }; + let closed = self.header_region(comp, ui, &mut bcx, &frame, plan.regions.header, (trailing, inset, header_parts)); + plan.close = plan.close.or(closed); + for stop in after_header { + crate::runtime::focus::register_stop(&plan.ctx, stop); + } + } + + /// The env the body and the end region share, the footer's, and whether the body shows. + fn line_step(&mut self, plan: &mut BodyPlan<'_>) { + let props = plan.props; + plan.animated = props.collapse.is_some_and(|collapse| collapse.animated); + plan.is_open = plan.open || (plan.animated && self.presence.visible); + let enabled = plan.gate.unwrap_or(true); + // What the body and the end region share: gate, roving group and commands. The body adds its arena, + // transform and scroll owner; the end region lies outside them. + if !enabled || props.roving.is_some() { + let id = plan.id; + plan.line_env = plan.region_env.derive_local(|scoped| { + scoped.enabled &= enabled; + if props.roving.is_some() { + scoped.roving = Some(crate::contract::steps::body_group(id)); + } + }); + } + // 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. + if footer_in_end(props) { + plan.footer_env = plan.region_env.derive_local(|scoped| scoped.content_column = true); + } + if plan.real { + crate::runtime::focus::begin_body(&plan.ctx); + } + // A stack is a content column where its width comes from its content: a content-sized stack in flow, or a + // held fill-width container. A stack given its width (a rect it is shown at, or a column's width it passes + // on) is a given column, so the width reaches down through nested stacks. + plan.content_column = !self.wide() && matches!(props.layout, layout::BodyLayout::Stack); + } + + /// The end region: in the measuring run before the body, at the region's place; in the real run after it, on the + /// body's line. + fn end_step(&mut self, comp: &mut C, ui: &mut Ui, cx: &mut Cx<'_, C>, plan: &mut BodyPlan<'_>) { + let props = plan.props; + let share = plan.share(false); + let mut end_cx = BodyCx::new( + plan.body_id, + plan.line_env.view(), + plan.resolved, + plan.regions.end, + &mut *cx.core.memory, + &mut plan.open, + plan.gate.as_mut(), + Some(share), + ); + // The end region shares the body's line, above a scroll bar under the body: its children sit on the + // members' line, from the body's top (a label may stand above the body). + let mut end = plan.regions.end; + let mut line = None; + if plan.real && !end_full_height(props) { + end.max.y = (end.max.y - plan.bars_inset.y).max(end.min.y); + let down = plan.body_rect.min.y - end.min.y; + line = layout::members_line(&plan.ctx, plan.layout_id).map(|line| RowLine { + centre: line.centre.map(|centre| centre + down), + height: line.height.map(|height| height + down), + ..line + }); + } + let frame = RegionFrame { id: plan.id, rtl: plan.rtl, node: plan.node, env: &plan.line_env, gap: plan.gap }; + let closed = self.end_region(comp, ui, &mut end_cx, &frame, props, end, line); + plan.close = plan.close.or(closed); + } + + /// B2: the body's place beside the regions measured so far, the label step and the body's env. + // 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 label_step(&mut self, ui: &mut Ui, env: &Env, cx: &Cx<'_, C>, plan: &mut BodyPlan<'_>) { + let props = plan.props; + let (ctx, id, real) = (&plan.ctx, plan.id, plan.real); + let beside = + if real { self.measured_sizes() } else { RegionSizes { header: self.header_size, footer: self.measured_footer, end: self.end_size } }; + if !real { + let placed = self.regions(props, plan.inner, plan.pad, plan.room, plan.rtl, beside); + (plan.regions.body, plan.regions.beside) = (placed.body, placed.beside); + } + let line = shared_line(props, beside); + // A row given its height sets its line at the middle of its band: the line is as high as the band. + plan.line = if self.centres_line(props) { Some(line.unwrap_or(0.0).max(plan.regions.body.height())) } else { line }; + plan.body_rect = plan.regions.body; + if let Some(side) = props.label.as_ref() { + let resolved = plan.resolved; + let input = LabelIn { + scope: id, + owner: id, + parent: plan.node.then_some(id), + row: plan.regions.body, + room: if self.sizing(props) == Sizing::Content { + layout::ambient_room(ctx).map_or(plan.room.x, |offered| plan.room.x.max(offered)) + } else { + plan.regions.body.width() + }, + content_row: false, + text: resolved.label_value, + side, + help: props.help.as_ref(), + enabled: resolved.enabled, + size: resolved.size, + control_min: scope::measured_control_min(ctx, id), + leaf: false, + in_column: self.in_column, + claims: false, + status: props.footer.is_some_and(|footer| footer.status), + trailing: Vec2::ZERO, + }; + let placed = label::run(ui, env, &input, None); + (plan.body_rect, plan.label_rect, plan.caption) = (placed.control, placed.label, placed.caption); + plan.label_input = Some(input); + } + plan.ran_top = plan.body_rect.min.y; + plan.label_extra = label_extra_of(plan.regions.body, plan.body_rect, plan.label_rect, plan.rtl); + // The body's control shows an inside label in its slot, in the measuring run and the real run alike. + let inside = props.label.as_ref().and_then(|side| label::inside(env.view(), side, cx.core.resolved.enabled)); + // In an inspector the control beside its label fills the width the label leaves. + let cell_fills = props.label.as_ref().is_some_and(|side| side.layout == label::FieldLayout::Beside) + && env.values.get::() == label::LabelScheme::Inspector; + let (room, content_column, scroll, beside, label_width) = + (plan.room, plan.content_column, plan.scroll, plan.regions.beside, plan.label_extra.x); + let first_body = plan.first.1; + plan.body_env = Some(plan.line_env.derive_local(|scoped| { + self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside }); + scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held); + scoped.cell_fills = cell_fills; + // A scrolling body shows its first child wherever the view is: the container has no first line there. + scoped.first_line = (!real && scroll.is_none()).then_some(first_body); + })); + } + + /// B3: the body region, on the body layer when the container transforms its body. + #[expect(clippy::expect_used, reason = "the label step sets the body env before the body step")] + fn body_step(&mut self, ui: &mut Ui, env: &Env, cx: &mut Cx<'_, C>, plan: &mut BodyPlan<'_>) { + let props = plan.props; + let body_env = plan.body_env.as_ref().expect("the label step ran"); + let reveal_clip = (plan.animated && self.presence.t < 1.0).then(|| { + let body_rect = plan.body_rect; + Rect::from_min_max( + body_rect.min, + Pos2::new(body_rect.max.x, body_rect.min.y + self.measured_body.map_or(0.0, |size| size.y) * self.presence.t), + ) + }); + let run = BodyRun { + ctx: &plan.ctx, + id: plan.id, + body_id: plan.body_id, + layout_id: plan.layout_id, + rtl: plan.rtl, + node: plan.node, + real: plan.real, + gap: plan.gap, + room_x: plan.room.x, + scroll: plan.scroll, + layout: &props.layout, + line: plan.line, + columns: LabelColumns::of(props, !self.wide() && !self.held(props, env)), + env: body_env, + reveal_clip, + }; + let body_rect = plan.body_rect; + let share = plan.share(false); + let mut bcx = BodyCx::new( + plan.body_id, + body_env.view(), + plan.resolved, + body_rect, + &mut *cx.core.memory, + &mut plan.open, + plan.gate.as_mut(), + Some(share), + ); + let mut bars = Vec2::ZERO; + self.body_size = match props.transform { + Some(transform) => self.run_transformed(&run, ui, (transform, cx.core.root_sense, plan.rect, body_rect), &mut bcx, &mut bars), + None => self.run_body(&run, ui, body_rect, &mut bcx, &mut bars), + }; + plan.close = plan.close.or(bcx.close_requested()); + plan.bars_inset = bars; + } + + /// The body region on its own layer, under the container's transform. The measuring run lays the body out on the + /// layer the real run shows it on. + fn run_transformed( + &mut self, + run: &BodyRun<'_>, + ui: &mut Ui, + (transform, root_sense, rect, body_rect): (craft_behavior::CanvasTransform, craft_behavior::Sense, Rect, Rect), + bcx: &mut BodyCx<'_>, + bars: &mut Vec2, + ) -> Option { + if !run.real { + return self.run_body(run, &mut measure_layer_ui(ui, run.id, body_rect), body_rect, bcx, bars); + } + let parent = ui.layer_id(); + let layer = areas::body_layer(parent, run.id); + let tf = areas::body_transform(body_rect.min, transform.scale, transform.offset); + if self.props.arena { + crate::primitives::sensing::set_layer(run.ctx, ArenaId::new(run.id), layer); + } + let forward = areas::Forward { root: run.id, sense: response::to_egui(root_sense), rect: rect.intersect(ui.clip_rect()) }; + let body_layer = + areas::BodyLayer { parent, layer, transform: tf, at: body_rect.min, clip: body_rect.intersect(ui.clip_rect()), forward: Some(forward) }; + areas::show_body_layer(run.ctx, body_layer, |area_ui| self.run_body(run, area_ui, body_rect, bcx, bars)) + } + + /// The body region's run at `at` in `parent`: its `Ui`, its layout and the label columns its rows share. Returns + /// the size the body took. + fn run_body(&mut self, run: &BodyRun<'_>, parent: &mut Ui, at: Rect, bcx: &mut BodyCx<'_>, bars: &mut Vec2) -> Option { + let mut body_ui = body_ui(run, parent, at); + let installed = Env::install_for(&body_ui, run.env.clone()); + let mut labels = LabelsFound::default(); + // The size the body took: a scrolling body takes the visible part of its content, since its region is a + // child that allocates nothing in `body_ui`. + let took = match run.scroll { + Some(scroll) => self.run_scrolled(run, scroll, &mut body_ui, at, bcx, &mut labels, bars), + // A row that places its block itself asks for its children's width, not the room it spans. + None => { + let (body, settle) = (&mut *self.body, &self.settle); + let (_, natural) = layout::run_body_measured(&mut body_ui, run.env, run.layout_id, run.layout, run.gap, run.line, |ui| { + shared_labels(ui, run.id, run.columns, run.room_x, settle.clone(), &mut labels, |ui| body(ui, bcx)) + }); + natural.map(|width| Vec2::new(width, body_ui.min_rect().height())) + } + }; + Env::restore(run.ctx, installed); + let took = took.unwrap_or_else(|| body_ui.min_rect().size()); + self.body_took(run, took, labels) + } + + /// What the body took, as its container counts it, and what its rows found of the label columns. + fn body_took(&mut self, run: &BodyRun<'_>, took: Vec2, labels: LabelsFound) -> Option { + // A content-sized column of rows takes, in a measuring run, the width they take at its group's widest + // label: the rows measured before the widest one measured against a narrower column. + let wide = self.wide(); + let stacked = matches!(run.layout, layout::BodyLayout::Stack) && !wide; + let took = match labels.extent.filter(|_| stacked && !run.real) { + Some(width) => Vec2::new(took.x.max(width), took.y), + None => took, + }; + // A content-sized body hands its rows' reaches on to the group around once its measure is known. + if !run.real && !wide { + self.reached = labels.reached.map(|reached| (reached, !matches!(run.layout, layout::BodyLayout::Stack))); + } + if !run.real { + self.unsettled = labels.unsettled; + } + Some(took) + } + + /// A scrolling body's run: its content lies in a region of its own, offset by the view, and only the run that + /// lays the content out for the view places its children. Returns the visible part of what the content took. + #[allow(clippy::too_many_arguments, reason = "the body region's run, its scroll, its `Ui` and the three results it writes")] + // A scrolling body's second `Ui` and view; opt-level 2 inlines it into `run_body`, where every body would hold them. + #[inline(never)] + fn run_scrolled( + &mut self, + run: &BodyRun<'_>, + scroll: Scroll, + body_ui: &mut Ui, + at: Rect, + bcx: &mut BodyCx<'_>, + labels: &mut LabelsFound, + bars: &mut Vec2, + ) -> Option { + let mut region = self.scroll_region(run, scroll, body_ui, at); + let (body, settle) = (&mut *self.body, &self.settle); + layout::run_body_measured(&mut region.ui, ®ion.env, run.layout_id, run.layout, run.gap, run.line, |ui| { + shared_labels(ui, run.id, run.columns, run.room_x, settle.clone(), labels, |ui| body(ui, bcx)) + }); + self.scrolled(run, scroll, at, region, bars) + } + + /// The region a scrolling body's content lies in this run, and the view it shows. + fn scroll_region(&mut self, run: &BodyRun<'_>, scroll: Scroll, body_ui: &mut Ui, at: Rect) -> ScrollRegion { + let (ctx, id, rtl) = (run.ctx, run.id, run.rtl); + let off = self.offset; + let big = crate::contract::MAX_EXTENT; + let bar = scroll_bar_look(&run.env.tokens).thickness; + let last = Vec2::new(self.last_extent.0, self.last_extent.1); + let inset = overflow_inset(scroll, last, at.size(), bar); + let shows = view_within(scroll, last, at, self.strip); + let seen = Rect::from_min_max( + Pos2::new(if rtl { shows.min.x + inset.x } else { shows.min.x }, shows.min.y), + Pos2::new(if rtl { shows.max.x } else { shows.max.x - inset.x }, shows.max.y - inset.y), + ); + let (width, height) = (if scroll.horizontal_on() { big } else { seen.width() }, if scroll.vertical_on() { big } else { seen.height() }); + let x = if scroll.horizontal_on() { off.x as f32 } else { 0.0 }; + let min_x = if rtl { seen.max.x - width + x } else { seen.min.x - x }; + let max = Rect::from_min_size(Pos2::new(min_x, seen.min.y - off.y as f32), Vec2::new(width, height)); + let layout_of = *body_ui.layout(); + let mut region_ui = alloc::child(body_ui, UiBuilder::new().scope_id(sub(id, "scroll_region")).layout(layout_of).max_rect(max)); + region_ui.set_clip_rect(shows.intersect(body_ui.clip_rect())); + // The view this pass shows, where this run lays the content out. + let shown = self.view_offset; + let shift = Vec2::new( + if scroll.horizontal_on() { (shown.x - off.x) as f32 * if rtl { -1.0 } else { 1.0 } } else { 0.0 }, + if scroll.vertical_on() { (shown.y - off.y) as f32 } else { 0.0 }, + ); + let view = crate::runtime::lazy::View { + owner: id, + rect: seen.translate(shift), + content: max, + axes: (scroll.horizontal_on(), scroll.vertical_on()), + rtl, + anchor: self.anchor.map(|anchor| anchor.child), + reveal: self.glide.map(|glide| glide.child), + }; + // Only the run that lays the content out for the view places its children; a measure lays it out for its + // own question. + let lays_out = run.real && !crate::runtime::measure::active(ctx); + if lays_out { + crate::runtime::lazy::begin(ctx, id); + } + let env = run.env.derive_local(|scoped| scoped.lazy = Some(view)); + let installed = Env::install_for(®ion_ui, env.clone()); + ScrollRegion { ui: region_ui, env, installed, seen, max, shown, bar, lays_out } + } + + /// After a scrolling body's content ran: the anchor and glide follow what it placed, and the body takes what the + /// view shows of it. + fn scrolled(&mut self, run: &BodyRun<'_>, scroll: Scroll, at: Rect, region: ScrollRegion, bars: &mut Vec2) -> Option { + let (ctx, id) = (run.ctx, run.id); + let ScrollRegion { ui: region_ui, installed, seen, max, shown, bar, lays_out, .. } = region; + Env::restore(ctx, installed); + if lays_out { + crate::contract::run::close_bar_line(ctx, id); + } + let extent = region_ui.min_rect().size(); + if lays_out { + let placed = crate::runtime::lazy::placed(ctx, id); + let keeps = !self.scroll_bound && !self.follows_end; + follow_anchor(ctx, (&placed, scroll, keeps), (extent, seen.size()), (&mut self.offset, self.offset_at_read), &mut self.anchor); + aim_glide(&mut self.glide, placed.reveal, shown, (extent, seen.size()), scroll); + if self.glide.is_some_and(|glide| glide.to != Some(Vec2::new(shown.x as f32, shown.y as f32))) { + repaint::request(ctx); + } + } + if run.real { + crate::runtime::egui::widgets::note_scroll_region(ctx, region_ui.clip_rect(), region_ui.min_rect().intersect(max)); + } + self.extent = Some(extent); + // Along an axis it scrolls the body took what the view shows; along the other it took its content. + *bars = overflow_inset(scroll, extent, at.size(), bar); + // Strips take their height from the view: a body that overflows takes all of its room. + let strips = strips_of(scroll, extent, at, self.strip).map_or(0.0, |(back, forward)| back.height() + forward.height()); + let took = extent + *bars + Vec2::new(0.0, strips); + Some(Vec2::new( + if scroll.horizontal_on() { took.x.min(at.width()) } else { took.x }, + if scroll.vertical_on() { took.y.min(at.height()) } else { took.y }, + )) + } + + /// After the body: a measuring run decides the label again from the control's reported minimum, and the body's + /// size counts the label column. + fn after_body(&mut self, ui: &mut Ui, env: &Env, plan: &mut BodyPlan<'_>) { + let (props, ctx, real) = (plan.props, &plan.ctx, plan.real); + // A measuring run decided the label before the control reported its minimum width: it decides again + // from the minimum this run recorded, so the extent it measures is the one the real run lays out. + if let (false, Some(input)) = (real, plan.label_input.as_mut()) { + input.control_min = scope::open_control_min(ctx, plan.id); + // The footer starts under the control column this decision gives, not the one before the control + // reported its minimum. + let placed = label::control_after(ui, env, input); + (plan.body_rect, plan.label_rect, plan.caption) = (placed.control, placed.label, placed.caption); + plan.label_extra = label_extra_of(plan.regions.body, plan.body_rect, plan.label_rect, plan.rtl); + } + if let Some(size) = &mut self.body_size { + let label_extra = plan.label_extra; + // A body beside its label in a content-sized column of rows reports how far it reaches past the label + // column, so that column's container measures its rows at the widest label. + let beside = |side: &&label::SideLabel| side.layout != label::FieldLayout::After && label_extra.x > 0.0 && label_extra.y <= 0.0; + if let (false, true, Some(side)) = (real, env.content.0, props.label.as_ref().filter(beside)) { + let column = if matches!(side.kind, label::LabelKind::Glyph(_)) { layout::GLYPHS } else { layout::LABELS }; + layout::report_beyond(ctx, std::slice::from_ref(&column), label::label_gap(env) + size.x); + } + *size += label_extra; + // A caption above the control counts whole toward the container's width, so a row never narrows the + // field below it. + size.x = size.x.max(plan.caption); + if let (false, true, Some(side)) = (real, env.content.0, props.label.as_ref()) { + label::report_after_reach(ctx, env, side, (plan.regions.body, plan.body_rect), size.x); + } + } + self.view = Some(plan.body_rect); + } + + /// The label scope covers the body only: footer controls are not the field's controls. A measuring run registers + /// no control, so it leaves the facts the real run records alone; it finds the container's first line. + fn close_label(&mut self, plan: &mut BodyPlan<'_>) { + let (ctx, id) = (&plan.ctx, plan.id); + if plan.props.label.is_some() { + if plan.real { + scope::finish(ctx, id, None); + } else { + scope::discard(ctx, id); + } + } + if !plan.real { + self.first_line = first_line_found(ctx, plan.first, plan.rect.min.y, plan.body_rect.min.y - plan.ran_top); + } + } + + /// B4: the footer region. + fn footer_step(&mut self, comp: &mut C, ui: &mut Ui, env: &Env, cx: &mut Cx<'_, C>, plan: &mut BodyPlan<'_>) { + let props = plan.props; + let (mut footer_rect, offset) = self.place_footer(props, &mut plan.regions, plan.inner, plan.body_rect, plan.rtl); + // The region's size counts the rule's band, the gap and the inset (they are part of what the footer took), so + // the content starts below the band and the gap and stays the inset away from the sides and the foot. + let lead = props.footer.and_then(|footer| footer.gap).map_or(0.0, |gap| gap_of(&env.tokens, gap)); + let inset = props.footer.map_or(0.0, |footer| pad_of(&env.tokens, footer.inset)); + let (rule_over, rule_under) = if footer_rule_under(props) { (0.0, self.rules.footer) } else { (self.rules.footer, 0.0) }; + footer_rect.min.y += rule_over + lead; + footer_rect.max.y = (footer_rect.max.y - inset - rule_under).max(footer_rect.min.y); + footer_rect.min.x += inset; + footer_rect.max.x = (footer_rect.max.x - inset).max(footer_rect.min.x); + let mut footer_ui = plan.frame().region(ui, "footer", footer_rect); + let share = plan.share(false); + let mut bcx = BodyCx::new( + plan.body_id, + plan.region_env.view(), + plan.resolved, + footer_rect, + &mut *cx.core.memory, + &mut plan.open, + plan.gate.as_mut(), + Some(share), + ); + let installed = Env::install_for(&footer_ui, plan.footer_env.clone()); + comp.footer(&mut footer_ui, &mut bcx); + Env::restore(&plan.ctx, installed); + plan.close = plan.close.or(bcx.close_requested()); + let mut took = self.region_size(&footer_ui); + // The footer's width counts from the container's edge, past the column it starts after. + if took.x > 0.0 { + took.x += offset + 2.0 * inset; + } + if took.y > 0.0 { + took.y += lead + inset; + } + took.y += self.rules.footer; + self.footer_size = Some(took); + } + + /// The open and gate state the regions left, the scroll bars, the surface at the final rect and the rules. + // 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 finish_content(&mut self, ui: &mut Ui, env: &Env, cx: &Cx<'_, C>, plan: &BodyPlan<'_>) { + let props = plan.props; + self.open = plan.open; + self.gate = plan.gate; + if plan.close.is_some() { + self.close = true; + self.reason = self.reason.or(plan.close); + } + if plan.is_open && plan.scroll.is_some() { + self.paint_scroll_bars(ui, cx, props, plan.rtl, env); + } + // The surface at the final rect, then the rules. + if let Some(kind) = props.surface { + plan.surface_slot.paint(&env.tokens, kind, plan.rect, env.direction); + } + if let Some(fill) = props.header.and_then(|header| header.fill) { + let style = surface_style(&env.tokens, props.surface.unwrap_or(SurfaceKind::Panel)); + let radius = CornerRadius { sw: 0, se: 0, ..style.radius }; + ui.painter().set(plan.band_slot, Shape::rect_filled(plan.regions.header, radius, band_color(&env.tokens, fill))); + } + paint_rules(ui, env, &plan.regions); + paint_edge_rule(ui, props, env, plan.rect); + } +} + +/// The invisible sizing-pass `Ui` a measuring sweep of container `id` lays its regions out in. +fn measure_ui(ctx: &Context, id: Id, layer: areas::LayerKey, rect: Rect) -> Ui { + Ui::new(ctx.clone(), sub(id, "measure"), UiBuilder::new().layer_id(layer).max_rect(rect).sizing_pass().invisible()) +} + +/// What the room and reuse decision of a measuring run leaves for the run itself. +struct MeasurePlan { + ctx: Context, + id: Id, + /// The inputs the run's record is kept under. + key: MeasureKey, + tolerance: f32, + /// The body scrolls vertically: it takes at most the room's height. + vertical: bool, + /// The body shares a scrolling view along y. + scrolled_share: bool, + /// A record this pass or a kept transcript holds, and whether this pass's run left it. + reused: Option<(Vec2, bool)>, +} + +impl BodyHooks<'_> { + /// The room of a measuring run, and whether the body shares a scrolling view; `Err` with the extent when no run is + /// needed. + fn measure_room(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Result { + 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 { + Mount::Inline => true, + Mount::Pane(pane) => pane.content_height, + _ => false, + }; + if !flows && at.ui.is_sizing_pass() { + return Err(self.extent(comp, at.ui, 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) }; + self.open = open || self.shown_closed; + self.open_at_read = self.open; + // An animated collapse shows a share of the full body height, so the body is measured while any of it shows. + let shows = self.open || (props.collapse.is_some_and(|collapse| collapse.animated) && self.presence.visible); + self.presence = Presence { t: f32::from(u8::from(shows)), visible: shows, exiting: false }; + self.measured_body = None; + self.measured_header = None; + self.measured_footer = Vec2::ZERO; + self.measured_end = None; + self.measured_controls = None; + // The measuring run lays a scrolling body's content out at the width the real run of this pass gives it: beside + // the bars the kept content extent asks for, so the records it leaves serve that run. + self.last = BodyView::default(); + self.offset = ScrollPos::default(); + self.region_gap = gap_of(&at.env.tokens, Gap::Tight); + self.end_gap = gap_of(&at.env.tokens, props.end.map_or(Gap::Tight, |end| end.gap)); + self.header_gap = header_gap_of(&props, &at.env.tokens); + self.rules = RuleBands::of(&props, &at.env.tokens, crate::runtime::egui::scale::pixels_per_point(at.ui.ctx())); + 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), + }; + self.given = self.given_axes(&props, at.env, at.at); + self.fixed_height = self.fixed_height(&props, at.at); + self.passes = self.passes_width(&props, at.env, at.at); + self.held = self.held(&props, at.env); + self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(_))); + // A held container across its column measures at the column's width. + 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); + // 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); + // A container placed at an explicit rect, or mounted on a layer or in a window, is no flow child of that body: + // it takes its own room, not a share. + let flows = matches!(at.at, ShowAt::Flow) && self.in_flow(comp); + // 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 (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))) + { + return Err(Vec2::ZERO); + } + if let Some(share) = crate::layout::fill_share(at.ui, 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) { + self.room.y = share; + scrolled_share = scrolled_y; + } + // A body that fills both axes its parent gives it takes the room, whatever its contents take: a parent's + // measuring run does not run them. It measures them in its own real run. A share of a scrolling view is the + // least of what it takes: its content may be taller. + if at.ui.is_sizing_pass() && self.given == (true, true) && self.room.is_finite() && !scrolled_share { + return Err(self.room); + } + Ok(scrolled_share) + } + + /// Whether a record serves the measuring run of container `id` in the room `measure_room` set. + fn measure_plan(&mut self, at: &Measuring<'_, '_>, id: Id, scrolled_share: bool) -> MeasurePlan { + let props = Arc::clone(&self.props); + let ctx = at.ui.ctx().clone(); + let pad = 2.0 * self.pads(&props, at.scx.tokens); + let vertical = scroll_of(&props).is_some_and(|scroll| scroll.vertical_on()); + 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(at.env, at.width); + // In its column's second sweep a held container measures across the column: its first-sweep record is + // content-sized. + let reused = ((self.reuse || at.ui.is_sizing_pass()) && !(self.across && at.ui.is_sizing_pass())) + .then(|| { + let found = layout_memory::run_found(&ctx, id); + let serves = found || layout_memory::kept_serves(&ctx, id, &key); + serves.then(|| self.reusable(&props, &ctx, id, pad, tolerance)).flatten().map(|took| (took, found)) + }) + .flatten(); + MeasurePlan { ctx, id, key, tolerance, vertical, scrolled_share, reused } + } + + /// A record that serves: it stands for the run, and a kept one is noted under this run's inputs too. + fn take_reused(&mut self, at: &Measuring<'_, '_>, plan: MeasurePlan, (took, found): (Vec2, bool)) -> Vec2 { + let (ctx, id) = (&plan.ctx, plan.id); + if found { + layout_memory::kept_also_under(ctx, id, plan.key); + } + // A capped body whose content outgrew its room was laid out as given it: the record of its content says so. + if self.over_room(&self.props, at.env, at.at, ctx, id) { + self.given.1 = true; + } + took + } + + /// The measuring run of a share of a scrolling view: as given while the content fits it, else at its content. + fn measure_share(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>, plan: MeasurePlan) -> Vec2 { + let fits = self.room.y + plan.tolerance; + self.given.1 = false; + let (content, kept) = crate::contract::draft(&plan.ctx, || self.measure_run(comp, at, cx, plan.key.clone(), None), |took| took.y > fits); + self.given.1 = true; + if kept { content } else { self.measure_run(comp, at, cx, plan.key, None) } + } + + /// The measuring run of a capped body: its content height while that fits the room, else laid out as given the room. + fn measure_capped(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>, plan: MeasurePlan) -> Vec2 { + let fits = self.room.y + plan.tolerance; + let (content, kept) = crate::contract::draft(&plan.ctx, || self.measure_run(comp, at, cx, plan.key.clone(), None), |took| took.y <= fits); + if kept { + content + } else { + self.given.1 = true; + self.measured_footer = self.footer_size.unwrap_or(Vec2::ZERO); + self.measure_run(comp, at, cx, plan.key, Some(content)) + } + } + + /// The extent a measuring run reports from what its regions `took`. + fn measured_took(&mut self, took: Vec2, vertical: bool) -> Vec2 { + // A layer hung from an opener or a rect is at least as wide as its overlay asks for, in the measuring run too, + // so the rows of a content-sized list inside it are placed at that width. + let took = Vec2::new(overlay_of(&self.props).map_or(took.x, |overlay| took.x.max(crate::contract::overlay::anchor_floor(overlay))), took.y); + self.overflow = (took.x - self.room.x).max(0.0); + // A body wider than the room overflows it, or scrolls along it; either way the container keeps to the room. + Vec2::new(took.x.min(self.room.x), if vertical { took.y.min(self.room.y) } else { took.y }) + } +} + +impl BodyHooks<'_> { + /// The hooks of the measuring run a real pass runs: they start from what this run's `read` found, as the + /// measuring run of a sizing parent does. + fn measuring_hooks(&mut self, fading: bool) -> BodyHooks<'_> { + 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, + strip: self.strip, + row: self.row, + 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)) + } + } +} diff --git a/crates/ui-contract/src/contract/body/regions.rs b/crates/ui-contract/src/contract/body/regions.rs index 21266ae84..4f99974ff 100644 --- a/crates/ui-contract/src/contract/body/regions.rs +++ b/crates/ui-contract/src/contract/body/regions.rs @@ -566,20 +566,26 @@ pub(super) fn shared_labels( body: impl FnOnce(&mut Ui) -> R, ) -> R { match columns { - LabelColumns::Own => { - let (result, scoped) = ColumnGroup::scope_measured(ui, sub(id, "labels"), seed, |ui, group| { - group.offer(room); - body(ui) - }); - (found.extent, found.unsettled) = (scoped.extent, scoped.unsettled); - result - } - LabelColumns::Through { sized } => { - let (result, reached) = ColumnGroup::through(ui, sub(id, "through"), room, sized, body); - found.reached = reached; - result - } + LabelColumns::Own => own_labels(ui, id, (room, seed), found, body), + LabelColumns::Through { sized } => through_labels(ui, id, (room, sized), found, body), LabelColumns::Field => ColumnGroup::field(ui, body), LabelColumns::Apart => ColumnGroup::barrier(ui, body), } } + +/// The body's rows in a label group of their own, offered `room` and opened at the `seed` widths. +fn own_labels(ui: &mut Ui, id: Id, (room, seed): (f32, Option), found: &mut LabelsFound, body: impl FnOnce(&mut Ui) -> R) -> R { + let (result, scoped) = ColumnGroup::scope_measured(ui, sub(id, "labels"), seed, |ui, group| { + group.offer(room); + body(ui) + }); + (found.extent, found.unsettled) = (scoped.extent, scoped.unsettled); + result +} + +/// The body's rows in the label group around the container. +fn through_labels(ui: &mut Ui, id: Id, (room, sized): (f32, bool), found: &mut LabelsFound, body: impl FnOnce(&mut Ui) -> R) -> R { + let (result, reached) = ColumnGroup::through(ui, sub(id, "through"), room, sized, body); + found.reached = reached; + result +} diff --git a/crates/ui-contract/src/contract/cx.rs b/crates/ui-contract/src/contract/cx.rs index cb01fdca8..3af57cef5 100644 --- a/crates/ui-contract/src/contract/cx.rs +++ b/crates/ui-contract/src/contract/cx.rs @@ -18,7 +18,7 @@ mod words; pub use access::Accessible; pub use body::BodyCx; -pub(crate) use body::BodyOwner; +pub(crate) use body::{BodyOwner, RegionShare}; pub use context::{Activation, Cx, CxCore}; pub(crate) use context::{RecordedText, Under, child_env}; pub use edit::Edit; diff --git a/crates/ui-contract/src/contract/cx/body.rs b/crates/ui-contract/src/contract/cx/body.rs index c021c2ed4..8b050b88f 100644 --- a/crates/ui-contract/src/contract/cx/body.rs +++ b/crates/ui-contract/src/contract/cx/body.rs @@ -33,6 +33,7 @@ pub struct BodyCx<'a> { } impl<'a> BodyCx<'a> { + #[allow(clippy::too_many_arguments, reason = "one argument per field the region's context starts from")] pub(crate) fn new( id: Id, env: EnvView<'a>, @@ -41,9 +42,12 @@ impl<'a> BodyCx<'a> { memory: &'a mut MemoryStage, open: &'a mut bool, gate: Option<&'a mut bool>, + shared: Option>, ) -> Self { memory.claim(id); - BodyCx { id, env, resolved, rect, memory, open, gate, gate_mixed: false, close: None, field_message: None, owner: None } + let (gate_mixed, field_message, owner) = + shared.map_or((false, None, None), |shared| (shared.gate_mixed, shared.field_message, Some(shared.owner))); + BodyCx { id, env, resolved, rect, memory, open, gate, gate_mixed, close: None, field_message, owner } } /// Asks the platform to open `url`, in a new tab where the platform has tabs and `new_tab` is set: the opener @@ -61,16 +65,6 @@ impl<'a> BodyCx<'a> { self.env.host()?.files().take_answer(ticket) } - pub(crate) fn with_gate_mixed(mut self, mixed: bool) -> Self { - self.gate_mixed = mixed; - self - } - - pub(crate) fn with_field_message(mut self, message: Option<(Message, craft_theme::variant::Tone)>) -> Self { - self.field_message = message; - self - } - /// The validity message of the first control in the container's label scope, recorded last frame, with the /// tone it shows in: a container whose footer declares `FooterRegion::status` shows it as its status text. `None` /// when the container has no label or no control reported one. @@ -147,13 +141,25 @@ impl<'a> BodyCx<'a> { Some(&super::Under::new(under.0, under.1)), ); let show = Box::new(move |ui: &mut Ui, rect: Rect| { - let _ = - crate::contract::run::show_leaf(crate::contract::Props::id(content, content_id), ui, crate::contract::run::ShowAt::Rect(rect), None); + let _ = crate::contract::run::show_leaf( + &mut Some(crate::contract::Props::id(content, content_id)), + ui, + crate::contract::run::ShowAt::Rect(rect), + None, + ); }); label::flow_leaf(ui, (id, self.resolved.id), under, label, side, child, Some(label::Trailing { size, show })) } } +/// What a container's regions share in their `BodyCx`: whether its gate is mixed (the header's only), its field's +/// message and the container that owns them. +pub(crate) struct RegionShare<'a> { + pub gate_mixed: bool, + pub field_message: Option<(Message, craft_theme::variant::Tone)>, + pub owner: BodyOwner<'a>, +} + /// What a container's body reads of its container: the style step 2 resolved for this pass, and the body gap. #[derive(Clone, Copy)] pub(crate) struct BodyOwner<'a> { @@ -169,11 +175,6 @@ impl<'a> BodyOwner<'a> { } impl<'a> BodyCx<'a> { - pub(crate) fn with_owner(mut self, owner: BodyOwner<'a>) -> Self { - self.owner = Some(owner); - self - } - /// The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body /// reads what its container's style holds (a dock root's docking sizes). `None` when the body's container has /// another style type, and for a body with no container: a popup's body or a collection's empty state. diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 187ba8fb3..3cc1dc3a8 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -334,8 +334,9 @@ impl StageAccess for CxCore<'_> { /// ``` #[non_exhaustive] pub struct Cx<'a, C: Component> { + /// The pass core, which the pipeline builds once per run and lends to every step. #[doc(hidden)] - pub core: CxCore<'a>, + pub core: &'a mut CxCore<'a>, /// The component's cached style. pub style: &'a C::Style, /// The shown copy of the value, shared with shown memory. @@ -354,7 +355,7 @@ impl<'a, C: Component> Deref for Cx<'a, C> { type Target = CxCore<'a>; fn deref(&self) -> &CxCore<'a> { - &self.core + self.core } } diff --git a/crates/ui-contract/src/contract/items/hooks.rs b/crates/ui-contract/src/contract/items/hooks.rs index d2d16758c..a3621a601 100644 --- a/crates/ui-contract/src/contract/items/hooks.rs +++ b/crates/ui-contract/src/contract/items/hooks.rs @@ -752,7 +752,7 @@ impl ShapeHooks for ItemsHooks<'_, '_, C> { let mut empty_ui = alloc::child(ui, builder); 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); + let mut bcx = BodyCx::new(sub(id, "body"), view, resolved, rect, &mut *cx.core.memory, &mut open, None, None); comp.empty(&mut empty_ui, &mut bcx); Env::restore(&ctx, installed); } diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index c8dc3dacd..fde9fb47b 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -303,7 +303,8 @@ pub(crate) fn flow_leaf( if cut { ui.set_clip_rect(Rect::NOTHING); } - let output = crate::contract::run::show_leaf(crate::contract::Props::id(child, id), ui, crate::contract::run::ShowAt::Rect(control), None); + let output = + crate::contract::run::show_leaf(&mut Some(crate::contract::Props::id(child, id)), ui, crate::contract::run::ShowAt::Rect(control), None); if cut { ui.set_clip_rect(shown_clip); } @@ -325,7 +326,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(child, ui, crate::contract::run::ShowAt::Flow, None); + return crate::contract::run::show_leaf(&mut Some(child), ui, crate::contract::run::ShowAt::Flow, None); } let label = std::mem::take(&mut child.common_mut(crate::contract::Internal::new()).label); let facts = crate::contract::run::TypeFacts::of::(); diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index c756b6d3d..494a6eeaa 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -714,17 +714,17 @@ 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(self, ui, ShowAt::Rect(rect), None) + run::show_leaf(&mut Some(self), ui, ShowAt::Rect(rect), 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(self, ui, ShowAt::Flow, Some(Box::new(tip))) + run::show_leaf(&mut Some(self), ui, ShowAt::Flow, 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(self, ui, ShowAt::Rect(rect), Some(Box::new(tip))) + run::show_leaf(&mut Some(self), ui, ShowAt::Rect(rect), Some(Box::new(tip))) } /// Measures without allocating: steps 1 to 5 under the id `show` would use next. It registers no id, opens no @@ -738,18 +738,18 @@ 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, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - run::show_container(self, ui, ShowAt::Flow, body, None) + run::show_container(&mut Some(self), ui, ShowAt::Flow, 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, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - run::show_container(self, ui, ShowAt::Rect(rect), body, None) + run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), body, None) } /// Shows the container at `rect` and takes that rect's room in the flow of `ui`: what is shown after it lies /// past it, as after [`show`](Self::show). fn show_at_taking_room(self, ui: &mut Ui, rect: Rect, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R) -> Inner { - run::show_container_taking(self, ui, rect, body) + run::show_container_taking(&mut Some(self), ui, rect, body) } /// Measures the container with `body` without allocating: steps 1 to 5 under the id `show` would use next, with @@ -761,7 +761,7 @@ pub trait ShowContainer: Container + sealed::ShowContainer { /// Shows the container with rich tooltip content. fn show_with_tip(self, ui: &mut Ui, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui)) -> Inner { - run::show_container(self, ui, ShowAt::Flow, body, Some(Box::new(tip))) + run::show_container(&mut Some(self), ui, ShowAt::Flow, body, Some(Box::new(tip))) } /// Shows the container at `rect` with rich tooltip content. @@ -772,7 +772,7 @@ pub trait ShowContainer: Container + sealed::ShowContainer { body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: impl FnOnce(&mut Ui), ) -> Inner { - run::show_container(self, ui, ShowAt::Rect(rect), body, Some(Box::new(tip))) + run::show_container(&mut Some(self), ui, ShowAt::Rect(rect), body, Some(Box::new(tip))) } } @@ -780,7 +780,7 @@ pub trait ShowContainer: Container + sealed::ShowContainer { pub trait ShowCollection: Collection + sealed::ShowCollection { /// Shows the visible items of `source`, one `item` call each. fn show_items<'r>(self, ui: &mut Ui, source: &dyn ItemSource, item: &mut ItemFn<'r, Self>) -> Self::Output { - run::show_items(self, ui, source, item) + run::show_items(&mut Some(self), ui, source, item) } } diff --git a/crates/ui-contract/src/contract/overlay/popups.rs b/crates/ui-contract/src/contract/overlay/popups.rs index 4b3f4dbfe..f1195f436 100644 --- a/crates/ui-contract/src/contract/overlay/popups.rs +++ b/crates/ui-contract/src/contract/overlay/popups.rs @@ -214,7 +214,7 @@ impl PopupHandle { /// Toggles or opens the popup from `trigger` at step 9, as the pass's pending open change. pub fn trigger(self, trigger: Trigger, cx: &mut Cx<'_, C>) { debug_assert!(C::OVERLAYS, "`{}` hosts a popup but sets `OVERLAYS = false`", std::any::type_name::()); - self.registered(&cx.core); + self.registered(cx.core); let core = &mut cx.core; let ctx = core.ctx.clone(); let resting = core.response.hovered() || core.focus.visible; @@ -253,7 +253,7 @@ impl PopupHandle { /// Queues an open that step 15 writes. For `Trigger::Manual` this and the binding are the only ways it opens. pub fn open(self, cx: &mut Cx<'_, C>) { debug_assert!(C::OVERLAYS, "`{}` hosts a popup but sets `OVERLAYS = false`", std::any::type_name::()); - self.open_in(&cx.core); + self.open_in(cx.core); } pub(super) fn open_in(self, core: &CxCore<'_>) { @@ -264,7 +264,7 @@ impl PopupHandle { /// Queues a close; step 15 writes the slot, so this pass still shows the popup open. pub fn close(self, cx: &mut Cx<'_, C>) { debug_assert!(C::OVERLAYS, "`{}` hosts a popup but sets `OVERLAYS = false`", std::any::type_name::()); - self.close_in(&cx.core); + self.close_in(cx.core); } pub(super) fn close_in(self, core: &CxCore<'_>) { @@ -275,7 +275,7 @@ impl PopupHandle { /// Whether a toggle, `open` or `close` queued in this pass leaves the popup's open state different from the /// state the pass began with. Valid from step 9. pub fn changed(self, cx: &mut Cx<'_, C>) -> bool { - self.registered(&cx.core); + self.registered(cx.core); let began = cx.core.memory.shown::(self.id).0; open_now(cx.core.memory, self.id) != began } @@ -285,7 +285,7 @@ impl PopupHandle { /// open state that differs from the bound value is written to it. A value the bind refuses to take (a given one) /// never forces the popup. Returns whether the popup is open in this pass. pub fn bind_open(self, cx: &mut Cx<'_, C>, mut open: BindMut<'_, bool>) -> bool { - self.registered(&cx.core); + self.registered(cx.core); let began = cx.core.memory.shown::(self.id).0; let seen = cx.core.memory.session::(sub(self.id, "bound")).0.unwrap_or(began); let held = match open.read(cx) { @@ -314,7 +314,7 @@ impl PopupHandle { /// Whether the popup is open in this pass: valid from step 8, with the changes queued so far applied. pub fn is_open(self, cx: &mut Cx<'_, C>) -> bool { debug_assert!(C::OVERLAYS, "`{}` hosts a popup but sets `OVERLAYS = false`", std::any::type_name::()); - self.is_open_in(&mut cx.core) + self.is_open_in(cx.core) } pub(crate) fn is_open_in(self, core: &mut CxCore<'_>) -> bool { diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 2712ffe9c..db26e8ca6 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -200,7 +200,7 @@ impl PaintUi<'_> { let installed = Env::install_for(kids, env); // The child sits in a rect its owner chose, and the owner's own measure answers for it: no body's transcript // holds it. - let output = layout_memory::boundary(&ctx, true, || run::show_leaf(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), 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 848203587..e3541af0b 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -496,7 +496,7 @@ pub(crate) trait Erased { fn pass_extent(&mut self, at: &Measuring<'_, '_>) -> Vec2; /// Builds the component's `Cx` over `core` and `style` (what `style` gave), runs `rest` with it, then `finish`. /// `rest` returns whether a real pass ran. - fn with_cx<'a>(&mut self, core: CxCore<'a>, style: &'a dyn StyleView, rest: &mut dyn FnMut(&mut dyn ErasedPass<'a>) -> bool); + fn with_cx<'a>(&mut self, core: &'a mut CxCore<'a>, style: &'a dyn StyleView, rest: &mut dyn FnMut(&mut dyn ErasedPass<'a>) -> bool); fn shape(&self) -> ShapeKind; fn declares_parts(&self) -> bool; @@ -651,19 +651,6 @@ struct Pass<'p, 'r, 'a> { injected: Option, } -/// Steps 6 to 16, in the `Ui` the host gives, inside the component's focus scope. -fn pass(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, host_env: Option<&Env>) { - let scope = if p.sizing || ui.is_sizing_pass() { None } else { p.p.focus() }; - let (ctx, id) = (p.p.core_ref().ctx.clone(), p.resolved.id); - if let Some(policy) = scope { - focus::push_scope(&ctx, id, policy, None); - } - run_in_host(p, ui, host_at, host_env); - if scope.is_some() { - focus::pop_scope(&ctx); - } -} - /// A component wider than its room widens the flow `Ui` it was placed in, toward the end of the line. fn expand_for_overflow(ui: &mut Ui, at: ShowAt, rect: Rect, overflow: f32, rtl: bool) { if overflow > 0.0 && matches!(at, ShowAt::Flow) { @@ -850,15 +837,70 @@ fn create_node(ctx: &Context, ui: &Ui, id: Id, member: bool, role: Role) -> bool } } -/// Steps 6 to 16 of the pass, run in the `Ui` the host gives. -#[expect( - clippy::cognitive_complexity, - reason = "steps 6 to 16 in their fixed order; each step is already its own function and the rest is the order" -)] +/// Steps 6 to 16, in the `Ui` the host gives, inside the component's focus scope. Children run inside the overlay +/// step, `paint`, the content and `paint_over`; each step group is its own function, so during a child's run this +/// level keeps only `HostStep` on the stack. 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) { + update_steps(p, &h); + overlay_step(p, ui, env, &h); + state_steps(p, ui, env, &h); + paint_step(p, ui, env, &mut h); + content_step(p, ui, env, &h); + paint_over_step(p, ui, env, &h); + report_steps(p, ui, env, &h); + } + if let Some(ctx) = scope { + focus::pop_scope(&ctx); + } +} + +/// Opens the component's focus scope, outside a sizing pass. Returns the context to close it with. +fn enter_scope(p: &Pass<'_, '_, '_>, ui: &Ui) -> Option { + let policy = if p.sizing || ui.is_sizing_pass() { None } else { p.p.focus() }; + policy.map(|policy| { + let ctx = p.p.core_ref().ctx.clone(); + focus::push_scope(&ctx, p.resolved.id, policy, None); + ctx + }) +} + +/// What steps 9 to 16 of one pass read of steps 6 to 8b. +struct HostStep { + ctx: Context, + id: Id, + /// The component's own direction: right to left unless its axis keeps its order. + rtl: bool, + rect: Rect, + /// The parts step 7 declared. + decls: super::cx::Decls, + text_keys: Option, + own: Sense, + member: Option, + node: bool, + /// The bar line whose rules wait for this member. + line: Option, + /// A bar's view cut the member: it shows nothing until the clip is restored. + cut: bool, + shown_clip: Rect, + inspected: bool, + /// The values `content_env` gave the content at step 13. + values: AppValues, + /// The clip around the component, and the clip inside its rect grown by its paint outset. + outer_clip: Rect, + inside: Rect, +} + +/// Steps 6 to 8b: place, parts, sense and the text part. `None` when the pass stops before 8b: a sizing pass, or an +/// 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 { let ctx = p.p.core_ref().ctx.clone(); let (id, rtl) = (p.resolved.id, p.env.direction.is_rtl()); - let (env, resolved, inert, facts, style) = (host_env.unwrap_or(p.env), p.resolved, p.inert, p.facts, p.style); + 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. @@ -877,7 +919,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h // The output words the value in a measuring run too, so what is measured beside the component holds it. let text = p.p.value_text(); *p.p.core_ref().value_text.borrow_mut() = text; - return; + return None; } p.real = true; let inspected = p.trace.recording() && inspect::open_element(ui, id, facts.name); @@ -1006,7 +1048,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h if inspected { inspect::close_element(&ctx, id, rect, rect); } - return; + return None; } // The popups the text part and `update` register start over for this pass. if facts.overlays { @@ -1025,6 +1067,32 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h super::text::run_selections(e.core(), &parts.text.selections); e.core().selections = parts.text.selections.iter().map(|decl| decl.part).collect(); } + Some(HostStep { + ctx, + id, + rtl, + rect, + decls: parts.decls, + text_keys, + own, + member, + node, + line, + cut, + shown_clip, + inspected, + values: AppValues::default(), + outer_clip: Rect::NOTHING, + inside: Rect::NOTHING, + }) +} + +/// Step 9, update, with the body's roving group, which registers after `update`. +// 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 update_steps(p: &mut Pass<'_, '_, '_>, h: &HostStep) { + let (facts, ctx, id, rtl) = (p.facts, &h.ctx, h.id, h.rtl); + let e = &mut *p.p; // 9 update p.trace.mark(Step::Update); e.gesture_gate(); @@ -1034,7 +1102,7 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h e.scrub_by_label(); e.update(); if cfg!(debug_assertions) { - let keys = text_keys.unwrap_or_else(|| e.keys()); + let keys = h.text_keys.unwrap_or_else(|| e.keys()); let held = |mv: NavMove| match keys.keep { focus::KeepKeys::BlockArrows => true, focus::KeepKeys::InlineArrows => matches!(mv, NavMove::Back | NavMove::Forward), @@ -1057,28 +1125,39 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h None => group, }; focus::register_group( - &ctx, + ctx, match core.roving_arrival { Some(arrival) => group.selected((arrival, None)), None => group, }, ); } - // 10 overlay +} + +/// Step 10, overlay: the component's popups show their content here. +fn overlay_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) { p.trace.mark(Step::Overlay); - if facts.overlays { - let core = e.core(); + if p.facts.overlays { + let (ctx, id) = (&h.ctx, h.id); + let core = p.p.core(); let open = overlay::open_map(&mut *core.memory, id); let parts = core .toggles .iter() .filter_map(|toggle| core.results.get(&(toggle.part.key, toggle.part.index)).map(|result| (toggle.part, result.rect))) .collect(); - let mut overlays = OverlayUi::new(&ctx, overlay::OverlayOwner { id, anchor: rect, parts }, &mut *ui, resolved, env.clone(), open); - e.overlay(&mut overlays); - overlay::apply_closes(&ctx, overlays.closed); + let mut overlays = OverlayUi::new(ctx, overlay::OverlayOwner { id, anchor: h.rect, parts }, &mut *ui, p.resolved, env.clone(), open); + p.p.overlay(&mut overlays); + overlay::apply_closes(ctx, overlays.closed); } - // What `update` and `overlay` left untaken goes back to the key service. +} + +/// Steps 11 (apply) and 12 (state), after what `update` and `overlay` left untaken goes back to the key service. +// 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 state_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) { + let (facts, resolved, style) = (p.facts, p.resolved, p.style); + let e = &mut *p.p; steps::after_update(e.core()); // 11 apply p.trace.mark(Step::Apply); @@ -1089,68 +1168,92 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h e.register_reset(); // 12 state p.trace.mark(Step::State); - let open = facts.overlays && overlay::popup_shown(&ctx, id); + let open = facts.overlays && overlay::popup_shown(&h.ctx, h.id); let expanded = e.expanded() == Some(true); steps::state(e, style, open, expanded, env.ink); if e.core_ref().state.flags.contains(crate::style::Flags::FOCUSED) { - commands::note_focus(&ctx, id, &env.commands); + commands::note_focus(&h.ctx, h.id, &env.commands); } - // 13 paint +} + +/// Step 13, paint: a composite's `paint` shows its children here. Leaves the clip inside the component's rect for +/// the content, and the values `content_env` gives it. +fn paint_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &mut HostStep) { p.trace.mark(Step::Paint); + let e = &mut *p.p; let fade = steps::fade(ui, env, e.core()); - let rule_from = line.filter(|_| facts.rule && !cut).map(|line| (line, steps::next_shape(ui))); - steps::paint_surface(ui, env, e.core_ref(), style); + let rule_from = h.line.filter(|_| p.facts.rule && !h.cut).map(|line| (line, steps::next_shape(ui))); + steps::paint_surface(ui, env, e.core_ref(), p.style); steps::paint_part_layers(ui, env, e.core_ref()); // Paint and content stay inside the rect (grown by the type's declared outset), however small the room is. - let outer_clip = ui.clip_rect(); - let inside = e.core_ref().rect.expand(e.paint_outset(&env.tokens)).intersect(outer_clip); - ui.set_clip_rect(inside); + h.outer_clip = ui.clip_rect(); + h.inside = e.core_ref().rect.expand(e.paint_outset(&env.tokens)).intersect(h.outer_clip); + ui.set_clip_rect(h.inside); e.paint(ui, env); // The content's values may read what `paint` found this pass. - let mut values = AppValues::default(); - e.content_env(&mut values); + e.content_env(&mut h.values); steps::unfade(ui, e.core(), fade); - ui.set_clip_rect(outer_clip); - steps::paint_focus(ui, e.core_ref(), style); + ui.set_clip_rect(h.outer_clip); + steps::paint_focus(ui, e.core_ref(), p.style); // A rule a bar's view shows waits for the member after it. if let Some((line, from)) = rule_from { hold_rule(ui, line, from); } - ui.set_clip_rect(inside); - // 14 content, then `paint_over` - if p.trace.mark(Step::Content) { - if facts.role == Role::Merged { - scope::begin(&ctx, id, id, scope::Kind::Merge); - } - // A real run checks a body's content against the kept transcript its records came from; a collection's rows - // are its own measure, not the enclosing body's, and a layer's content is not part of its parent's flow. - let scoped = (!p.sizing && !crate::runtime::measure::active(&ctx)) - .then(|| match e.shape() { - ShapeKind::Body => Some((Some(id), !e.in_flow())), - ShapeKind::Item => Some((None, true)), - _ => None, - }) - .flatten(); - if let Some((body, boundary)) = scoped { - crate::runtime::layout_memory::open_content(&ctx, body, boundary); - } - e.content(ui, env, &values); - if scoped.is_some() { - crate::runtime::layout_memory::close_content(&ctx, &e.regions(id)); - } + ui.set_clip_rect(h.inside); +} + +/// Step 14, content: a body's regions or a collection's rows. +fn content_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) { + if !p.trace.mark(Step::Content) { + return; } - // The `over` parts are placed before `paint_over`, so the children it shows stack above them (8.3). - ui.set_clip_rect(outer_clip); - sensing::place_over_widgets(ui, id, member, decls); - ui.set_clip_rect(inside); + let (ctx, id) = (&h.ctx, h.id); + let e = &mut *p.p; + if p.facts.role == Role::Merged { + scope::begin(ctx, id, id, scope::Kind::Merge); + } + // A real run checks a body's content against the kept transcript its records came from; a collection's rows + // are its own measure, not the enclosing body's, and a layer's content is not part of its parent's flow. + let scoped = (!p.sizing && !crate::runtime::measure::active(ctx)) + .then(|| match e.shape() { + ShapeKind::Body => Some((Some(id), !e.in_flow())), + ShapeKind::Item => Some((None, true)), + _ => None, + }) + .flatten(); + if let Some((body, boundary)) = scoped { + crate::runtime::layout_memory::open_content(ctx, body, boundary); + } + e.content(ui, env, &h.values); + if scoped.is_some() { + crate::runtime::layout_memory::close_content(ctx, &e.regions(id)); + } +} + +/// `paint_over`, after the `over` parts are placed, so the children it shows stack above them (8.3). +fn paint_over_step(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) { + ui.set_clip_rect(h.outer_clip); + sensing::place_over_widgets(ui, h.id, h.member, h.decls.parts()); + ui.set_clip_rect(h.inside); + let e = &mut *p.p; let fade = steps::fade(ui, env, e.core()); e.paint_over(ui, env); steps::unfade(ui, e.core(), fade); - ui.set_clip_rect(outer_clip); + ui.set_clip_rect(h.outer_clip); +} + +/// Steps 15 (settle) and 16 (report, then the tooltip), and the activation step 17 fires. +// 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 report_steps(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, env: &Env, h: &HostStep) { + let (facts, resolved, style) = (p.facts, p.resolved, p.style); + let (ctx, id) = (&h.ctx, h.id); + let e = &mut *p.p; // 15 settle p.trace.mark(Step::Settle); e.settle(); let edit = e.settle_values(); + let leaf = e.shape() == ShapeKind::Leaf; steps::rerun_after_edit(e, style, edit, &MeasureIn { ui: &*ui, env: p.env, proposal: Proposal::Ideal, room: p.room }, resolved, leaf); // 16 report, then the tooltip. p.trace.mark(Step::Report); @@ -1158,33 +1261,33 @@ fn run_in_host(p: &mut Pass<'_, '_, '_>, ui: &mut Ui, host_at: Option, h e, facts, &steps::ReportIn { - node, - decls: &parts.decls, - sense: own, + node: h.node, + decls: &h.decls, + sense: h.own, live: e.live(), scrolls: e.scrolls(), expanded: e.expanded(), position: e.position(), - group: steps::member_group(&ctx, env.roving, id), + group: steps::member_group(ctx, env.roving, id), }, ); let shows_label = e.shows_label(); - tooltip::run(e.core_ref(), tooltip::TipIn { ui: &*ui, env, rich: p.tip.take(), parts: &parts.decls, shows_label, message }); + tooltip::run(e.core_ref(), tooltip::TipIn { ui: &*ui, env, rich: p.tip.take(), parts: &h.decls, shows_label, message }); // Activations accumulate across the passes of a viewport mount; step 17 fires the bound command once, with the // injected source when there is one. let natural = e.activated() && resolved.enabled; let injected = e.core().injected.take().filter(|_| resolved.enabled); if (natural || injected.is_some()) && !e.core_ref().keep_open { - crate::runtime::overlay::note_activated(&ctx, id); + crate::runtime::overlay::note_activated(ctx, id); } p.activated |= natural || injected.is_some(); p.injected = p.injected.or(injected); - if inspected { + if h.inspected { let core = e.core_ref(); - inspect::close_element(&ctx, id, core.rect, core.content_rect); + inspect::close_element(ctx, id, core.rect, core.content_rect); } - if cut { - ui.set_clip_rect(shown_clip); + if h.cut { + ui.set_clip_rect(h.shown_clip); } } @@ -1286,12 +1389,76 @@ pub(super) fn run(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, tip: Option>) { +/// 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); + let mut stage = begun.open_stage(t); + let mixed = value_step(t, &begun, &mut stage); + let resolved = begun.resolved(t); + let room = room_step(t, ui, at, &begun); + let extent = extent_step(t, ui, (at, mixed), (&begun, &resolved), &mut stage); + let sizes = measure_step(t, ui, at, (&begun, &resolved, &room), extent, &mut stage); + let real = run_passes(t, ui, at, tip, (&begun, &resolved, &sizes), &mut stage); + if real { + t.record(&mut stage, &begun.ctx, resolved.id); + } + if !begun.sizing { + stage.write_back(); + } +} + +/// What steps 1 to 4 found, which the rest of the run reads. +struct Begun { + ctx: Context, + facts: TypeFacts, + shape: ShapeKind, + /// The parent `Ui` is in egui's invisible sizing pass: steps 1 to 6 run and allocate the size, with no id + /// registration, sensing or memory writes. + sizing: bool, + /// The inspector records this run; read once per run. + recording: bool, + /// The env of the parent `Ui`, which the style reads. + env: Env, + /// The env with the component's own command instance, when it has one. + own_env: Option, + /// `Common`, moved out of the component; `Resolved` borrows it. + common: Common, + step1: steps::EnvStep, + style: Arc, + id: Id, +} + +impl Begun { + /// The env steps 4 to 17 run under. + fn env(&self) -> &Env { + self.own_env.as_ref().unwrap_or(&self.env) + } + + fn trace(&self) -> Trace<'_> { + Trace::new(&self.ctx, self.id, self.shape, self.recording) + } + + /// The memory stage of step 3: a copy in a sizing pass, the component's own stage otherwise. + fn open_stage(&self, t: &dyn Erased) -> MemoryStage { + if self.sizing { + MemoryStage::open_peek(&self.ctx, self.id) + } else { + MemoryStage::open_owned(&self.ctx, self.id, t.memory_owner().unwrap_or(self.id)) + } + } + + /// `Common` after step 1, with the padding the shape adds. + fn resolved(&self, t: &dyn Erased) -> Resolved<'_> { + Resolved { pad: t.pad(&self.env().tokens), ..steps::resolved(self.id, &self.step1, &self.common) } + } +} + +/// Steps 1 to 3: env, style and id. +// Kept out of the recursive frame above it: opt-level 2 inlines it there, so its locals stay on the stack while children run. +#[inline(never)] +fn begin(t: &mut dyn Erased, ui: &Ui) -> Begun { let ctx = ui.ctx().clone(); let facts = t.facts(); crate::runtime::measure::count_run(&ctx, facts.name); @@ -1304,32 +1471,64 @@ fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option bool { + let mixed = t.value(stage, begun.id, begun.step1.command.as_deref(), begun.sizing); + t.read(stage, begun.id, &begun.env); + begun.trace().mark(Step::Value); + mixed +} + +/// What step 5 found: the room, the measured size and the size the root takes. +struct Sizes { + /// The width the parent offers, which step 5 and step 7's measure view both read. + room: Option, + /// The size step 5 measured, before `sized` made it fill. + measured: Vec2, + /// The size the root takes in the parent `Ui`. + size: Vec2, + inert: bool, + /// The row around the leaf gave it no width: it takes no place in the flow (`layout::shrink_cap`). + dropped: bool, +} + +/// What step 5 reads of the room before the measuring run: the width the parent offers and the shrink step of the +/// body around. +#[derive(Clone, Copy)] +struct Room { + room: Option, + in_flow: bool, + fill_body: bool, + shrink: Option, + cap: Option, + dropped: bool, +} + +/// Step 5's room: what the parent offers, capped by the width the row around gave a leaf. +fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { + let (ctx, shape, id) = (&begun.ctx, begun.shape, begun.id); + let env = begun.env(); let room = match at { ShowAt::Rect(rect) => Some(rect.width()), // A measuring run in a content column asks for what the content needs: nothing there fills the room. Once the @@ -1337,7 +1536,7 @@ fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option match env.column { Some(ColumnSweep::Column(width)) if env.content_column && t.fills_width() => Some(width), _ => Some(crate::layout::flow_room(ui).x) - .filter(|width| width.is_finite() && !(env.content_column && crate::runtime::measure::active(&ctx))), + .filter(|width| width.is_finite() && !(env.content_column && crate::runtime::measure::active(ctx))), }, }; // A leaf or body in flow that does not fill takes part in the shrink step of the body around it: in a row that @@ -1348,7 +1547,7 @@ fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option crate::layout::shrink_cap(&ctx, row, id), + Some(crate::layout::Shrink::Apply(row)) if shape == ShapeKind::Leaf => crate::layout::shrink_cap(ctx, row, id), _ => None, }; let dropped = given.is_some_and(|given| given.dropped); @@ -1357,31 +1556,61 @@ fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option Some(room.map_or(cap, |room| room.min(cap))), None => room, }; + Room { room, in_flow, fill_body, shrink, cap, dropped } +} + +/// Step 5's extent: a sizing pass measures the shape from its content; in a real pass a body or item shape takes +/// what its measuring run found. A body's children run here, in its measuring run. +fn extent_step( + t: &mut dyn Erased, + ui: &Ui, + (at, mixed): (ShowAt, bool), + (begun, resolved): (&Begun, &Resolved<'_>), + stage: &mut MemoryStage, +) -> Vec2 { + let (ctx, facts, shape, sizing, id) = (&begun.ctx, &begun.facts, begun.shape, begun.sizing, begun.id); + let env = begun.env(); // A body root with parts steps its press machine before its measuring run, so the body reads this pass's part // presses in both runs (`BodyCx::part_press`). Step 8 finds the outcome. A member of another arena senses at step 8. if !sizing && shape == ShapeKind::Body && (facts.parts || t.declares_parts()) && (t.arena() || facts.text() || env.arena.is_none()) { - sensing::sense_early(&ctx, id, resolved.enabled); + sensing::sense_early(ctx, id, resolved.enabled); } - // Sizes come from this pass: a sizing pass measures the shape from its content; in a real pass a body or item - // shape takes what its measuring run found. - let extent = if sizing || matches!(shape, ShapeKind::Body | ShapeKind::Item) { - let measuring = Measuring { ui: &*ui, at, width: None, env, scx: &scx, resolved: &resolved, command: step1.command.clone(), mixed }; - if sizing { t.measured_extent(&measuring, &mut stage) } else { t.pass_extent(&measuring) } + 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 }; + if sizing { t.measured_extent(&measuring, stage) } else { t.pass_extent(&measuring) } } else { t.extent(ui, at, id, &scx) - }; + } +} + +/// Step 5's sizes from the `extent`, and what the rows and bodies around the component take from it. +// 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 measure_step( + t: &mut dyn Erased, + ui: &Ui, + at: ShowAt, + (begun, resolved, room): (&Begun, &Resolved<'_>, &Room), + extent: Vec2, + stage: &mut MemoryStage, +) -> Sizes { + let (ctx, facts, shape, sizing, id) = (&begun.ctx, &begun.facts, begun.shape, begun.sizing, begun.id); + let env = begun.env(); + let style = &*begun.style; + let Room { room, in_flow, fill_body, shrink, cap, dropped } = *room; let ask = |t: &mut dyn Erased, proposal: Proposal, room: Option, extent: Vec2| { - measured(t, &MeasureIn { ui: &*ui, env, proposal, room }, &*style, &resolved, extent) + measured(t, &MeasureIn { ui: &*ui, env, proposal, room }, style, resolved, extent) }; let (size, inputs) = ask(&mut *t, Proposal::Ideal, room, extent); let ideal = Call { proposal: Proposal::Ideal, room, inputs, took: size }; // A control in a label scope reports its narrowest width, in a measuring run too: the real run's label step reads // it to decide whether the row fits the label beside it. - let in_label = shape == ShapeKind::Leaf && scope::in_label(&ctx); + let in_label = shape == ShapeKind::Leaf && scope::in_label(ctx); // A leaf that fills the main axis of its body tells the body its least in the body's first sweep: its share never // cuts it below that (`layout::fill_size`). The call joins the body's transcript, which holds it while the inputs // hold. - let fills = |axis: craft_behavior::Axis| t.fills() == Some(axis) || common.sizing == Some(super::Sizing::Fill); + 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)); @@ -1394,7 +1623,7 @@ fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option reads::note(&ctx, key, id, measuring, &[ideal, Sample { proposal: Proposal::Min, room: None, took: min }]), - None => reads::note(&ctx, key, id, measuring, &[ideal]), + Some(min) => reads::note(ctx, key, id, measuring, &[ideal, Sample { proposal: Proposal::Min, room: None, took: min }]), + None => reads::note(ctx, key, id, measuring, &[ideal]), } } // In the least measure of a body every leaf in flow takes its least. In a stack a leaf wider than the stack's room @@ -1447,22 +1676,22 @@ fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option { // The `Ideal` size in no room, and the least width at which its content shows whole. - let input = MeasureIn { ui: &*ui, env, proposal: Proposal::Ideal, room: None }; - let (content, _) = t.measure_content(&input, &resolved); - let ideal = steps::measure(&*style, &input, content, Vec2::ZERO, &resolved).x; - let whole = steps::whole(&*style, content, Vec2::ZERO, &resolved); + let input = MeasureIn { ui, env, proposal: Proposal::Ideal, room: None }; + let (content, _) = t.measure_content(&input, resolved); + let ideal = steps::measure(style, &input, content, Vec2::ZERO, resolved).x; + let whole = steps::whole(style, content, Vec2::ZERO, resolved); let least = ask(&mut *t, Proposal::Min, None, Vec2::ZERO).0.x; - crate::layout::report_shrink(&ctx, row, id, size.x, ideal, Some((whole, least)), t.cut_first()); + crate::layout::report_shrink(ctx, row, id, size.x, ideal, Some((whole, least)), t.cut_first()); } - Some(crate::layout::Shrink::Count(row)) => crate::layout::report_shrink(&ctx, row, id, size.x, size.x, None, false), - Some(crate::layout::Shrink::Least(row)) if shape == ShapeKind::Body => crate::layout::report_least(&ctx, row, id, size.x), + Some(crate::layout::Shrink::Count(row)) => crate::layout::report_shrink(ctx, row, id, size.x, size.x, None, false), + Some(crate::layout::Shrink::Least(row)) if shape == ShapeKind::Body => crate::layout::report_least(ctx, row, id, size.x), _ => {} } // A body that fills the rest of a shrinking row needs at least its content: the row counts it at that width, so // the units narrow to leave it, and it takes what they leave. if let Some(crate::layout::Shrink::Count(row)) = env.shrink.filter(|_| fill_body) { let content = measured.x + t.overflow(); - crate::layout::report_shrink(&ctx, row, id, size.x.min(content), content, Some((content, content)), false); + crate::layout::report_shrink(ctx, row, id, size.x.min(content), content, Some((content, content)), false); } // A component shown at a rect fills it: the rect is its size, and a leaf that measures nothing (a content // painter) still shows there. @@ -1471,68 +1700,96 @@ fn run_steps(t: &mut dyn Erased, ui: &mut Ui, at: ShowAt, mut tip: Option !steps::guard(size, shape), }; if inert && size != Vec2::ZERO { - let now = crate::runtime::frame::clock(&ctx); + let now = crate::runtime::frame::clock(ctx); let log = stage.shown::(sub(id, "size_log")); if now - log.0 >= 1.0 || log.0 > now { log.0 = now; log::debug!("{} measured the size {size:?} and shows nothing", facts.name); } } - let mut core = blank_core(env.view(), &resolved, &mut stage, ctx.clone(), env.ink, steps::inert_response(ui, id), step1.command.clone()); - core.faded = facts.faded && !resolved.enabled; + Sizes { room, measured, size, inert, dropped } +} + +/// Steps 6 to 17 under the run's one `CxCore`, which lives in this frame: a sizing child that recurses inside step 5 +/// finds no core of its level on the stack. Returns whether a pass ran past the sizing check. +// Holds the run's `CxCore`, which opt-level 2 would merge into `run_steps`, on the stack of every measuring run below. +#[inline(never)] +fn run_passes( + t: &mut dyn Erased, + ui: &mut Ui, + at: ShowAt, + mut tip: Option>, + (begun, resolved, sizes): (&Begun, &Resolved<'_>, &Sizes), + stage: &mut MemoryStage, +) -> bool { + let env = begun.env(); + let id = resolved.id; + let mut core = blank_core(env.view(), resolved, stage, begun.ctx.clone(), env.ink, steps::inert_response(ui, id), begun.step1.command.clone()); + core.faded = begun.facts.faded && !resolved.enabled; // 6 to 16, in the host's `Ui`, once per call of the host. - let mut host = t.host(HostCx { ui: &*ui, env, id, label: &step1.label, size }); - let parent = ui.scope_id(); - let mut real_pass = false; - t.with_cx(core, &*style, &mut |e| { - let mut run = Pass { - p: &mut *e, - facts: &facts, - env, - style: &*style, - resolved: &resolved, - trace, - tip: tip.take(), - at, - room, - measured, - size, - parent, - inert: inert || dropped, - dropped, - sizing, - real: false, - activated: false, - injected: None, - }; - host.run(id, ui, env, &mut |host_ui, host_at, host_env| pass(&mut run, host_ui, host_at, host_env)); - let (real, activated, injected) = (run.real, run.activated, run.injected); - // A layer's dismissal is decided after its body so a field inside commits in the press pass; its open state is - // written here, after the report (the one write point outside step 15, besides `request_close`). - if real && let Some(why) = host.dismissed() { - e.dismissed(why); - } - // 17 finish, once: the stage is written back after `finish` returns, so writes made in `finish` are kept. - if real { - trace.mark(Step::Finish); - let changed = e.changed(); - steps::before_finish(e.core(), activated, injected, changed); - // A control painting text through its faces (a select, a segmented control) reports that baseline too. - let core = e.core_ref(); - let baseline = core.paint.borrow().baseline; - if baseline.is_some() || shape == ShapeKind::Leaf { - scope::record_line(&ctx, core.rect, baseline); - } - } - real_pass = real; + let mut host = t.host(HostCx { ui: &*ui, env, id, label: &begun.step1.label, size: sizes.size }); + let mut real = false; + t.with_cx(&mut core, &*begun.style, &mut |e| { + real = passes(e, &mut *host, ui, (at, tip.take()), (begun, resolved, sizes)); real }); - if real_pass { - t.record(&mut stage, &ctx, id); + real +} + +/// Steps 6 to 16 in each call of the host, then the dismissal and step 17. +fn passes<'a>( + e: &mut dyn ErasedPass<'a>, + host: &mut dyn Host, + ui: &mut Ui, + (at, tip): (ShowAt, Option>), + (begun, resolved, sizes): (&Begun, &Resolved<'_>, &Sizes), +) -> bool { + let mut run = Pass { + p: e, + facts: &begun.facts, + env: begun.env(), + style: &*begun.style, + resolved, + trace: begun.trace(), + tip, + at, + room: sizes.room, + measured: sizes.measured, + size: sizes.size, + parent: ui.scope_id(), + inert: sizes.inert || sizes.dropped, + dropped: sizes.dropped, + sizing: begun.sizing, + real: false, + activated: false, + injected: None, + }; + host.run(resolved.id, ui, begun.env(), &mut |host_ui, host_at, host_env| run_in_host(&mut run, host_ui, host_at, host_env)); + finish_passes(&mut run, &*host, begun) +} + +/// The dismissal and step 17 after the host's passes. Returns whether a pass ran past the sizing check. +fn finish_passes(run: &mut Pass<'_, '_, '_>, host: &dyn Host, begun: &Begun) -> bool { + let (real, activated, injected) = (run.real, run.activated, run.injected); + let e = &mut *run.p; + // A layer's dismissal is decided after its body so a field inside commits in the press pass; its open state is + // written here, after the report (the one write point outside step 15, besides `request_close`). + if real && let Some(why) = host.dismissed() { + e.dismissed(why); } - if !sizing { - stage.write_back(); + // 17 finish, once: the stage is written back after `finish` returns, so writes made in `finish` are kept. + if real { + run.trace.mark(Step::Finish); + let changed = e.changed(); + steps::before_finish(e.core(), activated, injected, changed); + // A control painting text through its faces (a select, a segmented control) reports that baseline too. + let core = e.core_ref(); + let baseline = core.paint.borrow().baseline; + if baseline.is_some() || begun.shape == ShapeKind::Leaf { + scope::record_line(&begun.ctx, core.rect, baseline); + } } + real } /// Measures the component in `t` as `show` will show it, without allocating: steps 1 to 5 under the id `show` would diff --git a/crates/ui-contract/src/contract/run/typed.rs b/crates/ui-contract/src/contract/run/typed.rs index d73675b9d..9394c9226 100644 --- a/crates/ui-contract/src/contract/run/typed.rs +++ b/crates/ui-contract/src/contract/run/typed.rs @@ -25,12 +25,20 @@ use egui::{Context, Id, Rect, Ui, Vec2}; use std::collections::HashMap; use std::sync::Arc; -/// The component a `Typed` holds: its own for a show, which `finish` consumes, or the caller's for a measure. +/// The component a `Typed` holds: the show's slot, which `finish` empties, or the caller's for a measure. The show +/// keeps the slot in its own frame, so the component is on the stack once while its children run. enum Held<'c, C> { - Owned(Option), + Owned(&'c mut Option), Lent(&'c mut C), } +/// The component in a show's slot. The caller of a show makes the slot from the component it shows, so the component +/// is on the stack once while its children run; `finish` takes it out. +#[expect(clippy::expect_used, reason = "a show's slot holds the component until `finish`")] +fn held(slot: &mut Option) -> &mut C { + slot.as_mut().expect("the show's slot holds the component") +} + /// The style step 2 stored for the later steps of the run. #[expect(clippy::expect_used, reason = "step 2 stores the style before any step that reads it")] fn step_style(style: &Option>) -> &S { @@ -78,6 +86,38 @@ impl<'c, 'h, C: Component> Typed<'c, 'h, C> { fn new(comp: Held<'c, C>, hooks: &'h mut dyn ShapeHooks) -> Self { Typed { comp, hooks, style: None, shown: None, mixed: false, cancelled: Vec::new(), output: None } } + + /// The `Typed` of a show, whose `finish` takes the component out of `slot`. + fn owned(slot: &'c mut Option, hooks: &'h mut dyn ShapeHooks) -> Self { + Self::new(Held::Owned(slot), hooks) + } + + /// The output `finish` made. + #[expect(clippy::expect_used, reason = "`super::run` runs every step, and the last one sets the output")] + fn output(self) -> C::Output { + self.output.expect("the pipeline finishes every run") + } + + /// The component's `Cx` over the run's `core`, with the value step 4 found. + #[expect(clippy::expect_used, reason = "`Erased::style` produced the style this pipeline now hands back, so its type is `C::Style`")] + fn cx<'a>(&mut self, core: &'a mut CxCore<'a>, style: &'a dyn StyleView) -> Cx<'a, C> { + let style = style.as_any().downcast_ref::().expect("the pipeline holds the style `Erased::style` gave"); + let events = std::mem::take(&mut self.cancelled); + // A cancel step 4 raised over a document that moved is reported, not applied: the app's value stays. One that + // carries the value the gesture began with restores it at step 11. + let applied = if events.iter().any(|event| matches!(event, EditEvent::Cancel { before: Some(_), .. })) { 0 } else { events.len() }; + Cx { core, style, shown: self.shown.take(), mixed: self.mixed, events, applied, validity: Validity::Ok } + } + + /// Step 17's `finish`: the component leaves `Typed` only now, after its children ran. + // Takes the component out after the children ran; opt-level 2 inlines it into `with_cx`, whose frame then holds a copy during them. + #[inline(never)] + fn finish(&mut self, cx: Cx<'_, C>, real: bool) { + let id = cx.core.id; + let output = self.comp.take().finish(cx); + debug_assert!(!real || crate::contract::Outcome::response(&output).id == id, "an output's Response is the component's own"); + self.output = Some(output); + } } impl Erased for Typed<'_, '_, C> { @@ -148,20 +188,10 @@ impl Erased for Typed<'_, '_, C> { self.hooks.pass_extent(self.comp.get(), at, style, self.shown.clone()) } - #[expect(clippy::expect_used, reason = "`Erased::style` produced the style this pipeline now hands back, so its type is `C::Style`")] - fn with_cx<'a>(&mut self, core: CxCore<'a>, style: &'a dyn StyleView, rest: &mut dyn FnMut(&mut dyn ErasedPass<'a>) -> bool) { - let style = style.as_any().downcast_ref::().expect("the pipeline holds the style `Erased::style` gave"); - let events = std::mem::take(&mut self.cancelled); - // A cancel step 4 raised over a document that moved is reported, not applied: the app's value stays. One that - // carries the value the gesture began with restores it at step 11. - let applied = if events.iter().any(|event| matches!(event, EditEvent::Cancel { before: Some(_), .. })) { 0 } else { events.len() }; - let mut cx = Cx:: { core, style, shown: self.shown.take(), mixed: self.mixed, events, applied, validity: Validity::Ok }; - let mut comp = self.comp.take(); - let real = rest(&mut TypedPass { comp: &mut comp, hooks: &mut *self.hooks, cx: &mut cx }); - let id = cx.core.id; - let output = comp.finish(cx); - debug_assert!(!real || crate::contract::Outcome::response(&output).id == id, "an output's Response is the component's own"); - self.output = Some(output); + fn with_cx<'a>(&mut self, core: &'a mut CxCore<'a>, style: &'a dyn StyleView, rest: &mut dyn FnMut(&mut dyn ErasedPass<'a>) -> bool) { + let mut cx = self.cx(core, style); + let real = rest(&mut TypedPass { comp: self.comp.get(), hooks: &mut *self.hooks, cx: &mut cx }); + self.finish(cx, real); } fn shape(&self) -> ShapeKind { @@ -230,11 +260,11 @@ struct TypedPass<'r, 'a, C: Component> { impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { fn core(&mut self) -> &mut CxCore<'a> { - &mut self.cx.core + self.cx.core } fn core_ref(&self) -> &CxCore<'a> { - &self.cx.core + self.cx.core } fn shown_state(&mut self) -> &mut steps::ShownState { @@ -341,11 +371,11 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { } fn paint(&mut self, ui: &mut Ui, env: &Env) { - self.comp.paint(&mut paint_ui(ui, env, &self.cx.core, self.cx.style), self.cx); + self.comp.paint(&mut paint_ui(ui, env, self.cx.core, self.cx.style), self.cx); } fn paint_over(&mut self, ui: &mut Ui, env: &Env) { - self.comp.paint_over(&mut paint_ui(ui, env, &self.cx.core, self.cx.style), self.cx); + self.comp.paint_over(&mut paint_ui(ui, env, self.cx.core, self.cx.style), self.cx); } fn settle_values(&mut self) -> steps::ValueEdit { @@ -479,13 +509,6 @@ impl<'a, C: Component> ErasedPass<'a> for TypedPass<'_, 'a, C> { } } -#[expect(clippy::expect_used, reason = "`super::run` runs every step, and the last one sets the output")] -fn run(comp: C, ui: &mut Ui, at: ShowAt, tip: Option>, hooks: &mut dyn ShapeHooks) -> C::Output { - let mut typed = Typed::new(Held::Owned(Some(comp)), hooks); - super::run(&mut typed, ui, at, tip); - typed.output.expect("the pipeline finishes every run") -} - fn measure_shape( comp: &mut C, ui: &Ui, @@ -498,36 +521,38 @@ fn measure_shape( } pub(crate) fn show_leaf>( - comp: C, + slot: &mut Option, ui: &mut Ui, at: ShowAt, tip: Option>, ) -> C::Output { - let scope = comp.common(Internal::new()).command_scope; - run(comp, ui, at, tip, &mut LeafHooks { scope }) + 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); + typed.output() } /// Shows a container at `rect` and takes the rect's room in the flow of `ui`, through the one helper that moves a /// parent's flow past a rect, so a sibling shown after it lies past it. pub(crate) fn show_container_taking( - comp: C, + slot: &mut Option, ui: &mut Ui, rect: Rect, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, ) -> Inner { - let shown = show_container(comp, ui, ShowAt::Rect(rect), body, None); + let shown = show_container(slot, ui, ShowAt::Rect(rect), body, None); crate::runtime::egui::alloc::advance_past(ui, rect); shown } pub(crate) fn show_container( - mut comp: C, + slot: &mut Option, ui: &mut Ui, at: ShowAt, mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>) -> R, tip: Option>, ) -> Inner { - if let Some(output) = unshown(&mut comp, ui) { + if let Some(output) = unshown(held(slot), ui) { return Inner { output, inner: None, settle: None }; } let mut inner: Option = None; @@ -537,11 +562,12 @@ pub(crate) fn show_container( ran |= !cx.memory.is_peek(); inner = Some(body(ui, cx)); }; - let ctx = ui.ctx().clone(); - let props = Arc::new(comp.props(Internal::new()).clone()); - let output = run(comp, ui, at, tip, &mut crate::contract::body::BodyHooks::new(&mut call, props)); + 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); + let output = typed.output(); let id = crate::contract::Outcome::response(&output).id; - let settle = ran.then(|| crate::contract::settle::SettleAt { ctx, body: sub(id, "body"), owner: id }); + let settle = ran.then(|| crate::contract::settle::SettleAt { ctx: ui.ctx().clone(), body: sub(id, "body"), owner: id }); Inner { output, inner, settle } } @@ -580,10 +606,18 @@ fn unshown(comp: &mut C, ui: &Ui) -> Option { Some(output) } -pub(crate) fn show_items<'r, C: Collection>(comp: C, ui: &mut Ui, source: &dyn ItemSource, item: &mut ItemFn<'r, C>) -> C::Output { - let view = comp.filtered(source, &Env::of(ui)); +pub(crate) fn show_items<'r, C: Collection>( + slot: &mut Option, + ui: &mut Ui, + source: &dyn ItemSource, + item: &mut ItemFn<'r, C>, +) -> C::Output { + let view = held(slot).filtered(source, &Env::of(ui)); let source = view.as_deref().unwrap_or(source); - run(comp, ui, ShowAt::Flow, None, &mut crate::contract::items::ItemsHooks::::new(source, item)) + 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); + typed.output() } /// Measures `comp` as `show` will show it, without allocating: steps 1 to 5 under the id `show` would use next. It @@ -610,8 +644,8 @@ pub(crate) fn measure_container( let mut call = |ui: &mut Ui, cx: &mut BodyCx<'_>| { body(ui, cx); }; - let props = Arc::new(comp.props(Internal::new()).clone()); - measure_shape(comp, ui, None, proposal, None, &mut crate::contract::body::BodyHooks::new(&mut call, props)) + let mut hooks = crate::contract::body::BodyHooks::of(comp, &mut call); + measure_shape(comp, ui, None, proposal, None, &mut hooks) } /// A measuring run's extent: the shape's `measured_extent` under a `Cx` that senses nothing and writes only to the @@ -625,8 +659,8 @@ pub(crate) fn measured_extent( shown: Option>>, ) -> (Vec2, Option>>) { let response = steps::inert_response(at.ui, at.resolved.id); - let core = blank_core(at.env.view(), at.resolved, stage, at.ui.ctx().clone(), at.env.ink, response, at.command.clone()); - let mut cx = Cx:: { core, style, shown, mixed: at.mixed, events: Vec::new(), applied: 0, validity: Validity::Ok }; + let mut core = blank_core(at.env.view(), at.resolved, stage, at.ui.ctx().clone(), at.env.ink, response, at.command.clone()); + let mut cx = Cx:: { core: &mut core, style, shown, mixed: at.mixed, events: Vec::new(), applied: 0, validity: Validity::Ok }; let ctx = at.ui.ctx(); let extent = reads::measuring(ctx, at.resolved.id, || steps::measuring(ctx, || hooks.measured_extent(comp, at, &mut cx))); (extent, cx.shown.take()) @@ -663,7 +697,7 @@ pub(crate) fn paint_face(ui: &mut Ui, env: &Env, source: &super::FaceSo core.content_rect = flow.inset(face.padding(rect, &style)); core.flow = flow; core.visible = rect; - let mut cx = Cx:: { core, style: &style, shown, mixed, events: Vec::new(), applied: 0, validity: Validity::Ok }; + let cx = Cx:: { core: &mut core, style: &style, shown, mixed, events: Vec::new(), applied: 0, validity: Validity::Ok }; // A face shows its own inputs as `steps::state` reads them for a component: a checked check box takes the on // look, a selected face the selected one. let flags = part_state.flags | source.flags | steps::value_flags(&face, &cx); @@ -672,7 +706,7 @@ pub(crate) fn paint_face(ui: &mut Ui, env: &Env, source: &super::FaceSo cx.core.state = state; cx.core.stated = true; cx.core.ink = steps::surface_ink(StyleView::surface(&*style), &state, env.ink); - steps::paint_surface(ui, env, &cx.core, &*style); + steps::paint_surface(ui, env, cx.core, &*style); { let results = HashMap::new(); let mut pui = PaintUi { @@ -840,7 +874,7 @@ pub(crate) fn member_show( core.press = sensed.press; core.member_of = Some(node.owner); core.intents = crate::runtime::keys::intents_of(&ctx, Some(id), rtl); - let mut cx = Cx:: { core, style: &style, shown, mixed, events: Vec::new(), applied: 0, validity: Validity::Ok }; + let mut cx = Cx:: { core: &mut core, style: &style, shown, mixed, events: Vec::new(), applied: 0, validity: Validity::Ok }; let flags = part_state.flags | steps::value_flags(&item, &cx); let on = f32::from(u8::from(flags.intersects(Flags::ON))); let state = StateSet::new(part_state.state, flags, crate::style::StateMix::new(part_state.t.hover, part_state.t.press, on)); @@ -851,22 +885,22 @@ pub(crate) fn member_show( // Paint stays inside the row grown by the type's declared outset, as a run's does; a faded member's veil fills it. let outer_clip = ui.clip_rect(); ui.set_clip_rect(row.expand(C::paint_outset(&env.tokens)).intersect(outer_clip)); - let fade = steps::fade(ui, env, &mut cx.core); - steps::paint_surface(ui, env, &cx.core, &*style); - steps::paint_part_layers(ui, env, &cx.core); - item.paint(&mut super::paint_ui(ui, env, &cx.core, &*style), &cx); - item.paint_over(&mut super::paint_ui(ui, env, &cx.core, &*style), &cx); - steps::unfade(ui, &mut cx.core, fade); + let fade = steps::fade(ui, env, cx.core); + steps::paint_surface(ui, env, cx.core, &*style); + steps::paint_part_layers(ui, env, cx.core); + item.paint(&mut super::paint_ui(ui, env, cx.core, &*style), &cx); + item.paint_over(&mut super::paint_ui(ui, env, cx.core, &*style), &cx); + steps::unfade(ui, cx.core, fade); ui.set_clip_rect(outer_clip); let mut access = Access::default(); item.access(&mut access, &cx); - let member_node = report_member(&cx.core, &access, node, C::ROLE); + let member_node = report_member(cx.core, &access, node, C::ROLE); { let paint = cx.core.paint.borrow(); - steps::report_parts(&cx.core, &decls, &access.nodes, &paint.faces, member_node); + steps::report_parts(cx.core, &decls, &access.nodes, &paint.faces, member_node); } - crate::contract::cx::write_cursor(&cx.core); - let tip = member_tip(&cx.core, &decls, node.part, tooltip, row); + crate::contract::cx::write_cursor(cx.core); + let tip = member_tip(cx.core, &decls, node.part, tooltip, row); MemberShown { output: item.finish(cx), tip } } diff --git a/crates/ui-contract/src/contract/steps/update.rs b/crates/ui-contract/src/contract/steps/update.rs index 372c9155d..9d4db0705 100644 --- a/crates/ui-contract/src/contract/steps/update.rs +++ b/crates/ui-contract/src/contract/steps/update.rs @@ -66,7 +66,7 @@ pub(crate) fn edit_intents(comp: &mut C, cx: &mut Cx<'_, C>) { } } let reset = cx.core.intents.take_reset(); - let double = double_click(&cx.core).filter(|_| !matches!(C::INPUT, Input::Text | Input::Editor)); + let double = double_click(cx.core).filter(|_| !matches!(C::INPUT, Input::Text | Input::Editor)); if reset.is_some() || double.is_some() { let part = match reset { Some(whole) => cx.core.active.filter(|_| !whole), diff --git a/crates/ui-contract/src/contract/text.rs b/crates/ui-contract/src/contract/text.rs index cb5a98056..5ba196b66 100644 --- a/crates/ui-contract/src/contract/text.rs +++ b/crates/ui-contract/src/contract/text.rs @@ -420,7 +420,7 @@ pub(crate) fn run( let read_only = cx.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) }; - let held = cx.popup(EDIT_MENU).is_open_in(&mut cx.core); + let held = cx.popup(EDIT_MENU).is_open_in(cx.core); serve_access(cx, &mut state, widget, &decl.shown, read_only); if std::mem::take(&mut state.select_all) { let len = state.draft.as_deref().unwrap_or(&decl.shown).chars().count(); diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 6540d6f42..da234377f 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -588,6 +588,11 @@ fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo .0 } +/// A child of `ui` with `layout`, built outside the generic sweeps that run a body in it. +fn laid_out_child(ui: &mut Ui, layout: egui::Layout) -> Ui { + ui.new_child(egui::UiBuilder::new().layout(layout)) +} + /// Whether a body given `axis` shares it among the children that fill it. fn shares_along(env: &Env, axis: Axis) -> bool { if axis == Axis::Y { !env.content.1 } else { !env.content.0 } @@ -626,7 +631,7 @@ fn share_sweep(ui: &mut Ui, env: &Env, id: Id, axis: Axis, share: Option fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layout, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Rect) { let ctx = ui.ctx().clone(); let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui) -> R| { - let mut child = ui.new_child(egui::UiBuilder::new().layout(layout)); + let mut child = laid_out_child(ui, layout); let inner = body(&mut child); (inner, child.min_rect()) }; @@ -637,7 +642,7 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: let along = |size: Vec2| if axis == Axis::Y { size.y } else { size.x }; let first = crate::contract::keeping_ids(&ctx, || { let (inner, rect, room) = { - let mut first = ui.new_child(egui::UiBuilder::new().layout(layout)); + let mut first = laid_out_child(ui, layout); let room = share_room(&first, axis); pass_state::with::(&ctx, |counts| counts.0.insert(id, 0)); let inner = share_sweep(&mut first, env, id, axis, None, body); @@ -1153,7 +1158,7 @@ fn run_grid(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec let (out, kept) = layout_memory::draft( &ctx, || { - let mut first = ui.new_child(egui::UiBuilder::new().layout(layout)); + let mut first = laid_out_child(ui, layout); let (inner, measured, short, unsettled) = sweep(&mut first, env, seed, columns, &|flow| cursor(columns, &none, flow).each_alone()); (inner, measured, first.min_rect(), short, unsettled) @@ -1333,106 +1338,137 @@ pub(crate) fn run_body_measured( // Each sweep of a measuring run finds the body's first line and an unwrapped row's line afresh. let target = env.first_line.filter(|_| sizing); let row = (sizing && matches!(layout, BodyLayout::Row { wrap: false, .. })).then_some(id); - let mut body = |ui: &mut Ui| { + let body = |ui: &mut Ui| { open_sweep(&ctx, target, row); body(ui) }; + // Each layout runs in its own function, so a body nested in bodies keeps only its own layout's frame on the stack. + let line = RowIn { id, gap, shared, sizing, rtl }; match layout { - BodyLayout::Stack => { - // Each leaf shows at most the stack's room, never below its least. - let env = env.derive_local(|scoped| scoped.shrink = Some(Shrink::Fit)); - let installed = Env::install_for(ui, env.clone()); - // 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() { - run_column(ui, &env, id, child::column_layout(rtl), body) - } else { - run_sharing(ui, &env, id, Axis::Y, child::column_layout(rtl), body) - }; - Env::restore(&ctx, installed); - (inner, None) - } - BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => { - 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.row_line = Some(line); - scoped.first_line = None; - }), - ); - let inner = run_spread(ui, id, gap.x, rtl, &mut body); - Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared); - inner - }); - inner - } - BodyLayout::Row { wrap: false, align: RowAlign::Start } => { - let room = ui.available_rect_before_wrap(); - let line = on_line(id, row_line(&ctx, sizing, id, shared), shared); - 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| { - scoped.row_room = Some(room.width()); - scoped.row_line = Some(line); - scoped.first_line = None; - }), - ); - let inner = run_shrinking(ui, id, &mut body); - Env::restore(&ctx, installed); - record_line(ui, sizing, id, shared); - inner - }); - (inner, None) - } - BodyLayout::Row { wrap, align } => { - let room = ui.available_rect_before_wrap(); - let rect = match *align { - RowAlign::Start | RowAlign::SpaceBetween => None, - 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() }; - // 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; - let lead = if *align == RowAlign::Center { spare / 2.0 } else { spare }; - Flow::new(room, rtl).take_start(lead).1.rect() - }) - } - }; - // A wrapped row has a line per wrap, so its children stay on the top of each, and its first child gives its - // first line. - let line = (!*wrap).then(|| on_line(id, row_line(&ctx, sizing, id, shared), shared)); - // Where its least is asked, a wrapping row is as narrow as its widest child at its least: every child on a - // 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; - if line.is_some() { - scoped.first_line = None; - } - }), - ); - let inner = if *wrap { body(ui) } else { run_shrinking(ui, id, &mut body) }; - Env::restore(&ctx, installed); - if !*wrap { - record_line(ui, sizing, id, shared); - } - inner - }); - if *align != RowAlign::Start { - found(&ctx, sizing, id, room.size(), took.size()); - } - (inner, (*align != RowAlign::Start).then(|| took.width())) - } + BodyLayout::Stack => (run_stack(ui, env, &line, body), None), + BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => run_spread_row(ui, env, &line, body), + BodyLayout::Row { wrap: false, align: RowAlign::Start } => (run_start_row(ui, env, &line, body), None), + BodyLayout::Row { wrap, align } => run_row(ui, env, &line, (*wrap, *align), body), BodyLayout::Grid { columns } => (run_grid(ui, env, id, columns, gap, body), None), } } + +/// What the layouts of `run_body_measured` read besides the env. +#[derive(Clone, Copy)] +struct RowIn { + id: Id, + gap: Vec2, + /// The line the body shares with its container's inline header or end region. + shared: Option, + sizing: bool, + rtl: bool, +} + +/// A `Stack` body: each leaf shows at most the stack's room, never below its least. +fn run_stack(ui: &mut Ui, env: &Env, at: &RowIn, body: impl FnMut(&mut Ui) -> R) -> R { + let ctx = ui.ctx().clone(); + let env = env.derive_local(|scoped| scoped.shrink = Some(Shrink::Fit)); + let installed = Env::install_for(ui, env.clone()); + // 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() { + 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) + }; + Env::restore(&ctx, installed); + inner +} + +/// An unwrapped `Row` that spreads its children over its room. +fn run_spread_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mut Ui) -> R) -> (R, Option) { + let ctx = ui.ctx().clone(); + 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.row_line = Some(line); + scoped.first_line = None; + }), + ); + let inner = run_spread(ui, id, gap.x, rtl, &mut body); + Env::restore(&ctx, installed); + record_line(ui, sizing, id, shared); + inner + }); + inner +} + +/// An unwrapped `Row` placed from its start, whose children share and shrink to its room. +fn run_start_row(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&mut Ui) -> R) -> R { + let ctx = ui.ctx().clone(); + 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; + }), + ); + let inner = run_shrinking(ui, id, &mut body); + Env::restore(&ctx, installed); + record_line(ui, sizing, id, shared); + inner + }) +} + +/// A wrapped `Row`, or one that places its block at its center or end: the width its children take at the gap alone +/// is what the body asks for. +fn run_row(ui: &mut Ui, env: &Env, at: &RowIn, (wrap, align): (bool, RowAlign), mut body: impl FnMut(&mut Ui) -> R) -> (R, Option) { + let ctx = ui.ctx().clone(); + let RowIn { id, shared, sizing, rtl, .. } = *at; + let room = ui.available_rect_before_wrap(); + let rect = match align { + RowAlign::Start | RowAlign::SpaceBetween => None, + 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() }; + // 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; + let lead = if align == RowAlign::Center { spare / 2.0 } else { spare }; + Flow::new(room, rtl).take_start(lead).1.rect() + }) + } + }; + // A wrapped row has a line per wrap, so its children stay on the top of each, and its first child gives its + // first line. + let line = (!wrap).then(|| on_line(id, row_line(&ctx, sizing, id, shared), shared)); + // Where its least is asked, a wrapping row is as narrow as its widest child at its least: every child on a + // 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; + if line.is_some() { + scoped.first_line = None; + } + }), + ); + let inner = if wrap { body(ui) } else { run_shrinking(ui, id, &mut body) }; + Env::restore(&ctx, installed); + if !wrap { + record_line(ui, sizing, id, shared); + } + inner + }); + if align != RowAlign::Start { + found(&ctx, sizing, id, room.size(), took.size()); + } + (inner, (align != RowAlign::Start).then(|| took.width())) +} diff --git a/crates/ui-contract/src/layout/column_group.rs b/crates/ui-contract/src/layout/column_group.rs index c9caf30e3..105f6af61 100644 --- a/crates/ui-contract/src/layout/column_group.rs +++ b/crates/ui-contract/src/layout/column_group.rs @@ -241,19 +241,27 @@ impl ColumnGroup { seed: Option, rows: impl FnOnce(&mut Ui, &mut ColumnGroup) -> R, ) -> (R, Scoped) { - let ctx = ui.ctx().clone(); - let id = sub(ui.scope_id(), key); - let depth = layout_memory::depth(&ctx); + let mut group = Self::open_scope(ui.ctx(), sub(ui.scope_id(), key), seed); + let result = rows(ui, &mut group); + (result, group.close_scope()) + } + + /// Opens the group `id` at its `seed` widths. Its rows run in the caller, between this and `close_scope`. + fn open_scope(ctx: &Context, id: Id, seed: Option) -> ColumnGroup { + let depth = layout_memory::depth(ctx); let widest = seed.unwrap_or_default(); - pass_state::with::(&ctx, |open| { + pass_state::with::(ctx, |open| { open.0.push(Frame::Group { id, widest, beyond: HashMap::new(), early: HashMap::new(), room: None, depth }); }); - let mut group = ColumnGroup { id, ctx: ctx.clone() }; - let result = rows(ui, &mut group); - let frame = pass_state::with::(&ctx, |open| open.0.pop()); + ColumnGroup { id, ctx: ctx.clone() } + } + + /// Closes the group `open_scope` opened: in a measuring run, what its rows found. + fn close_scope(&self) -> Scoped { + let frame = pass_state::with::(&self.ctx, |open| open.0.pop()); match frame { - Some(frame) if crate::runtime::measure::active(&ctx) => (result, close(&ctx, frame)), - _ => (result, Scoped::default()), + Some(frame) if crate::runtime::measure::active(&self.ctx) => close(&self.ctx, frame), + _ => Scoped::default(), } } @@ -337,21 +345,11 @@ impl ColumnGroup { /// measuring run returns how far the rows reached past the columns. pub(crate) fn through(ui: &mut Ui, id: Id, room: f32, sized: bool, rows: impl FnOnce(&mut Ui) -> R) -> (R, Option) { let ctx = ui.ctx().clone(); - if pass_state::with::(&ctx, |open| open.innermost(&[])).is_none() { + if !open_through(&ctx, id, room, sized) { return (Self::barrier(ui, rows), None); } - pass_state::with::(&ctx, |open| open.0.push(Frame::Through { id, beyond: HashMap::new(), room, sized })); let result = rows(ui); - let Some(Frame::Through { beyond, .. }) = pass_state::with::(&ctx, |open| open.0.pop()) else { return (result, None) }; - if !crate::runtime::measure::active(&ctx) || beyond.is_empty() { - return (result, None); - } - let reached = beyond.into_iter().filter_map(|(columns, past)| { - let (group, _) = pass_state::with::(&ctx, |open| open.innermost(&columns))?; - let width = columns.iter().map(|column| current_width(&ctx, group, column)).sum(); - Some((columns, width, past)) - }); - (result, Some(Reached(reached.collect()))) + (result, close_through(&ctx)) } /// Records the width the group's container was offered. A row that sits directly in the group decides whether @@ -454,3 +452,26 @@ fn current_width(ctx: &Context, group: Id, column: &ColumnKey) -> f32 { fn column_width(ctx: &Context, group: Id, column: &ColumnKey) -> Option { layout_memory::measured(ctx, sub(group, column)).map(|found| found.took.x) } + +/// Opens a `Frame::Through` for the rows of container `id` inside a group; `false` outside every group. +fn open_through(ctx: &Context, id: Id, room: f32, sized: bool) -> bool { + if pass_state::with::(ctx, |open| open.innermost(&[])).is_none() { + return false; + } + pass_state::with::(ctx, |open| open.0.push(Frame::Through { id, beyond: HashMap::new(), room, sized })); + true +} + +/// Closes the frame `open_through` opened: in a measuring run, how far its rows reached past the columns. +fn close_through(ctx: &Context) -> Option { + let Some(Frame::Through { beyond, .. }) = pass_state::with::(ctx, |open| open.0.pop()) else { return None }; + if !crate::runtime::measure::active(ctx) || beyond.is_empty() { + return None; + } + let reached = beyond.into_iter().filter_map(|(columns, past)| { + let (group, _) = pass_state::with::(ctx, |open| open.innermost(&columns))?; + let width = columns.iter().map(|column| current_width(ctx, group, column)).sum(); + Some((columns, width, past)) + }); + Some(Reached(reached.collect())) +} diff --git a/crates/ui-contract/src/primitives/surface.rs b/crates/ui-contract/src/primitives/surface.rs index f413687b0..d41ebde03 100644 --- a/crates/ui-contract/src/primitives/surface.rs +++ b/crates/ui-contract/src/primitives/surface.rs @@ -63,7 +63,7 @@ impl SurfaceSlot { } /// Paints the surface `kind` over `rect`. - pub(crate) fn paint(self, tokens: &UiTokens, kind: SurfaceKind, rect: Rect, direction: Direction) { + pub(crate) fn paint(&self, tokens: &UiTokens, kind: SurfaceKind, rect: Rect, direction: Direction) { let shapes = Surface::shapes(&surface_style(tokens, kind), None, rect, Corners::All, direction, self.painter.pixels_per_point()); self.painter.set(self.slot, Shape::Vec(shapes)); } diff --git a/crates/ui-contract/src/runtime/egui/child.rs b/crates/ui-contract/src/runtime/egui/child.rs index a5f1fd509..9831d7b7e 100644 --- a/crates/ui-contract/src/runtime/egui/child.rs +++ b/crates/ui-contract/src/runtime/egui/child.rs @@ -24,14 +24,20 @@ pub(crate) fn pinned_layout() -> Layout { /// Runs `body` in a child `Ui` with an explicit layout and returns what it produced with the rect the child /// took in `ui`. `rect` bounds the child; `None` gives it the rest of the parent. pub(crate) fn block(ui: &mut Ui, rect: Option, layout: Layout, body: impl FnOnce(&mut Ui) -> R) -> (R, Rect) { - let mut builder = UiBuilder::new().layout(layout); - if let Some(rect) = rect { - builder = builder.max_rect(rect); - } - let out = ui.scope_builder(builder, body); + let out = ui.scope_dyn(block_builder(rect, layout), Box::new(body)); (out.inner, out.response.rect) } +/// The builder of a `block`'s child, made outside the generic `block` so a body nested in blocks keeps one builder +/// per level on the stack. +fn block_builder(rect: Option, layout: Layout) -> UiBuilder { + let builder = UiBuilder::new().layout(layout); + match rect { + Some(rect) => builder.max_rect(rect), + None => builder, + } +} + /// The physical layout of a `Stack` or `Grid` body for `right_to_left`. pub(crate) fn column_layout(right_to_left: bool) -> Layout { stack_layout(right_to_left) diff --git a/crates/ui-contract/src/testing/layout.rs b/crates/ui-contract/src/testing/layout.rs index 977bda43f..4f6bbe796 100644 --- a/crates/ui-contract/src/testing/layout.rs +++ b/crates/ui-contract/src/testing/layout.rs @@ -119,7 +119,7 @@ impl Component for Block { } fn finish(self, cx: Cx<'_, Self>) -> Response { - cx.core.response + cx.response.clone() } } diff --git a/crates/ui-contract/tests/it/body/mod.rs b/crates/ui-contract/tests/it/body/mod.rs index bfc420b97..ef7344a76 100644 --- a/crates/ui-contract/tests/it/body/mod.rs +++ b/crates/ui-contract/tests/it/body/mod.rs @@ -1,4 +1,5 @@ //! The body step and the mount host: regions, scrolling, move and resize, and viewport mounts. mod mounts; +mod nesting; mod placement; diff --git a/crates/ui-contract/tests/it/body/nesting.rs b/crates/ui-contract/tests/it/body/nesting.rs new file mode 100644 index 000000000..b21f97a73 --- /dev/null +++ b/crates/ui-contract/tests/it/body/nesting.rs @@ -0,0 +1,39 @@ +//! Deep nesting: a component's run keeps only what it reads after its children on the stack. + +use craft_ui::contract::{Props as _, Show as _, ShowContainer as _}; +use craft_ui::layout::BodyLayout; +use craft_ui::testing::layout::Block; +use craft_ui::testing::{Frames, trial}; +use craft_ui_test_kit::contract::Panel; +use egui::{Ui, Vec2}; +use std::cell::Cell; + +/// Containers sixteen deep, rows inside stacks, show on a thread with a 512 KiB stack: their measuring runs and their +/// real runs both stay within it. +#[trial] +fn sixteen_nested_containers_show_on_a_512_kib_stack() { + let reached = std::thread::Builder::new() + .stack_size(512 * 1024) + .spawn(|| { + let reached = Cell::new(0); + let mut frames = Frames::new(); + frames.idle(2, |ui| nest(ui, 16, &reached)); + reached.get() + }) + .expect("the thread starts") + .join() + .expect("the frames run"); + assert!(reached > 0, "the innermost body ran"); +} + +fn nest(ui: &mut Ui, depth: usize, reached: &Cell) { + let layout = if depth.is_multiple_of(2) { BodyLayout::Stack } else { BodyLayout::row() }; + Panel::new().layout(layout).id_salt(depth).show(ui, |ui, _| { + if depth == 1 { + Block::new(Vec2::splat(10.0)).show(ui); + reached.set(reached.get() + 1); + } else { + nest(ui, depth - 1, reached); + } + }); +} diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index fe7b9fae5..b43344868 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -180,7 +180,7 @@ macro_rules! layout_component { } fn finish(self, cx: Cx<'_, Self>) -> Response { - cx.core.response + cx.response.clone() } }