From aae6c5a458e138aee1e579c2d41cd72f0c43d7c8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 20:15:40 +0000 Subject: [PATCH 01/15] Layout: a body's row line and grid cells are for its direct children only A component an app shows inside an egui container (an egui::Grid, ui.horizontal) in a Row or Grid body read the body's env up the Ui stack and was placed as one of the body's children: a labelled check box in an egui::Grid inside a full-width form row took a slot as high as the row's whole line, so every grid row was as tall as the block (PhotoCraft's Conditional Mode Change dialog), and a check box in ui.horizontal in a Grid body took the grid's cells. Env::installed_for says whether a Ui has an env entry of its own; row_line_of and grid_of give the row's line and the grid's cells only there. The spread row's sweeps install the row's env for the Ui its children run in. --- crates/ui-contract/src/contract/body/hooks.rs | 8 +-- crates/ui-contract/src/contract/body/size.rs | 18 +++-- crates/ui-contract/src/contract/lazy.rs | 2 +- crates/ui-contract/src/layout/body.rs | 43 ++++++++---- crates/ui-contract/src/layout/mod.rs | 4 +- crates/ui-contract/src/runtime/env.rs | 13 +++- crates/ui-widgets/tests/it/layout/row_line.rs | 69 ++++++++++++++++++- 7 files changed, 129 insertions(+), 28 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index bf9e23c47..9cda37695 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -291,13 +291,13 @@ impl ShapeHooks for BodyHooks<'_> { let props = comp.props(Internal::new()); self.room = self.mount_room(props, ui, id, at, scx.tokens); let env = Env::of(ui); - self.given = self.given_axes(props, &env, at); + self.given = self.given_axes(props, (&env, ui), at); self.fixed_height = self.fixed_height(props, at); self.passes = self.passes_width(props, &env, at); self.held = self.held(props, &env); self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); self.in_column = label::in_column(ui); - self.given.1 |= self.given_room(props, &env, at, ui.ctx(), id); + self.given.1 |= self.given_room(props, (&env, ui), at, id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; let room = self.room.x - 2.0 * self.pads(props, scx.tokens).x; @@ -1828,8 +1828,8 @@ impl BodyHooks<'_> { Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)), None => self.mount_room(&props, at.ui, id, at.at, at.scx.tokens), }; - self.given = self.given_axes(&props, at.env, at.at); - self.given.1 |= self.given_room(&props, at.env, at.at, at.ui.ctx(), id); + self.given = self.given_axes(&props, (at.env, at.ui), at.at); + self.given.1 |= self.given_room(&props, (at.env, at.ui), at.at, id); 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); diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 1cb5f02c7..cae3774d6 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -125,9 +125,9 @@ impl<'b> BodyHooks<'b> { /// too: the line is a fixed cross extent, and the container fills it (a bar in a shell slot). A container that /// fills its height where its parent sizes from its content is capped (`capped`), and `given_room` decides whether /// it is given its room. - pub(super) fn given_axes(&self, props: &ContainerProps, env: &Env, at: ShowAt) -> (bool, bool) { + pub(super) fn given_axes(&self, props: &ContainerProps, (env, ui): (&Env, &Ui), at: ShowAt) -> (bool, bool) { let sizing = self.sizing(props); - let fills_line = sizing == Sizing::FillWidth && unwrapped_row(props) && env.row_line.is_some(); + let fills_line = sizing == Sizing::FillWidth && unwrapped_row(props) && crate::layout::row_line_of(ui, env).is_some(); let fits_bar = props.content_in_bar && env.values.get::().0; let (x, y) = (!sizing.content_width() && !fits_bar, sizing.fills_height() || fills_line); match (at, &props.mount) { @@ -143,12 +143,15 @@ impl<'b> BodyHooks<'b> { /// body runs in it, so the children in it that fill share it (a ribbon group as tall as the tallest group, its /// title at its foot). In the row's measuring run there is no settled line, not even where the row shares a line /// with an inline header or an end region, and the container measures its content. - pub(super) fn line_height(&self, props: &ContainerProps, env: &Env, at: ShowAt) -> Option { + pub(super) fn line_height(&self, props: &ContainerProps, (env, ui): (&Env, &Ui), at: ShowAt) -> Option { let inline = matches!((at, &props.mount), (ShowAt::Flow, Mount::Inline)); if !(inline && self.sizing(props).fills_height() && env.content.1) { return None; } - env.row_line.filter(|line| line.settled).and_then(|line| line.height).filter(|height| height.is_finite() && *height > 0.0) + crate::layout::row_line_of(ui, env) + .filter(|line| line.settled) + .and_then(|line| line.height) + .filter(|height| height.is_finite() && *height > 0.0) } /// Whether a content-sized inline container passes the width its column gives it on to its own body, where `env` @@ -217,10 +220,11 @@ impl<'b> BodyHooks<'b> { /// children that fill share it: the room is the settled line of the row it stands on (`line_height`), or its /// content is taller than the room, as this pass's measure found it (the record `content` its measuring run leaves /// then). Otherwise it takes its content height. - pub(super) fn given_room(&self, props: &ContainerProps, env: &Env, at: ShowAt, ctx: &Context, id: Id) -> bool { + pub(super) fn given_room(&self, props: &ContainerProps, (env, ui): (&Env, &Ui), at: ShowAt, id: Id) -> bool { + let ctx = ui.ctx(); let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ctx)); self.capped(props, env, at) - && (self.line_height(props, env, at).is_some() + && (self.line_height(props, (env, ui), at).is_some() || layout_memory::measured(ctx, sub(id, "content")).is_some_and(|content| content.took.y > self.room.y + tolerance)) } @@ -345,7 +349,7 @@ impl<'b> BodyHooks<'b> { let shares_view = !room.y.is_finite() && self.sizing(props).fills_height() && crate::layout::shares_y(ui); let y = shares_view.then(|| crate::layout::view_room(ui, craft_behavior::Axis::Y)).flatten().unwrap_or(room.y); // A body that fills the height of the row line it stands on runs in that line. - let y = self.line_height(props, &Env::of(ui), at).unwrap_or(y); + let y = self.line_height(props, (&Env::of(ui), ui), at).unwrap_or(y); Vec2::new(cap.map_or(room.x, |cap| room.x.min(cap)), props.room_height.unwrap_or(y)) } }, diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index bb622ea9f..6594e2b68 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -317,7 +317,7 @@ fn place_view(ui: &mut Ui, rect: Rect) -> Rect { /// view taller than that reaches, and a view no run showed yet, stays at the row's top. The room keeps its size, so a /// kept run replays moved with it. fn on_row_line(ui: &Ui, id: egui::Id, room: Rect) -> Rect { - let Some(centre) = Env::of(ui).row_line.and_then(|line| line.centre) else { + let Some(centre) = crate::layout::row_line_of(ui, &Env::of(ui)).and_then(|line| line.centre) else { return room; }; let Some(size) = lazy::last_extent(ui.ctx(), id) else { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index f65e44ecc..57accbccc 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -328,7 +328,7 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 // its measuring run, where the child measured at its own size. if axis == Axis::Y && env.content.1 - && let Some(line) = env.row_line.and_then(|line| line.height) + && let Some(line) = row_line_of(ui, &env).and_then(|line| line.height) { return measured.max(line); } @@ -502,7 +502,7 @@ pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(& let shrink = Env::of(ui).shrink; // The unit's content is no unit of the row: it runs in a room of its own, on the row's line only to fill it. Its // children take no slots on the line and report nothing to the row: the unit's block is what stands in the row. - let line = Env::of(ui).row_line.map(|line| RowLine { places: false, ..line }); + let line = row_line_of(ui, &Env::of(ui)).map(|line| RowLine { places: false, ..line }); let own_room = Env::of(ui).derive_local(|scoped| { scoped.start_room(); scoped.row_line = line; @@ -1161,7 +1161,10 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( let sweep = |ui: &mut Ui, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { let flow = Flow::new(ui.available_rect_before_wrap(), rtl); pass_state::with::(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(Spread::new(flow, gap, last, leasts, probe)))); + // The children run in the sweep's own `Ui`: the row's env is installed for it, so they are its direct children. + let installed = Env::install_for(ui, Env::of(ui)); let inner = body(ui); + Env::restore(&ctx, installed); let spread = match pass_state::with::(&ctx, |cursors| cursors.0.remove(&id)) { Some(Cursor::Spread(spread)) => Some(spread), _ => None, @@ -1262,7 +1265,7 @@ pub fn place_in_flow(ui: &mut Ui, size: Vec2) -> Rect { /// and its first line to the container whose header or body it starts. pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let env = Env::of(ui); - let (line, target) = (env.row_line.filter(|line| line.places), env.first_line); + let (line, target) = (row_line_of(ui, &env).filter(|line| line.places), env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its // rows reported before it. @@ -1304,6 +1307,18 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { placed } +/// The line of the unwrapped `Row` body a child placed in flow in `ui` stands on, `env` being `ui`'s env: only a direct +/// child of the row has it (`Env::installed_for`). +pub(crate) fn row_line_of(ui: &Ui, env: &Env) -> Option { + env.row_line.filter(|_| Env::installed_for(ui)) +} + +/// The `Grid` or spread `Row` body whose next cell a child placed in flow in `ui` takes, `env` being `ui`'s env: only a +/// direct child of the body takes one (`Env::installed_for`). +fn grid_of(ui: &Ui, env: &Env) -> Option { + env.grid.filter(|_| Env::installed_for(ui)) +} + /// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the /// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { @@ -1315,7 +1330,8 @@ pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { /// cells after it stay in their columns. Outside a grid it does nothing. pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); - let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); + let grid = + grid_of(ui, &env).filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { take_in(ui, &env, Vec2::ZERO); } @@ -1325,7 +1341,8 @@ pub fn empty_cell(ui: &mut Ui) { /// closes. fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { close_flow_start(ui.ctx(), env); - match cell_in(ui, env.grid, size) { + let grid = grid_of(ui, env); + match cell_in(ui, grid, size) { Some(cell) => (cell, true), None => (alloc::space(ui, size), false), } @@ -1335,7 +1352,8 @@ fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { /// it; `None`, taking nothing, outside such a body. pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { let env = Env::of(ui); - let cell = cell_in(ui, env.grid, size); + let grid = grid_of(ui, &env); + let cell = cell_in(ui, grid, size); if cell.is_some() { close_flow_start(ui.ctx(), &env); } @@ -1351,7 +1369,8 @@ fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { /// The region the next child shown in flow in `ui` measures and is placed in: that of the next cell of the `Grid` or /// spread `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. pub(crate) fn flow_region(ui: &Ui) -> Rect { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); + let cell = + grid_of(ui, &Env::of(ui)).and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); cell.unwrap_or_else(|| ui.available_rect_before_wrap()) } @@ -1365,7 +1384,7 @@ pub(crate) fn row_alone_room(ui: &Ui) -> Option { /// The room a child shown in flow in `ui` measures and sizes in: the room of the next cell of the `Grid` or spread /// `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. pub(crate) fn flow_room(ui: &Ui) -> Vec2 { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); + let cell = grid_of(ui, &Env::of(ui)).and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); cell.unwrap_or_else(|| open_room(ui)) } @@ -1392,7 +1411,8 @@ fn open_room(ui: &Ui) -> Vec2 { /// The room a child that fills its width fills in `ui`: `flow_room`, except that in a `Content` column of a `Grid` it /// is the column's width, so the child never measures as the room and pushes the next column out of it. pub(crate) fn flow_fill_room(ui: &Ui) -> Vec2 { - let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); + let cell = + grid_of(ui, &Env::of(ui)).and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); cell.unwrap_or_else(|| open_room(ui)) } @@ -1414,15 +1434,14 @@ pub(crate) fn shares_y(ui: &Ui) -> bool { /// Whether the next child shown in flow in `ui` goes in a `Content` column of the `Grid` body that encloses `ui` /// directly: like a content-sized column, a child that fills its width is placed at its measured width there. pub(crate) fn in_grid_content_column(ui: &Ui) -> bool { - Env::of(ui) - .grid + grid_of(ui, &Env::of(ui)) .is_some_and(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).is_some_and(Cursor::in_content_column))) } /// The cell the next child shown in flow in `ui` takes, when the body that encloses `ui` directly is a `Grid`: the /// grid's body, the cell's column and whether the column is a `Content` one. pub(crate) fn grid_cell(ui: &Ui) -> Option<(Id, usize, bool)> { - let grid = Env::of(ui).grid?; + let grid = grid_of(ui, &Env::of(ui))?; pass_state::with::(ui.ctx(), |cursors| { let cursor = cursors.0.get(&grid)?; Some((grid, cursor.grid_column()?, cursor.in_content_column())) diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index c9afb1e1d..77090807d 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -26,6 +26,6 @@ pub(crate) use body::run_body; pub(crate) use body::{ BodyLine, BracketTook, HeldKind, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, - place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, - take_bracket, take_cell, take_in_flow, view_room, + place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, row_line_of, run_body_measured, shares_y, + shrink_cap, take_bracket, take_cell, take_in_flow, view_room, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 9708a392e..a76a73908 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -307,7 +307,8 @@ pub(crate) enum ColumnSweep { } /// The line of an unwrapped `Row` body, as its direct children placed in flow see it: a child of one line sits with -/// its centre on the line's centre, and a child of more than one line, or with no line of its own, at its top. +/// its centre on the line's centre, and a child of more than one line, or with no line of its own, at its top. Read +/// through `layout::row_line_of`, which gives it only to the direct children (`Env::installed_for`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct RowLine { /// The row body, which the children of a measuring run report their lines to. @@ -772,6 +773,16 @@ impl Env { Installed { viewport, node, previous } } + /// Whether `ui` is a `Ui` an env entry was installed for (`install_for`), not one that reads an entry installed + /// further up its stack. What a body sets up for the children it places in flow (its `Grid` or spread row's cells, + /// its unwrapped row's line) is for its direct children, which it shows in the `Ui` it installed its env for. A + /// `Ui` egui code makes inside that one (an `egui::Grid`, `ui.horizontal` in a caller's closure) lays out its own + /// children: a component placed there takes no cell or line of the body around it. + pub(crate) fn installed_for(ui: &Ui) -> bool { + let node = stack::node_id(ui); + PerViewport::::with(ui.ctx(), pass::current_viewport(ui.ctx()), |envs| envs.entries.contains_key(&node)) + } + /// Puts back the entry `install_for` replaced. pub(crate) fn restore(ctx: &Context, installed: Installed) { PerViewport::::with(ctx, installed.viewport, |envs| match installed.previous { diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 92a3cd6b8..b77106fb8 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -1,7 +1,8 @@ //! The row line: a child of an unwrapped row that is one line sits with its centre on the row's line; a child of more //! than one line (a column, a field with a help line below) sits at the row's top. A control with its label after it //! or above it, and a field labelled above, sit on the line by their control, as a bare control does, in a row and in -//! a grid's cell. +//! a grid's cell. Components an app shows in an egui container inside a row or grid are laid out by that container: +//! they take neither the row's line nor the grid's cells. use craft_behavior::ColumnWidth; use craft_theme::ControlSize; @@ -165,3 +166,69 @@ fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_ assert!((button.center().y - check.center().y).abs() <= ROUNDING, "{at}: the box {check:?} sits on the button's line {button:?}"); } } + +/// Check boxes an app lays out in an `egui::Grid` inside a row (a dialog's custom row of two columns of check boxes) +/// are no children of the row: the grid's rows are as high as the same grid's outside a row, not as high as the row's +/// line, and what follows the row starts under the grid. +#[trial] +fn check_boxes_in_an_egui_grid_in_a_row_keep_their_own_rows() { + const ROWS: usize = 3; + let shown = |in_row: bool| { + let seen = Rc::new(Cell::new(([Rect::NOTHING; ROWS], Rect::NOTHING))); + let out = Rc::clone(&seen); + let _fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(300.0, 600.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + let mut boxes = [Rect::NOTHING; ROWS]; + let mut grid = |ui: &mut egui::Ui| { + egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { + for (row, rect) in boxes.iter_mut().enumerate() { + *rect = Checkbox::new(Bind::given(true)).label(format!("Left {row}")).show(ui).response.rect; + Checkbox::new(Bind::given(false)).label(format!("Right {row}")).show(ui); + ui.end_row(); + } + }); + }; + if in_row { + Row::new().fill().show(ui, |ui, _| grid(ui)); + } else { + Stack::new().fill().show(ui, |ui, _| grid(ui)); + } + let after = Button::new("After").show(ui).rect; + out.set((boxes, after)); + }); + }); + seen.get() + }; + let (alone, _) = shown(false); + let (boxes, after) = shown(true); + let pitch = |boxes: &[Rect; ROWS]| boxes[1].top() - boxes[0].top(); + assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); + assert!(after.top() >= boxes[ROWS - 1].bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}"); +} + +/// Check boxes in a `ui.horizontal` an app shows in a `Grid` body are laid out by it: side by side on one line, taking +/// none of the grid's cells. +#[trial] +fn check_boxes_in_an_egui_container_in_a_grid_take_no_cells() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let _fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 400.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + Grid::new(&[ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| { + Text::new("Name").show(ui); + let pair = ui.horizontal(|ui| { + let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect; + let two = Checkbox::new(Bind::given(true)).label("Two").show(ui).response.rect; + (one, two) + }); + out.set(pair.inner); + }); + }); + }); + let (one, two) = seen.get(); + assert!((one.center().y - two.center().y).abs() <= ROUNDING && two.left() >= one.right() - ROUNDING, "One {one:?}, then Two {two:?} on its line"); +} From 7547d34702128c7a71bfd36946ef5cd3471c079b Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 20:43:45 +0000 Subject: [PATCH 02/15] Layout: a labelled control in a flow egui lays out without wrapping decides its label at its own width egui::Grid offers a column with no width from the last frame its least cell width (40 points). A check box's label after it was decided in that width, so it wrapped, its cell grew taller than the one-line cells beside it, and egui::Grid centred the shorter cells lower: in PhotoCraft's Conditional Mode Change dialog, Bitmap and RGB Color no longer shared a row. The column then stayed that narrow. In a Ui that egui lays out (no body installed its env for it) where egui extends text instead of wrapping it (Ui::wrap_mode: ui.horizontal, an egui::Grid without a max column width), the label step's row has no end: the label keeps its natural width, a beside label never stacks for want of room, and the step's flow widens from the row's start edge to what the label and control need. Craft's own rows, bars and grid cells, and vertical and wrapping flows, keep their bounded room. --- crates/ui-contract/src/contract/body/hooks.rs | 1 + .../ui-contract/src/contract/label/place.rs | 45 ++++++++++++------- crates/ui-contract/src/contract/label/step.rs | 14 +++++- crates/ui-contract/src/contract/paint_ui.rs | 2 +- crates/ui-widgets/tests/it/layout/row_line.rs | 42 ++++++++++++++--- 5 files changed, 81 insertions(+), 23 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 9cda37695..2e46f888b 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1288,6 +1288,7 @@ impl BodyHooks<'_> { plan.regions.body.width() }, content_row: false, + unbounded: false, text: resolved.label_value, side, help: props.help.as_ref(), diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index f86ab6e67..ca9c88259 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -87,7 +87,7 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let gap = label_gap(env); let indent = after_indent(ctx, env, input, gap); let mut natural = leaf.measure_in(kids, craft_behavior::Proposal::Ideal); - if input.side.layout == FieldLayout::After { + if input.side.layout == FieldLayout::After && !input.unbounded { // The label takes the room the control and the gap leave, and its detail wraps there. let room = (input.row.width() - indent - input.control_min - gap).max(0.0); if natural.x > room { @@ -96,7 +96,9 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } let baseline = leaf.baseline.get(); if input.side.layout == FieldLayout::Line { - let (cell, rest) = flow.take_end(env.control(input.size).number); + let number = env.control(input.size).number; + let flow = if input.unbounded { widened(flow, natural.x + gap + number) } else { flow }; + let (cell, rest) = flow.take_end(number); let width = natural.x.min((rest.rect().width() - gap).max(0.0)); let drop = (cell.height() - natural.y).max(0.0) / 2.0; let label = Flow::new(rest.rect(), rtl).align(Vec2::new(width, natural.y), Align::Min, Align::Min).translate(Vec2::new(0.0, drop)); @@ -124,20 +126,19 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let caption = if matches!(input.side.layout, FieldLayout::Above | FieldLayout::Caption(_)) { column } else { 0.0 }; // The room decides; a beside label gets the width it needs even where last frame's content was narrower. A label // that never sits beside stacks in an unbounded room as well. - let stacks = (input.room < stack_below || stack_below == f32::INFINITY) && !(input.content_row && input.side.layout == FieldLayout::Beside); - // A stacked label has the row's width at most; its name elides there. - let column = if stacks { column.min(input.row.width()) } else { column }; - let flow = if stacks || input.row.width() >= stack_below { - flow - } else { - let mut wide = input.row; - if rtl { - wide.min.x = wide.max.x - stack_below; - } else { - wide.max.x = wide.min.x + stack_below; - } - Flow::new(wide, rtl) + let stacks = (input.room < stack_below || stack_below == f32::INFINITY) + && !((input.content_row || input.unbounded) && input.side.layout == FieldLayout::Beside); + // A stacked label has the row's width at most, where its name elides; in a row without an end it keeps its own. + let column = if stacks && !input.unbounded { column.min(input.row.width()) } else { column }; + // A beside label that does not stack takes its column, the gap and the control's least, past the row's end where + // the row is narrower. A row without an end is as wide as its label and control need, whatever the layout. + let need = match input.side.layout { + FieldLayout::After if input.unbounded => indent + input.control_min + gap + natural.x, + _ if input.unbounded && stacks => column.max(input.control_min), + _ if stacks => 0.0, + _ => stack_below, }; + let flow = widened(flow, need); if input.side.layout == FieldLayout::After { let flow = if indent > 0.0 { flow.take_start(indent).1 } else { flow }; @@ -162,6 +163,20 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } } +/// `flow` widened from its start edge to `need` when it is narrower: its end edge moves, to the left under RTL. +fn widened(flow: Flow, need: f32) -> Flow { + let mut wide = flow.rect(); + if wide.width() >= need { + return flow; + } + if flow.is_rtl() { + wide.min.x = wide.max.x - need; + } else { + wide.max.x = wide.min.x + need; + } + Flow::new(wide, flow.is_rtl()) +} + /// The gap between a label and its control: `space.gap.inline`, `space.gap.item` inside a bar. pub(crate) fn label_gap(env: &Env) -> f32 { let gaps = &env.tokens.space.gap; diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index e9126f28b..c186c28c6 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -32,6 +32,9 @@ pub(crate) struct LabelIn<'a> { /// The row sits in a column that takes its width from its content: a beside label never stacks for want of room, /// since the column is as wide as the label, the gap and the control need. pub content_row: bool, + /// The row's flow sets no end to it (`LeafLabel::unbounded`): the row is as wide as its label and control need, so + /// the label neither wraps nor stacks for want of room. + pub unbounded: bool, pub text: &'a Label, pub side: &'a SideLabel, /// The help line the container's footer shows; it joins the control's description with the label's detail. @@ -82,6 +85,9 @@ pub(crate) struct LeafLabel<'a> { pub parent: Option, /// The row the label and the child share. pub row: Rect, + /// The row's flow sets no end to it: egui lays it out and extends text there (an `egui::Grid` row, `ui.horizontal`). + /// `row` then gives only the row's start edge, top and height. + pub unbounded: bool, pub text: &'a Label, pub side: &'a SideLabel, /// What the child inherits (`leaf_under`). @@ -148,6 +154,7 @@ fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, tr row, room: row.width(), content_row: env.content.0, + unbounded: at.unbounded, text: at.text, side: at.side, help: None, @@ -392,7 +399,12 @@ fn flow_leaf_row( // grid's cell or a horizontal layout. The row spans the room's own edges: a room that scrolls along x is unbounded // at its start edge, the left one under RTL. let row = Rect::from_min_max(avail.min, egui::pos2(avail.max.x, avail.min.y + ideal.y)); - let at = LeafLabel { id, owner, parent: None, row, text: &label, side: &side, under: &under }; + // A flow egui lays out (no body installed its env for `ui`) in which egui extends text rather than wrapping it + // (`ui.horizontal`, an `egui::Grid` without a max column width) offers the row no end: the label is decided at + // its own width. An `egui::Grid` offers a column with no width from the last frame its least cell width, where + // the label would wrap and keep the column that narrow. + let unbounded = !Env::installed_for(ui) && ui.wrap_mode() == egui::TextWrapMode::Extend; + let at = LeafLabel { id, owner, parent: None, row, unbounded, text: &label, side: &side, under: &under }; let decided = decide_leaf(ui, &env, &at, &mut child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size)); // In a column that sizes from its content the row is the label plus the control, never the room around them. // A row of a horizontal flow is as wide as its label and control: the room it has there is unbounded. diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index f60372b59..1e61f4d8f 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -163,7 +163,7 @@ impl PaintUi<'_> { let env = Env::of(self.ui); let mut child = child; let under = label::leaf_under(&env, &side, &child, (self.enabled, self.size)); - let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, text: &label, side: &side, under: &under }; + let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, unbounded: false, text: &label, side: &side, under: &under }; let ctx = self.ui.ctx().clone(); layout_memory::boundary(&ctx, true, || { let placed = crate::layout::ColumnGroup::field(&mut *self.ui, |ui| label::leaf(ui, &env, &at, &mut child, None)); diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index b77106fb8..b198a9369 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -174,18 +174,18 @@ fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_ fn check_boxes_in_an_egui_grid_in_a_row_keep_their_own_rows() { const ROWS: usize = 3; let shown = |in_row: bool| { - let seen = Rc::new(Cell::new(([Rect::NOTHING; ROWS], Rect::NOTHING))); + let seen = Rc::new(Cell::new(([(Rect::NOTHING, Rect::NOTHING); ROWS], Rect::NOTHING))); let out = Rc::clone(&seen); let _fixture = settled(move |ui| { let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(300.0, 600.0)); let out = Rc::clone(&out); Stack::new().fill().show_at(ui, room, move |ui, _| { - let mut boxes = [Rect::NOTHING; ROWS]; + let mut boxes = [(Rect::NOTHING, Rect::NOTHING); ROWS]; let mut grid = |ui: &mut egui::Ui| { egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { for (row, rect) in boxes.iter_mut().enumerate() { - *rect = Checkbox::new(Bind::given(true)).label(format!("Left {row}")).show(ui).response.rect; - Checkbox::new(Bind::given(false)).label(format!("Right {row}")).show(ui); + rect.0 = Checkbox::new(Bind::given(true)).label(format!("Left {row}")).show(ui).response.rect; + rect.1 = Checkbox::new(Bind::given(false)).label(format!("Right {row}")).show(ui).response.rect; ui.end_row(); } }); @@ -203,9 +203,12 @@ fn check_boxes_in_an_egui_grid_in_a_row_keep_their_own_rows() { }; let (alone, _) = shown(false); let (boxes, after) = shown(true); - let pitch = |boxes: &[Rect; ROWS]| boxes[1].top() - boxes[0].top(); + for (left, right) in boxes { + assert!((left.center().y - right.center().y).abs() <= ROUNDING, "the two columns share each row: {left:?} {right:?}"); + } + let pitch = |boxes: &[(Rect, Rect); ROWS]| boxes[1].0.top() - boxes[0].0.top(); assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); - assert!(after.top() >= boxes[ROWS - 1].bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}"); + assert!(after.top() >= boxes[ROWS - 1].0.bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}"); } /// Check boxes in a `ui.horizontal` an app shows in a `Grid` body are laid out by it: side by side on one line, taking @@ -232,3 +235,30 @@ fn check_boxes_in_an_egui_container_in_a_grid_take_no_cells() { let (one, two) = seen.get(); assert!((one.center().y - two.center().y).abs() <= ROUNDING && two.left() >= one.right() - ROUNDING, "One {one:?}, then Two {two:?} on its line"); } + +/// Under right-to-left, a check box in a `ui.horizontal` too narrow for its label keeps the label on one line: the +/// row is as wide as its box and label, and the label runs on from its box towards the left, past the room's end. +#[trial] +fn a_check_box_in_a_narrow_horizontal_keeps_its_label_on_one_line_under_rtl() { + const LONG: &str = "Second option with a long name"; + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let mut fixture = Fixture::new(move |ui| { + let out = Rc::clone(&out); + Stack::new().fill().show(ui, move |ui, _| { + let pair = ui.horizontal(|ui| { + let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect; + let two = Checkbox::new(Bind::given(false)).label(LONG).show(ui).response.rect; + (one, two) + }); + out.set(pair.inner); + }); + }); + fixture.direction(craft_i18n::Direction::Rtl).room(egui::vec2(160.0, 200.0)).settle(); + fixture.idle(3); + let (one, two) = seen.get(); + let label = text(&fixture, LONG); + assert!(two.right() <= one.left() + ROUNDING, "Two {two:?} follows One {one:?} towards the left"); + assert!(label.height() < two.height() * 1.5, "the label {label:?} stays on one line beside its box {two:?}"); + assert!(label.right() <= two.left() + ROUNDING, "the label {label:?} runs on from its box {two:?} towards the left"); +} From f6b98be494c4d9873c13739f0d7ada6aa7a375b4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 21:50:53 +0000 Subject: [PATCH 03/15] egui: pin storytold/egui next efd532a5, which makes Ui::is_grid public --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 28 ++++++++++++++-------------- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 96a9f4e10..b61f9f08b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5450,7 +5450,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "bytemuck", "emath", @@ -5506,7 +5506,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "ahash", "bytemuck", @@ -5541,7 +5541,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "accesskit", "ahash", @@ -5560,7 +5560,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "ahash", "bytemuck", @@ -5579,7 +5579,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5599,7 +5599,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "bytemuck", "egui", @@ -5612,7 +5612,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "eframe", "egui", @@ -5689,7 +5689,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "bytemuck", ] @@ -5762,7 +5762,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" dependencies = [ "ahash", "bytemuck", @@ -5788,7 +5788,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" [[package]] name = "equator" @@ -15119,19 +15119,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" +source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" diff --git a/Cargo.toml b/Cargo.toml index 8afdc685c..c65ccbb18 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -emath = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +emath = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid From f4bd0ae95f28f3ec91c9dc97374e0db237a3b269 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 21:50:53 +0000 Subject: [PATCH 04/15] Layout: what a body sets up for its children in flow stops at egui containers; labels unbounded only in an egui::Grid cell Env::of clears the start_room facts (grid cursor, row line and room, shrink step, first line, flow start, fill share, content column, offered width) when the entry it finds was installed for an ancestor of the Ui, not for the Ui itself. Copies made from it (with_env, MemoView's counting install, with_item_facts) and the measure keys start from the cleared facts. Env::installed_for, row_line_of and grid_of go. Craft code that runs children in a Ui it makes installs its env there: run_sharing and measure_sharing's no-share block, run_spread's sweeps, Lazy and MemoView, Pages, measure_slot, the levelled unit's probe, a content-height pane at a caller rect (a room of its own), PaintUi's children. flow_scope is the craft form of ui.scope, push_id and with_layout around craft content; the dock group header and the Liquify footer use it, and the select search row and the date popup's Today row are craft Rows. A craft Grid documents that an egui container in it is no cell. The label step's signal is egui's Ui::is_grid (egui_cell): in an egui::Grid cell a labelled control or container decides its label at its own width and widens at the cell's right edge in either direction. ui.horizontal keeps wrapping and stacking at the room's end. --- crates/imaging/src/ui/liquify/mod.rs | 4 +- crates/ui-contract/src/contract/body.rs | 4 + crates/ui-contract/src/contract/body/hooks.rs | 12 +-- crates/ui-contract/src/contract/body/size.rs | 26 +++---- .../ui-contract/src/contract/label/place.rs | 40 ++++++---- crates/ui-contract/src/contract/label/step.rs | 27 ++++--- crates/ui-contract/src/contract/lazy.rs | 8 +- crates/ui-contract/src/contract/mount.rs | 4 +- crates/ui-contract/src/contract/pages.rs | 7 +- crates/ui-contract/src/contract/paint_ui.rs | 6 +- crates/ui-contract/src/layout/body.rs | 73 +++++++------------ crates/ui-contract/src/layout/mod.rs | 4 +- crates/ui-contract/src/layout/slot.rs | 5 +- crates/ui-contract/src/runtime/env.rs | 57 +++++++++++---- .../ui-contract/src/runtime/env/overrides.rs | 9 +++ crates/ui-panels/src/docking/group.rs | 39 +++++----- .../ui-widgets/src/layout_components/mod.rs | 4 + crates/ui-widgets/src/pickers/date.rs | 5 +- crates/ui-widgets/src/pickers/select.rs | 3 +- 19 files changed, 192 insertions(+), 145 deletions(-) diff --git a/crates/imaging/src/ui/liquify/mod.rs b/crates/imaging/src/ui/liquify/mod.rs index 61e2304eb..cd382c75e 100644 --- a/crates/imaging/src/ui/liquify/mod.rs +++ b/crates/imaging/src/ui/liquify/mod.rs @@ -81,7 +81,7 @@ use craft_ui::layout_components::Row; use craft_ui::primitives::Checker; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase}; -use craft_ui::runtime::env::Env; +use craft_ui::runtime::env::{Env, flow_scope}; use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft_ui::runtime::words::CommonWords; use craft_ui::sections::{DialogRole, FooterButton}; @@ -462,7 +462,7 @@ impl LiquifyWorkspace { .opened(open) .buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]) .footer(|ui, _| { - ui.vertical_centered(|ui| { + let _ = flow_scope(ui, egui::UiBuilder::new().layout(egui::Layout::top_down(egui::Align::Center)), |ui| { let mut guard = this.borrow_mut(); let work: &mut LiquifyWorkspace = &mut guard; let events = Checkbox::new(Bind::given(work.preview)).label(preview_label.clone()).show(ui).events; diff --git a/crates/ui-contract/src/contract/body.rs b/crates/ui-contract/src/contract/body.rs index e03be55cb..82d220de4 100644 --- a/crates/ui-contract/src/contract/body.rs +++ b/crates/ui-contract/src/contract/body.rs @@ -166,6 +166,9 @@ pub(super) struct BodyHooks<'b> { /// The container is a row of a vertical flow, not a member of a row's line (`label::in_column`), as its parent /// flow showed it this run: its own measuring run shows its content in a flow of its own. in_column: bool, + /// The container is shown in a cell of an `egui::Grid` (`LabelIn::egui_cell`), as its parent flow showed it this + /// run: its label is decided at its own width. + egui_cell: bool, /// The line just before the container in its flow is a rule (`layout::flow_start`), as its parent flow showed it /// this run: a rule above its header is not drawn, so two rules never follow each other. after_rule: bool, @@ -245,6 +248,7 @@ impl<'b> BodyHooks<'b> { held: false, across: false, in_column: true, + egui_cell: false, after_rule: false, follows_end: false, } diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 2e46f888b..701d3f3e0 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -291,13 +291,14 @@ impl ShapeHooks for BodyHooks<'_> { let props = comp.props(Internal::new()); self.room = self.mount_room(props, ui, id, at, scx.tokens); let env = Env::of(ui); - self.given = self.given_axes(props, (&env, ui), at); + self.given = self.given_axes(props, &env, at); self.fixed_height = self.fixed_height(props, at); self.passes = self.passes_width(props, &env, at); self.held = self.held(props, &env); self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); self.in_column = label::in_column(ui); - self.given.1 |= self.given_room(props, (&env, ui), at, id); + self.egui_cell = ui.is_grid(); + self.given.1 |= self.given_room(props, &env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; let room = self.room.x - 2.0 * self.pads(props, scx.tokens).x; @@ -1288,7 +1289,7 @@ impl BodyHooks<'_> { plan.regions.body.width() }, content_row: false, - unbounded: false, + egui_cell: self.egui_cell, text: resolved.label_value, side, help: props.help.as_ref(), @@ -1829,8 +1830,8 @@ impl BodyHooks<'_> { Some(width) => Vec2::new(width, props.room_height.unwrap_or(f32::INFINITY)), None => self.mount_room(&props, at.ui, id, at.at, at.scx.tokens), }; - self.given = self.given_axes(&props, (at.env, at.ui), at.at); - self.given.1 |= self.given_room(&props, (at.env, at.ui), at.at, id); + self.given = self.given_axes(&props, at.env, at.at); + self.given.1 |= self.given_room(&props, at.env, at.at, at.ui.ctx(), id); 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); @@ -1840,6 +1841,7 @@ impl BodyHooks<'_> { self.room.x = width; } self.in_column = label::in_column(at.ui); + self.egui_cell = at.ui.is_grid(); // 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); diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index cae3774d6..932b2fa41 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -29,9 +29,9 @@ pub(super) struct MeasureKey { /// Whether the body shows, and how much of it an animated collapse shows. shows: (bool, f32), env: EnvFacts, - /// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), and with a rule - /// just before it (a rule above its header is not drawn). - flow: (bool, bool), + /// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), with a rule just + /// before it (a rule above its header is not drawn), and in a cell of an `egui::Grid`. + flow: (bool, bool, bool), } /// The props a body was measured under, compared on the fields its measure reads. @@ -95,7 +95,7 @@ impl<'b> BodyHooks<'b> { width, shows: (self.open, self.presence.t), env: EnvFacts::of(env), - flow: (self.in_column, self.after_rule), + flow: (self.in_column, self.after_rule, self.egui_cell), } } @@ -125,9 +125,9 @@ impl<'b> BodyHooks<'b> { /// too: the line is a fixed cross extent, and the container fills it (a bar in a shell slot). A container that /// fills its height where its parent sizes from its content is capped (`capped`), and `given_room` decides whether /// it is given its room. - pub(super) fn given_axes(&self, props: &ContainerProps, (env, ui): (&Env, &Ui), at: ShowAt) -> (bool, bool) { + pub(super) fn given_axes(&self, props: &ContainerProps, env: &Env, at: ShowAt) -> (bool, bool) { let sizing = self.sizing(props); - let fills_line = sizing == Sizing::FillWidth && unwrapped_row(props) && crate::layout::row_line_of(ui, env).is_some(); + let fills_line = sizing == Sizing::FillWidth && unwrapped_row(props) && env.row_line.is_some(); let fits_bar = props.content_in_bar && env.values.get::().0; let (x, y) = (!sizing.content_width() && !fits_bar, sizing.fills_height() || fills_line); match (at, &props.mount) { @@ -143,15 +143,12 @@ impl<'b> BodyHooks<'b> { /// body runs in it, so the children in it that fill share it (a ribbon group as tall as the tallest group, its /// title at its foot). In the row's measuring run there is no settled line, not even where the row shares a line /// with an inline header or an end region, and the container measures its content. - pub(super) fn line_height(&self, props: &ContainerProps, (env, ui): (&Env, &Ui), at: ShowAt) -> Option { + pub(super) fn line_height(&self, props: &ContainerProps, env: &Env, at: ShowAt) -> Option { let inline = matches!((at, &props.mount), (ShowAt::Flow, Mount::Inline)); if !(inline && self.sizing(props).fills_height() && env.content.1) { return None; } - crate::layout::row_line_of(ui, env) - .filter(|line| line.settled) - .and_then(|line| line.height) - .filter(|height| height.is_finite() && *height > 0.0) + env.row_line.filter(|line| line.settled).and_then(|line| line.height).filter(|height| height.is_finite() && *height > 0.0) } /// Whether a content-sized inline container passes the width its column gives it on to its own body, where `env` @@ -220,11 +217,10 @@ impl<'b> BodyHooks<'b> { /// children that fill share it: the room is the settled line of the row it stands on (`line_height`), or its /// content is taller than the room, as this pass's measure found it (the record `content` its measuring run leaves /// then). Otherwise it takes its content height. - pub(super) fn given_room(&self, props: &ContainerProps, (env, ui): (&Env, &Ui), at: ShowAt, id: Id) -> bool { - let ctx = ui.ctx(); + pub(super) fn given_room(&self, props: &ContainerProps, env: &Env, at: ShowAt, ctx: &Context, id: Id) -> bool { let tolerance = measure_tolerance(crate::runtime::egui::scale::pixels_per_point(ctx)); self.capped(props, env, at) - && (self.line_height(props, (env, ui), at).is_some() + && (self.line_height(props, env, at).is_some() || layout_memory::measured(ctx, sub(id, "content")).is_some_and(|content| content.took.y > self.room.y + tolerance)) } @@ -349,7 +345,7 @@ impl<'b> BodyHooks<'b> { let shares_view = !room.y.is_finite() && self.sizing(props).fills_height() && crate::layout::shares_y(ui); let y = shares_view.then(|| crate::layout::view_room(ui, craft_behavior::Axis::Y)).flatten().unwrap_or(room.y); // A body that fills the height of the row line it stands on runs in that line. - let y = self.line_height(props, (&Env::of(ui), ui), at).unwrap_or(y); + let y = self.line_height(props, &Env::of(ui), at).unwrap_or(y); Vec2::new(cap.map_or(room.x, |cap| room.x.min(cap)), props.room_height.unwrap_or(y)) } }, diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index ca9c88259..11403fc5d 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -87,7 +87,7 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: let gap = label_gap(env); let indent = after_indent(ctx, env, input, gap); let mut natural = leaf.measure_in(kids, craft_behavior::Proposal::Ideal); - if input.side.layout == FieldLayout::After && !input.unbounded { + if input.side.layout == FieldLayout::After && !input.egui_cell { // The label takes the room the control and the gap leave, and its detail wraps there. let room = (input.row.width() - indent - input.control_min - gap).max(0.0); if natural.x > room { @@ -95,9 +95,11 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } } let baseline = leaf.baseline.get(); + // An egui grid's cell grows at its right edge in any direction (`LabelIn::egui_cell`); a row grows at its end edge. + let grows = if input.egui_cell { Grows::Right } else { Grows::End }; if input.side.layout == FieldLayout::Line { let number = env.control(input.size).number; - let flow = if input.unbounded { widened(flow, natural.x + gap + number) } else { flow }; + let flow = if input.egui_cell { widened(flow, natural.x + gap + number, grows) } else { flow }; let (cell, rest) = flow.take_end(number); let width = natural.x.min((rest.rect().width() - gap).max(0.0)); let drop = (cell.height() - natural.y).max(0.0) / 2.0; @@ -127,18 +129,18 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: // The room decides; a beside label gets the width it needs even where last frame's content was narrower. A label // that never sits beside stacks in an unbounded room as well. let stacks = (input.room < stack_below || stack_below == f32::INFINITY) - && !((input.content_row || input.unbounded) && input.side.layout == FieldLayout::Beside); - // A stacked label has the row's width at most, where its name elides; in a row without an end it keeps its own. - let column = if stacks && !input.unbounded { column.min(input.row.width()) } else { column }; + && !((input.content_row || input.egui_cell) && input.side.layout == FieldLayout::Beside); + // A stacked label has the row's width at most, where its name elides; in an egui grid's cell it keeps its own. + let column = if stacks && !input.egui_cell { column.min(input.row.width()) } else { column }; // A beside label that does not stack takes its column, the gap and the control's least, past the row's end where - // the row is narrower. A row without an end is as wide as its label and control need, whatever the layout. + // the row is narrower. An egui grid's cell is as wide as its label and control need, whatever the layout. let need = match input.side.layout { - FieldLayout::After if input.unbounded => indent + input.control_min + gap + natural.x, - _ if input.unbounded && stacks => column.max(input.control_min), + FieldLayout::After if input.egui_cell => indent + input.control_min + gap + natural.x, + _ if input.egui_cell && stacks => column.max(input.control_min), _ if stacks => 0.0, _ => stack_below, }; - let flow = widened(flow, need); + let flow = widened(flow, need, grows); if input.side.layout == FieldLayout::After { let flow = if indent > 0.0 { flow.take_start(indent).1 } else { flow }; @@ -163,16 +165,24 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } } -/// `flow` widened from its start edge to `need` when it is narrower: its end edge moves, to the left under RTL. -fn widened(flow: Flow, need: f32) -> Flow { +/// The edge a flow that is too narrow grows at (`widened`). +#[derive(Clone, Copy)] +enum Grows { + /// Its end edge: the left one under RTL. + End, + /// Its right edge, in either direction. + Right, +} + +/// `flow` widened to `need` at the edge `grows` names, when it is narrower. +fn widened(flow: Flow, need: f32, grows: Grows) -> Flow { let mut wide = flow.rect(); if wide.width() >= need { return flow; } - if flow.is_rtl() { - wide.min.x = wide.max.x - need; - } else { - wide.max.x = wide.min.x + need; + match grows { + Grows::End if flow.is_rtl() => wide.min.x = wide.max.x - need, + Grows::End | Grows::Right => wide.max.x = wide.min.x + need, } Flow::new(wide, flow.is_rtl()) } diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index c186c28c6..f81ab751f 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -32,9 +32,9 @@ pub(crate) struct LabelIn<'a> { /// The row sits in a column that takes its width from its content: a beside label never stacks for want of room, /// since the column is as wide as the label, the gap and the control need. pub content_row: bool, - /// The row's flow sets no end to it (`LeafLabel::unbounded`): the row is as wide as its label and control need, so - /// the label neither wraps nor stacks for want of room. - pub unbounded: bool, + /// The row is a cell of an `egui::Grid` (`LeafLabel::egui_cell`): the row is as wide as its label and control need, + /// so the label neither wraps nor stacks for want of room, and it grows at its right edge in any direction. + pub egui_cell: bool, pub text: &'a Label, pub side: &'a SideLabel, /// The help line the container's footer shows; it joins the control's description with the label's detail. @@ -85,9 +85,9 @@ pub(crate) struct LeafLabel<'a> { pub parent: Option, /// The row the label and the child share. pub row: Rect, - /// The row's flow sets no end to it: egui lays it out and extends text there (an `egui::Grid` row, `ui.horizontal`). - /// `row` then gives only the row's start edge, top and height. - pub unbounded: bool, + /// The row is a cell of an `egui::Grid`: egui places it from the cell's left edge in any direction, and gives the + /// column the width it takes from the next frame. `row` then gives only the cell's left edge, top and height. + pub egui_cell: bool, pub text: &'a Label, pub side: &'a SideLabel, /// What the child inherits (`leaf_under`). @@ -154,7 +154,7 @@ fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, tr row, room: row.width(), content_row: env.content.0, - unbounded: at.unbounded, + egui_cell: at.egui_cell, text: at.text, side: at.side, help: None, @@ -399,12 +399,10 @@ fn flow_leaf_row( // grid's cell or a horizontal layout. The row spans the room's own edges: a room that scrolls along x is unbounded // at its start edge, the left one under RTL. let row = Rect::from_min_max(avail.min, egui::pos2(avail.max.x, avail.min.y + ideal.y)); - // A flow egui lays out (no body installed its env for `ui`) in which egui extends text rather than wrapping it - // (`ui.horizontal`, an `egui::Grid` without a max column width) offers the row no end: the label is decided at - // its own width. An `egui::Grid` offers a column with no width from the last frame its least cell width, where - // the label would wrap and keep the column that narrow. - let unbounded = !Env::installed_for(ui) && ui.wrap_mode() == egui::TextWrapMode::Extend; - let at = LeafLabel { id, owner, parent: None, row, unbounded, text: &label, side: &side, under: &under }; + // An `egui::Grid` offers a column with no width from the last frame its least cell width, where the label would + // wrap and keep the column that narrow: in its cell the label is decided at its own width. + let egui_cell = ui.is_grid(); + let at = LeafLabel { id, owner, parent: None, row, egui_cell, text: &label, side: &side, under: &under }; let decided = decide_leaf(ui, &env, &at, &mut child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size)); // In a column that sizes from its content the row is the label plus the control, never the room around them. // A row of a horizontal flow is as wide as its label and control: the room it has there is unbounded. @@ -415,9 +413,10 @@ fn flow_leaf_row( let rtl = env.direction.is_rtl(); let span = |cell: Rect| Flow::new(Rect::from_min_size(cell.min, Vec2::new(cell.width(), ideal.y)), rtl).span(0.0, control_width); let (decided_control, decided_label) = (span(decided.control()), decided.label()); + // An egui grid's cell takes its extent from its left edge in any direction. let extent = if !content { avail.width() - } else if rtl { + } else if rtl && !egui_cell { avail.max.x - decided_control.min.x.min(decided_label.min.x) } else { decided_control.max.x.max(decided_label.max.x) - avail.min.x diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 6594e2b68..f5d4ab15d 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -172,8 +172,10 @@ impl Lazy { open_record(&ctx, audited.is_some()); } let mut child = alloc::child(ui, UiBuilder::new().max_rect(available).layout(layout).scope_id(id)); - // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. - let out = layout_memory::boundary(&ctx, false, || add(&mut child, &mut run)); + // Its extent in the body around it comes from its content's measure, so a change inside reaches that body. The + // content runs in the env of `ui`, as the direct children of the body around it: a plain `Lazy` keeps their + // line, cells and shrink step, and a memoized view starts its own room on top of it. + let out = layout_memory::boundary(&ctx, false, || Env::run_in(&mut child, env, |child| add(child, &mut run))); let rect = child.min_rect(); // The child `Ui` writes its widget rect when it drops: the record holds it as written. drop(child); @@ -317,7 +319,7 @@ fn place_view(ui: &mut Ui, rect: Rect) -> Rect { /// view taller than that reaches, and a view no run showed yet, stays at the row's top. The room keeps its size, so a /// kept run replays moved with it. fn on_row_line(ui: &Ui, id: egui::Id, room: Rect) -> Rect { - let Some(centre) = crate::layout::row_line_of(ui, &Env::of(ui)).and_then(|line| line.centre) else { + let Some(centre) = Env::of(ui).row_line.and_then(|line| line.centre) else { return room; }; let Some(size) = lazy::last_extent(ui.ctx(), id) else { diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 34137bf9a..06b25e3d6 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -149,7 +149,9 @@ impl Host for PaneHost { if self.0.content_height { let builder = egui::UiBuilder::new().max_rect(rect); let mut ui = crate::runtime::egui::alloc::child(parent, builder); - pass(&mut ui, Some(ShowAt::Flow), None); + // A layout room of its own, as a docked pane's. + let room = env.new_room(); + Env::run_in(&mut ui, room.clone(), |ui| pass(ui, Some(ShowAt::Flow), Some(&room))); crate::runtime::egui::alloc::advance_past(parent, ui.min_rect()); } else { pass(parent, Some(ShowAt::Rect(rect)), None); diff --git a/crates/ui-contract/src/contract/pages.rs b/crates/ui-contract/src/contract/pages.rs index 28c7b0916..02d0fb37f 100644 --- a/crates/ui-contract/src/contract/pages.rs +++ b/crates/ui-contract/src/contract/pages.rs @@ -3,6 +3,7 @@ use crate::layout::flow_region; use crate::runtime::egui::alloc; +use crate::runtime::env::Env; use crate::runtime::layout_memory; use crate::runtime::lazy; use crate::runtime::memory::sub; @@ -42,6 +43,8 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { let base = sub(ui.scope_id(), ("pages", self.salt)); let region = flow_region(ui); let layout = *ui.layout(); + // Each page runs in the env of `ui`, as the direct children of the body around it. + let env = Env::of(ui); let hidden = self.pages.iter().filter(|key| *key != self.current).fold(Vec2::ZERO, |largest, key| { let id = sub(base, hash(key)); let kept = lazy::measured(&ctx, id).map(|(size, reads)| { @@ -59,7 +62,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { layout_memory::boundary(&ctx, true, || { let room = Rect::from_min_size(region.min, Vec2::new(region.width(), f32::INFINITY)); let mut child = alloc::child(ui, UiBuilder::new().max_rect(room).layout(layout).scope_id(id).sizing_pass().invisible()); - page(&mut child, key); + Env::run_in(&mut child, env.clone(), |child| page(child, key)); child.min_rect().size() }) }); @@ -72,7 +75,7 @@ impl<'a, K: Hash + PartialEq> Pages<'a, K> { let id = sub(base, hash(self.current)); let mut child = alloc::child(ui, UiBuilder::new().max_rect(region).layout(layout).scope_id(id)); child.set_min_size(hidden.min(region.size())); - let out = page(&mut child, self.current); + let out = Env::run_in(&mut child, env, |child| page(child, self.current)); let rect = child.min_rect(); drop(child); // What the place took comes from the hidden pages' measures as well as from the shown page's components. diff --git a/crates/ui-contract/src/contract/paint_ui.rs b/crates/ui-contract/src/contract/paint_ui.rs index 1e61f4d8f..5ad18430c 100644 --- a/crates/ui-contract/src/contract/paint_ui.rs +++ b/crates/ui-contract/src/contract/paint_ui.rs @@ -163,7 +163,7 @@ impl PaintUi<'_> { let env = Env::of(self.ui); let mut child = child; let under = label::leaf_under(&env, &side, &child, (self.enabled, self.size)); - let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, unbounded: false, text: &label, side: &side, under: &under }; + let at = LeafLabel { id, owner: self.id, parent: Some(self.id), row: rect, egui_cell: false, text: &label, side: &side, under: &under }; let ctx = self.ui.ctx().clone(); layout_memory::boundary(&ctx, true, || { let placed = crate::layout::ColumnGroup::field(&mut *self.ui, |ui| label::leaf(ui, &env, &at, &mut child, None)); @@ -183,12 +183,14 @@ impl PaintUi<'_> { fn child_with(&mut self, id: Id, rect: Rect, child: C, tip: Option>, inside: Option>) -> C::Output { let scope = sub(self.id, "children"); let parent = &mut *self.ui; + // The kids' `Ui` holds no entry of its own: they inherit the env of the composite's `Ui`. + let outer = Env::of(parent); let kids = self.kids.get_or_insert_with(|| { let builder = egui::UiBuilder::new().layout(child::pinned_layout()).scope_id(scope).max_rect(self.rect); alloc::child(parent, access::with_parent(builder, self.id)) }); let ctx = kids.ctx().clone(); - let env = super::cx::child_env(&Env::of(kids), &super::cx::Under { enabled: self.enabled, size: self.size, inside }); + let env = super::cx::child_env(&outer, &super::cx::Under { enabled: self.enabled, size: self.size, inside }); // A child shown while the owner's fade runs lies under the owner's veil, so a faded child adds none of its own. let env = match self.fade { Some(_) => { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 57accbccc..909d0f76e 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -92,7 +92,9 @@ impl BodyLayout { BodyLayout::Row { wrap: false, align: RowAlign::Start } } - /// Children row-major over `columns`: a `'static` slice, or columns built in the pass. + /// Children row-major over `columns`: a `'static` slice, or columns built in the pass. The cells are the body's + /// craft children: an egui container shown in the body is no cell, and egui places it below the cells placed so + /// far. Content that should take a cell goes in a craft body (`Row`). pub fn grid(columns: impl Into>) -> Self { BodyLayout::Grid { columns: columns.into(), fit: GridFit::Stack, cells: CellAlign::Center } } @@ -328,7 +330,7 @@ pub(crate) fn fill_size(ui: &Ui, id: Id, axis: Axis, measured: f32, offered: f32 // its measuring run, where the child measured at its own size. if axis == Axis::Y && env.content.1 - && let Some(line) = row_line_of(ui, &env).and_then(|line| line.height) + && let Some(line) = env.row_line.and_then(|line| line.height) { return measured.max(line); } @@ -502,7 +504,7 @@ pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(& let shrink = Env::of(ui).shrink; // The unit's content is no unit of the row: it runs in a room of its own, on the row's line only to fill it. Its // children take no slots on the line and report nothing to the row: the unit's block is what stands in the row. - let line = row_line_of(ui, &Env::of(ui)).map(|line| RowLine { places: false, ..line }); + let line = Env::of(ui).row_line.map(|line| RowLine { places: false, ..line }); let own_room = Env::of(ui).derive_local(|scoped| { scoped.start_room(); scoped.row_line = line; @@ -521,13 +523,13 @@ pub fn levelled_unit(ui: &mut Ui, key: Id, levels: usize, mut show: impl FnMut(& }); let width = ui.max_rect().width(); for level in 0..levels.max(1) { - let installed = Env::install_for(ui, no_room.clone()); // Every level shows the same bodies under the same ids: each measures as a probe, so no level reuses a // record another level left, and none serves the sweep at the levels given, which records its own. let (_, took) = layout_memory::probing(&ctx, || { - crate::runtime::egui::sizing::run_sized(ui, width, child::column_layout(rtl), |ui| show(ui, level)) + crate::runtime::egui::sizing::run_sized(ui, width, child::column_layout(rtl), |ui| { + Env::run_in(ui, no_room.clone(), |ui| show(ui, level)) + }) }); - Env::restore(&ctx, installed); if level == 0 { widest = took; } @@ -889,7 +891,7 @@ fn run_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::Layo return inner; } if !shares_along(env, axis) { - return child::block(ui, None, layout, body).0; + return child::block(ui, None, layout, |ui| Env::run_in(ui, env.clone(), body)).0; } let key = sub(id, "share"); child::block(ui, None, layout, |ui| { @@ -943,7 +945,7 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: let ctx = ui.ctx().clone(); let in_child = |ui: &mut Ui, body: &mut dyn FnMut(&mut Ui) -> R| { let mut child = laid_out_child(ui, layout); - let inner = body(&mut child); + let inner = Env::run_in(&mut child, env.clone(), body); (inner, child.min_rect()) }; if !shares_along(env, axis) { @@ -1158,13 +1160,12 @@ impl Spread { fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut(&mut Ui) -> R) -> (R, Option) { let ctx = ui.ctx().clone(); let layout = child::row_layout(rtl, false); - let sweep = |ui: &mut Ui, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { + let env = Env::of(ui); + let sweep = |ui: &mut Ui, env: &Env, last: Option, leasts: Vec, probe: bool, body: &mut dyn FnMut(&mut Ui) -> R| { let flow = Flow::new(ui.available_rect_before_wrap(), rtl); pass_state::with::(&ctx, |cursors| cursors.0.insert(id, Cursor::Spread(Spread::new(flow, gap, last, leasts, probe)))); // The children run in the sweep's own `Ui`: the row's env is installed for it, so they are its direct children. - let installed = Env::install_for(ui, Env::of(ui)); - let inner = body(ui); - Env::restore(&ctx, installed); + let inner = Env::run_in(ui, env.clone(), body); let spread = match pass_state::with::(&ctx, |cursors| cursors.0.remove(&id)) { Some(Cursor::Spread(spread)) => Some(spread), _ => None, @@ -1177,13 +1178,13 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( let count = this_pass(&ctx, false, leasts_id).map_or(0, |count| count.x as usize); let leasts = (0..count).map(|i| this_pass(&ctx, false, sub(id, ("least", i))).map_or(0.0, |least| least.x)).collect(); let last = this_pass(&ctx, false, id); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, last, leasts, false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, last, leasts, false, body)).0; return (inner, natural(&spread)); } let room = ui.available_rect_before_wrap().size(); let ((inner, spread), rect, short) = crate::contract::keeping_ids(&ctx, || { let mut first = ui.new_child(egui::UiBuilder::new().layout(layout)); - let (inner, spread) = sweep(&mut first, None, Vec::new(), false, body); + let (inner, spread) = sweep(&mut first, &env, None, Vec::new(), false, body); // Half a point: less than a pixel shows at any scale the box runs. let short = spread.as_ref().is_some_and(|spread| spread.count >= 2 && room.x.is_finite() && spread.natural > room.x + 0.5); (((inner, spread), first.min_rect(), short), short) @@ -1191,21 +1192,19 @@ fn run_spread(ui: &mut Ui, id: Id, gap: f32, rtl: bool, body: &mut dyn FnMut( let (inner, spread, leasts) = if short { #[cfg(feature = "testing")] measure::count_least(&ctx, id); - let probe = Env::of(ui).derive_local(|scoped| { + let probe = env.derive_local(|scoped| { scoped.unbounded.0 = true; scoped.least = true; }); let leasts = crate::contract::keeping_ids(&ctx, || { let leasts = layout_memory::probing(&ctx, || { let mut least = ui.new_child(egui::UiBuilder::new().layout(layout)); - let installed = Env::install_for(&least, probe.clone()); - let (_, spread) = sweep(&mut least, None, Vec::new(), true, body); - Env::restore(&ctx, installed); + let (_, spread) = sweep(&mut least, &probe, None, Vec::new(), true, body); spread.map_or_else(Vec::new, |spread| spread.widths) }); (leasts, true) }); - let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, None, leasts.clone(), false, body)).0; + let (inner, spread) = child::block(ui, None, layout, |ui| sweep(ui, &env, None, leasts.clone(), false, body)).0; (inner, spread, leasts) } else { ui.advance_cursor_after_rect(rect); @@ -1265,7 +1264,7 @@ pub fn place_in_flow(ui: &mut Ui, size: Vec2) -> Rect { /// and its first line to the container whose header or body it starts. pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { let env = Env::of(ui); - let (line, target) = (row_line_of(ui, &env).filter(|line| line.places), env.first_line); + let (line, target) = (env.row_line.filter(|line| line.places), env.first_line); let child = InFlow { first: if child.line { child.first } else { one_line(child.first, size.y) }, ..child }; // A one-line child of a bracketed row sits with its centre on the bracket's middle, between the controls its // rows reported before it. @@ -1307,18 +1306,6 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { placed } -/// The line of the unwrapped `Row` body a child placed in flow in `ui` stands on, `env` being `ui`'s env: only a direct -/// child of the row has it (`Env::installed_for`). -pub(crate) fn row_line_of(ui: &Ui, env: &Env) -> Option { - env.row_line.filter(|_| Env::installed_for(ui)) -} - -/// The `Grid` or spread `Row` body whose next cell a child placed in flow in `ui` takes, `env` being `ui`'s env: only a -/// direct child of the body takes one (`Env::installed_for`). -fn grid_of(ui: &Ui, env: &Env) -> Option { - env.grid.filter(|_| Env::installed_for(ui)) -} - /// Takes `size` in flow in `ui`: the next cell of the `Grid` or spread `Row` body that encloses it directly, else the /// next allocation of `ui`'s layout. Returns the rect taken and whether it is a cell. pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { @@ -1330,8 +1317,7 @@ pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) { /// cells after it stay in their columns. Outside a grid it does nothing. pub fn empty_cell(ui: &mut Ui) { let env = Env::of(ui); - let grid = - grid_of(ui, &env).filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); + let grid = env.grid.filter(|body| pass_state::with::(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_))))); if grid.is_some() { take_in(ui, &env, Vec2::ZERO); } @@ -1341,8 +1327,7 @@ pub fn empty_cell(ui: &mut Ui) { /// closes. fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { close_flow_start(ui.ctx(), env); - let grid = grid_of(ui, env); - match cell_in(ui, grid, size) { + match cell_in(ui, env.grid, size) { Some(cell) => (cell, true), None => (alloc::space(ui, size), false), } @@ -1352,8 +1337,7 @@ fn take_in(ui: &mut Ui, env: &Env, size: Vec2) -> (Rect, bool) { /// it; `None`, taking nothing, outside such a body. pub(crate) fn take_cell(ui: &mut Ui, size: Vec2) -> Option { let env = Env::of(ui); - let grid = grid_of(ui, &env); - let cell = cell_in(ui, grid, size); + let cell = cell_in(ui, env.grid, size); if cell.is_some() { close_flow_start(ui.ctx(), &env); } @@ -1369,8 +1353,7 @@ fn cell_in(ui: &mut Ui, grid: Option, size: Vec2) -> Option { /// The region the next child shown in flow in `ui` measures and is placed in: that of the next cell of the `Grid` or /// spread `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. pub(crate) fn flow_region(ui: &Ui) -> Rect { - let cell = - grid_of(ui, &Env::of(ui)).and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); + let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::region))); cell.unwrap_or_else(|| ui.available_rect_before_wrap()) } @@ -1384,7 +1367,7 @@ pub(crate) fn row_alone_room(ui: &Ui) -> Option { /// The room a child shown in flow in `ui` measures and sizes in: the room of the next cell of the `Grid` or spread /// `Row` body that encloses `ui` directly, else the rest of `ui`'s layout. pub(crate) fn flow_room(ui: &Ui) -> Vec2 { - let cell = grid_of(ui, &Env::of(ui)).and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); + let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::room))); cell.unwrap_or_else(|| open_room(ui)) } @@ -1411,8 +1394,7 @@ fn open_room(ui: &Ui) -> Vec2 { /// The room a child that fills its width fills in `ui`: `flow_room`, except that in a `Content` column of a `Grid` it /// is the column's width, so the child never measures as the room and pushes the next column out of it. pub(crate) fn flow_fill_room(ui: &Ui) -> Vec2 { - let cell = - grid_of(ui, &Env::of(ui)).and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); + let cell = Env::of(ui).grid.and_then(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).map(Cursor::fill_room))); cell.unwrap_or_else(|| open_room(ui)) } @@ -1434,14 +1416,15 @@ pub(crate) fn shares_y(ui: &Ui) -> bool { /// Whether the next child shown in flow in `ui` goes in a `Content` column of the `Grid` body that encloses `ui` /// directly: like a content-sized column, a child that fills its width is placed at its measured width there. pub(crate) fn in_grid_content_column(ui: &Ui) -> bool { - grid_of(ui, &Env::of(ui)) + Env::of(ui) + .grid .is_some_and(|body| pass_state::with::(ui.ctx(), |cursors| cursors.0.get(&body).is_some_and(Cursor::in_content_column))) } /// The cell the next child shown in flow in `ui` takes, when the body that encloses `ui` directly is a `Grid`: the /// grid's body, the cell's column and whether the column is a `Content` one. pub(crate) fn grid_cell(ui: &Ui) -> Option<(Id, usize, bool)> { - let grid = grid_of(ui, &Env::of(ui))?; + let grid = Env::of(ui).grid?; pass_state::with::(ui.ctx(), |cursors| { let cursor = cursors.0.get(&grid)?; Some((grid, cursor.grid_column()?, cursor.in_content_column())) diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 77090807d..c9afb1e1d 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -26,6 +26,6 @@ pub(crate) use body::run_body; pub(crate) use body::{ BodyLine, BracketTook, HeldKind, InFlow, at_flow_start, close_first_line, close_flow_start_in, counting_fills, fill_share, fill_size, flow_fill_room, flow_region, flow_room, flow_start, grid_cell, held_kind, in_grid_content_column, leaf_fill_room, members_line, open_first_lines, - place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, row_line_of, run_body_measured, shares_y, - shrink_cap, take_bracket, take_cell, take_in_flow, view_room, + place_in_cell, report_bracket_control, report_held, report_least, report_shrink, row_alone_room, run_body_measured, shares_y, shrink_cap, + take_bracket, take_cell, take_in_flow, view_room, }; diff --git a/crates/ui-contract/src/layout/slot.rs b/crates/ui-contract/src/layout/slot.rs index 79e573ffb..e4f26734b 100644 --- a/crates/ui-contract/src/layout/slot.rs +++ b/crates/ui-contract/src/layout/slot.rs @@ -7,6 +7,7 @@ use egui::{Ui, Vec2}; /// Runs `body` in an invisible sizing pass `width` wide and returns the size it took. Nothing is allocated in /// `ui` and nothing is painted; the closure sees the env of `ui`. pub fn measure_slot(ui: &mut Ui, width: f32, body: impl FnOnce(&mut Ui)) -> Vec2 { - let rtl = Env::of(ui).direction.is_rtl(); - sizing::run_sized(ui, width, child::column_layout(rtl), body).1 + let env = Env::of(ui); + let rtl = env.direction.is_rtl(); + sizing::run_sized(ui, width, child::column_layout(rtl), |ui| Env::run_in(ui, env, body)).1 } diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index a76a73908..fd345be5b 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -44,7 +44,7 @@ mod view; pub use app_values::{AppValues, EnvValue, StyleValue}; pub use craft_platform::appearance::SystemReader; use host_words::{host_dates, host_format, host_words}; -pub use overrides::{Overrides, ThemeScope, WheelScope, WordsOverride, with_env}; +pub use overrides::{Overrides, ThemeScope, WheelScope, WordsOverride, flow_scope, with_env}; pub use root::{ResolvedRoot, RootEnv}; pub use system::{SystemState, system_appearance}; pub(crate) use tokens::TokenInputs; @@ -307,8 +307,7 @@ pub(crate) enum ColumnSweep { } /// The line of an unwrapped `Row` body, as its direct children placed in flow see it: a child of one line sits with -/// its centre on the line's centre, and a child of more than one line, or with no line of its own, at its top. Read -/// through `layout::row_line_of`, which gives it only to the direct children (`Env::installed_for`). +/// its centre on the line's centre, and a child of more than one line, or with no line of its own, at its top. #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct RowLine { /// The row body, which the children of a measuring run report their lines to. @@ -417,7 +416,8 @@ impl Scoped { /// Ends the layout room of the enclosing body: its flow grid and content column. The axes the body sizes from its /// content stay (`content`): like `cell_fills` and `least`, they say what a child that fills takes there, its - /// measured size or the room, and the place of a memoized view holds them (`flow`). + /// measured size or the room, and the place of a memoized view holds them (`flow`). `has_room` checks the same set, + /// and `Env::of` ends it for a `Ui` below the one an entry was installed for. pub(crate) fn start_room(&mut self) { self.grid = None; self.grid_top = false; @@ -435,6 +435,24 @@ impl Scoped { self.offered = None; } + /// Whether any of the facts `start_room` ends is set. + fn has_room(&self) -> bool { + self.grid.is_some() + || self.grid_top + || self.content_column + || self.given_column + || self.row_room.is_some() + || self.row_line.is_some() + || self.first_line.is_some() + || self.flow_body.is_some() + || self.column_row + || self.fill_body.is_some() + || self.fill_share.is_some() + || self.shrink.is_some() + || self.column.is_some() + || self.offered.is_some() + } + /// Starts the layout room of a memoized view's content (`start_room`), keeping whether the enclosing body is a /// content-sized or a given column, as `start_room` keeps the content axes. The view's content then measures and /// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from @@ -664,14 +682,27 @@ impl Env { /// The env of `ui`: the nearest entry up the `Ui` stack, else the running viewport's root env, so the `Ui` /// of an egui `Area` or `Window` reads the app's root values. For app panels (layer 8) and caller closures only. /// + /// What a body sets up for the children it places in flow (`Scoped::start_room`: its `Grid` or spread row's cells, + /// its unwrapped row's line and shrink step, its flow start, its content column) is for its direct children, which + /// it shows in the `Ui` it installed its env for. A `Ui` egui code makes below that one (an `egui::Grid`, + /// `ui.horizontal`, `ui.push_id` in a caller's closure) lays out its own children: an entry found for an ancestor + /// of `ui` comes without those facts, so a component there takes no cell, line or shrink step of the body around it. + /// /// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`, outside sizing passes. pub fn of(ui: &Ui) -> Env { let ctx = ui.ctx(); let viewport = pass::current_viewport(ctx); + let own = stack::node_id(ui); let found = PerViewport::::with(ctx, viewport, |envs| { - stack::nearest(ui, |node| envs.entries.get(&node).cloned()).or_else(|| envs.root.clone()) + stack::nearest(ui, |node| envs.entries.get(&node).map(|env| (env.clone(), node == own))) + .or_else(|| envs.root.clone().map(|env| (env, true))) }); - let env = found.unwrap_or_else(|| Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx))); + let env = match found { + Some((env, true)) => env, + Some((env, false)) if env.scoped.has_room() => env.derive_local(Scoped::start_room), + Some((env, false)) => env, + None => Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx)), + }; // egui's `invisible()` also disables the `Ui`, and a sizing `Ui` is invisible, not disabled: in a sizing pass // the env keeps the enabled state the real run has, so a memoized view keys alike in both. if style::is_enabled(ui) || ui.is_sizing_pass() { env } else { env.derive_local(|s| s.enabled = false) } @@ -773,14 +804,12 @@ impl Env { Installed { viewport, node, previous } } - /// Whether `ui` is a `Ui` an env entry was installed for (`install_for`), not one that reads an entry installed - /// further up its stack. What a body sets up for the children it places in flow (its `Grid` or spread row's cells, - /// its unwrapped row's line) is for its direct children, which it shows in the `Ui` it installed its env for. A - /// `Ui` egui code makes inside that one (an `egui::Grid`, `ui.horizontal` in a caller's closure) lays out its own - /// children: a component placed there takes no cell or line of the body around it. - pub(crate) fn installed_for(ui: &Ui) -> bool { - let node = stack::node_id(ui); - PerViewport::::with(ui.ctx(), pass::current_viewport(ui.ctx()), |envs| envs.entries.contains_key(&node)) + /// Runs `body` in `ui` with `env` installed for it, and puts back what the install replaced, also when `body` + /// panics. A body runs its direct children this way in a `Ui` it makes for them. + pub(crate) fn run_in(ui: &mut Ui, env: Env, body: impl FnOnce(&mut Ui) -> R) -> R { + let ctx = ui.ctx().clone(); + let _restore = Restore { ctx: &ctx, installed: Some(Env::install_for(ui, env)) }; + body(ui) } /// Puts back the entry `install_for` replaced. diff --git a/crates/ui-contract/src/runtime/env/overrides.rs b/crates/ui-contract/src/runtime/env/overrides.rs index cb9e7d2c4..8be00d377 100644 --- a/crates/ui-contract/src/runtime/env/overrides.rs +++ b/crates/ui-contract/src/runtime/env/overrides.rs @@ -176,6 +176,15 @@ impl Overrides { } } +/// Runs `body` in a child `Ui` built from `builder`, as `ui.scope_builder` does, under the env of `ui`: the components +/// it shows are children of the body around `ui` as those shown in `ui` itself are, on its line and in its cells. The +/// craft form of `ui.scope`, `ui.push_id` (`UiBuilder::id_salt`) and `ui.with_layout` around craft content: what a +/// body sets up for its children in flow does not reach a `Ui` egui code makes below the body's own (`Env::of`). +pub fn flow_scope(ui: &mut Ui, builder: egui::UiBuilder, body: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { + let env = Env::of(ui); + ui.scope_builder(builder, |child| Env::run_in(child, env, body)) +} + /// Runs `body` in a child `Ui` with `set`'s changes applied to the inherited values. A scope that disables /// disables its child `Ui`; one that changes direction builds the child with an explicit layout and never /// inherits the parent's. diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 237c1014a..6f0f181aa 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -510,26 +510,25 @@ impl Container for let surface_pressed = cx.surface_pressed(); let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; let mut sent = Vec::new(); - let strip = ui - .with_layout(layout, |ui| { - ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) - if let Some(hook) = extra.as_mut() { - hook.run(ui, cx); - } - let row = TabRow { - anchor: self.anchor.clone(), - panels: self.panels.clone(), - active: self.active, - closable: self.closable, - wheel_selects: self.wheel_selects_tabs, - dock: self.dock, - sent: Outbox::new(&mut sent), - }; - // The env around the tab row holds only values its key follows (the shell, the dock's arrangement, a - // floating window's layer), no handle or context rebuilt each pass, so it replays at rest. - MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui) - }) - .inner; + let strip = crate::runtime::env::flow_scope(ui, egui::UiBuilder::new().layout(layout), |ui| { + ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) + if let Some(hook) = extra.as_mut() { + hook.run(ui, cx); + } + let row = TabRow { + anchor: self.anchor.clone(), + panels: self.panels.clone(), + active: self.active, + closable: self.closable, + wheel_selects: self.wheel_selects_tabs, + dock: self.dock, + sent: Outbox::new(&mut sent), + }; + // The env around the tab row holds only values its key follows (the shell, the dock's arrangement, a + // floating window's layer), no handle or context rebuilt each pass, so it replays at rest. + MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui) + }) + .inner; self.extra = extra; // A press on the group's empty body focuses its panel, as in Photoshop. if surface_pressed && let Some(strip) = strip { diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index a869191b7..300c0996e 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -212,6 +212,10 @@ layout_component!( ); layout_component!( /// Children row-major over a column list: a child in flow takes the next cell. + /// + /// The cells are the grid's craft children. An egui container shown in the body (`ui.horizontal`, an + /// `egui::Grid`) is no cell: egui places it below the cells placed so far, its children are not cells, and the + /// next child takes the next cell. Content that should take a cell goes in a craft body (`Row`). Grid, GridStyleKey, [] diff --git a/crates/ui-widgets/src/pickers/date.rs b/crates/ui-widgets/src/pickers/date.rs index d8819c941..0ebb83cd1 100644 --- a/crates/ui-widgets/src/pickers/date.rs +++ b/crates/ui-widgets/src/pickers/date.rs @@ -18,8 +18,9 @@ use crate::buttons::{IconButton, Link}; use crate::choice::Segmented; use crate::contract::{ Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, Input, MeasureCx, Overlay, OverlayUi, Overlays as _, PaintUi, - PartsCx, Props as _, Remember as _, Role, Show as _, WordSetCx as _, clicked, + PartsCx, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, clicked, }; +use crate::layout_components::Row; use crate::primitives::{IconSpec, TextKey, TextOptions, TextRun}; use crate::runtime::env::Label; use crate::text::{Adornment, FieldStyle, place, reserve}; @@ -338,7 +339,7 @@ impl Component for DatePicker<'_> { view = next; } let mut pick = page.picked.map(Some); - ui.horizontal(|ui| { + let _ = Row::new().show(ui, |ui, _| { let at_precision = today.map(|today| match view.precision { DatePrecision::Day => today, DatePrecision::Month => PickedDate::month(today.year, today.month.unwrap_or(1)), diff --git a/crates/ui-widgets/src/pickers/select.rs b/crates/ui-widgets/src/pickers/select.rs index 8aec2a378..f23620475 100644 --- a/crates/ui-widgets/src/pickers/select.rs +++ b/crates/ui-widgets/src/pickers/select.rs @@ -16,6 +16,7 @@ use crate::contract::{ MeasureCx, Numeric, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupHandle, PopupKind, Props as _, Role, Show as _, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, step_stop, step_stops, }; +use crate::layout_components::Row; use crate::list::{List, ListRow, ThumbAspect}; use crate::menu::Menu; use crate::primitives::ContentPainterCx; @@ -318,7 +319,7 @@ impl Component for Select<'_, T> { let list = ui.scope_id().with("options"); let mut query = String::new(); if searchable || header_menu.is_some() { - ui.horizontal(|ui| { + let _ = Row::new().show(ui, |ui, _| { if searchable { query = search::show(ui, body, popup, cx, &name, list); } From 9d928c79546749c764037fc391fa8cb97cfae130 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 21:50:53 +0000 Subject: [PATCH 05/15] Trials: flow facts stop at egui containers, a Lazy keeps the row's line, labels in egui grid cells and narrow horizontals --- crates/ui-widgets/tests/it/layout/row_line.rs | 288 ++++++++++++++---- 1 file changed, 225 insertions(+), 63 deletions(-) diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index b198a9369..30256917e 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -2,17 +2,18 @@ //! than one line (a column, a field with a help line below) sits at the row's top. A control with its label after it //! or above it, and a field labelled above, sit on the line by their control, as a bare control does, in a row and in //! a grid's cell. Components an app shows in an egui container inside a row or grid are laid out by that container: -//! they take neither the row's line nor the grid's cells. +//! they take neither the row's line nor the grid's cells. In an `egui::Grid`'s cell a labelled control decides its +//! label at its own width. use craft_behavior::ColumnWidth; use craft_theme::ControlSize; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::contract::{Bind, FieldLayout, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::Text; -use craft_ui::form::{Field, Help}; +use craft_ui::form::{Field, FieldGroup, Help}; use craft_ui::layout_components::{Grid, Row, Stack}; -use craft_ui::runtime::env::Label; +use craft_ui::runtime::env::{Label, with_env}; use craft_ui::testing::{Fixture, last_pass_measuring_runs, trial}; use egui::Rect; use std::cell::Cell; @@ -167,80 +168,156 @@ fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_ } } +const GRID_ROWS: usize = 3; +type GridBoxes = [(Rect, Rect); GRID_ROWS]; + +/// Two columns of labelled check boxes in an `egui::Grid`, each box run through `wrap` (`ui.show` or a scope around +/// it): the box rects of each row. +fn boxes_grid(ui: &mut egui::Ui, wrap: fn(&mut egui::Ui, Checkbox<'_>) -> Rect) -> GridBoxes { + let mut boxes = [(Rect::NOTHING, Rect::NOTHING); GRID_ROWS]; + egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { + for (row, rect) in boxes.iter_mut().enumerate() { + rect.0 = wrap(ui, Checkbox::new(Bind::given(true)).label(format!("Left {row}"))); + rect.1 = wrap(ui, Checkbox::new(Bind::given(false)).label(format!("Right {row}"))); + ui.end_row(); + } + }); + boxes +} + +fn plain(ui: &mut egui::Ui, check: Checkbox<'_>) -> Rect { + check.show(ui).response.rect +} + +fn read_only(ui: &mut egui::Ui, check: Checkbox<'_>) -> Rect { + with_env(ui, |set| set.read_only = Some(true), |ui| check.show(ui).response.rect) +} + +/// The grid of `boxes_grid` in a 300 pt column, inside an unwrapped `Row` or a `Stack`, with a button after it. +fn grid_in(in_row: bool, wrap: fn(&mut egui::Ui, Checkbox<'_>) -> Rect) -> (GridBoxes, Rect) { + let seen = Rc::new(Cell::new(([(Rect::NOTHING, Rect::NOTHING); GRID_ROWS], Rect::NOTHING))); + let out = Rc::clone(&seen); + let _fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(300.0, 600.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + let mut boxes = [(Rect::NOTHING, Rect::NOTHING); GRID_ROWS]; + if in_row { + Row::new().fill().show(ui, |ui, _| boxes = boxes_grid(ui, wrap)); + } else { + Stack::new().fill().show(ui, |ui, _| boxes = boxes_grid(ui, wrap)); + } + let after = Button::new("After").show(ui).rect; + out.set((boxes, after)); + }); + }); + seen.get() +} + +fn pitch(boxes: &GridBoxes) -> f32 { + boxes[1].0.top() - boxes[0].0.top() +} + /// Check boxes an app lays out in an `egui::Grid` inside a row (a dialog's custom row of two columns of check boxes) /// are no children of the row: the grid's rows are as high as the same grid's outside a row, not as high as the row's /// line, and what follows the row starts under the grid. #[trial] fn check_boxes_in_an_egui_grid_in_a_row_keep_their_own_rows() { - const ROWS: usize = 3; - let shown = |in_row: bool| { - let seen = Rc::new(Cell::new(([(Rect::NOTHING, Rect::NOTHING); ROWS], Rect::NOTHING))); - let out = Rc::clone(&seen); - let _fixture = settled(move |ui| { - let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(300.0, 600.0)); - let out = Rc::clone(&out); - Stack::new().fill().show_at(ui, room, move |ui, _| { - let mut boxes = [(Rect::NOTHING, Rect::NOTHING); ROWS]; - let mut grid = |ui: &mut egui::Ui| { - egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { - for (row, rect) in boxes.iter_mut().enumerate() { - rect.0 = Checkbox::new(Bind::given(true)).label(format!("Left {row}")).show(ui).response.rect; - rect.1 = Checkbox::new(Bind::given(false)).label(format!("Right {row}")).show(ui).response.rect; - ui.end_row(); - } - }); - }; - if in_row { - Row::new().fill().show(ui, |ui, _| grid(ui)); - } else { - Stack::new().fill().show(ui, |ui, _| grid(ui)); - } - let after = Button::new("After").show(ui).rect; - out.set((boxes, after)); - }); - }); - seen.get() - }; - let (alone, _) = shown(false); - let (boxes, after) = shown(true); - for (left, right) in boxes { - assert!((left.center().y - right.center().y).abs() <= ROUNDING, "the two columns share each row: {left:?} {right:?}"); - } - let pitch = |boxes: &[(Rect, Rect); ROWS]| boxes[1].0.top() - boxes[0].0.top(); + let (alone, _) = grid_in(false, plain); + let (boxes, after) = grid_in(true, plain); assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); - assert!(after.top() >= boxes[ROWS - 1].0.bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}"); + assert!(after.top() >= boxes[GRID_ROWS - 1].0.bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}"); } -/// Check boxes in a `ui.horizontal` an app shows in a `Grid` body are laid out by it: side by side on one line, taking -/// none of the grid's cells. +/// The same check boxes, each in an env scope (`with_env`): the scope copies the env it finds in the grid's `Ui`, +/// which holds none of the row's facts, so the grid's rows stay as high as the same grid's outside a row. #[trial] -fn check_boxes_in_an_egui_container_in_a_grid_take_no_cells() { - let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); +fn check_boxes_in_env_scopes_in_an_egui_grid_in_a_row_keep_their_own_rows() { + let (alone, _) = grid_in(false, read_only); + let (boxes, _) = grid_in(true, read_only); + assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); +} + +/// Two columns of labelled check boxes in an `egui::Grid` share each row: the first column's labels are decided at +/// their own width, not wrapped in the narrow column egui offers a column it has no width for yet. +#[trial] +fn two_columns_of_labelled_check_boxes_in_an_egui_grid_share_each_row() { + let (boxes, _) = grid_in(false, plain); + for (left, right) in boxes { + assert!((left.center().y - right.center().y).abs() <= ROUNDING, "the two columns share each row: {left:?} {right:?}"); + assert!(right.left() >= left.right() - ROUNDING, "the right column {right:?} follows the left {left:?}"); + } +} + +/// In a form whose labelled rows share a label column, check boxes in an `egui::Grid` in a full-width row (a dialog's +/// custom row) each sit at their cell's start: none takes the form's label-column indent. +#[trial] +fn check_boxes_in_an_egui_grid_in_a_forms_row_sit_at_their_cells_start() { + let seen = Rc::new(Cell::new([(Rect::NOTHING, Rect::NOTHING); GRID_ROWS])); let out = Rc::clone(&seen); let _fixture = settled(move |ui| { - let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 400.0)); + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 600.0)); let out = Rc::clone(&out); Stack::new().fill().show_at(ui, room, move |ui, _| { - Grid::new(&[ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| { - Text::new("Name").show(ui); - let pair = ui.horizontal(|ui| { - let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect; - let two = Checkbox::new(Bind::given(true)).label("Two").show(ui).response.rect; - (one, two) + FieldGroup::new("Mode").labels(LabelScheme::Form).show(ui, |ui, _| { + Field::new("Name").show(ui, |ui, _| { + Button::new("Pick").show(ui); }); - out.set(pair.inner); + Row::new().fill().show(ui, |ui, _| out.set(boxes_grid(ui, plain))); }); }); }); - let (one, two) = seen.get(); - assert!((one.center().y - two.center().y).abs() <= ROUNDING && two.left() >= one.right() - ROUNDING, "One {one:?}, then Two {two:?} on its line"); + let boxes = seen.get(); + for (row, (left, _)) in boxes.iter().enumerate() { + assert!((left.left() - boxes[0].0.left()).abs() <= ROUNDING, "row {row}'s box {left:?} starts where the first {:?} does", boxes[0].0); + } } -/// Under right-to-left, a check box in a `ui.horizontal` too narrow for its label keeps the label on one line: the -/// row is as wide as its box and label, and the label runs on from its box towards the left, past the room's end. +/// A craft `Grid`'s cells are its craft children. A `ui.horizontal` an app shows in one is no cell: egui lays out its +/// check boxes side by side on one line and places it below the cells placed so far, at the grid's start edge, and the +/// next craft child takes the next cell, beside "Name". #[trial] -fn a_check_box_in_a_narrow_horizontal_keeps_its_label_on_one_line_under_rtl() { +fn check_boxes_in_an_egui_container_in_a_grid_take_no_cells() { + let seen = Rc::new(Cell::new([Rect::NOTHING; 5])); + let out = Rc::clone(&seen); + let fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 400.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + let mut pair = (Rect::NOTHING, Rect::NOTHING); + Grid::new(&[ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| { + Text::new("Name").show(ui); + Text::new("Size").show(ui); + pair = ui + .horizontal(|ui| { + let one = Checkbox::new(Bind::given(true)).label("One").show(ui).response.rect; + let two = Checkbox::new(Bind::given(true)).label("Two").show(ui).response.rect; + (one, two) + }) + .inner; + }); + let after = Button::new("After").show(ui).rect; + out.set([pair.0, pair.1, after, Rect::NOTHING, Rect::NOTHING]); + }); + }); + let [one, two, after, ..] = seen.get(); + let (name, size) = (text(&fixture, "Name"), text(&fixture, "Size")); + assert!((one.center().y - two.center().y).abs() <= ROUNDING && two.left() >= one.right() - ROUNDING, "One {one:?}, then Two {two:?} on its line"); + assert!( + (size.center().y - name.center().y).abs() <= ROUNDING && size.left() >= name.right() - ROUNDING, + "Size {size:?} takes the cell beside Name {name:?}" + ); + assert!(one.top() >= name.bottom() - ROUNDING, "the pair {one:?} lies under Name's row {name:?}"); + assert!(one.left() <= name.left() + ROUNDING, "the pair {one:?} starts at the grid's start edge, as Name {name:?} does"); + assert!(after.top() >= one.bottom().max(two.bottom()) - ROUNDING, "the grid {after:?} reaches past the pair {one:?} {two:?}"); +} + +/// A check box in a `ui.horizontal` too narrow for its label wraps the label at the room's end: egui gives the +/// horizontal the room it has, and nothing runs past it. +#[trial] +fn a_check_box_in_a_narrow_horizontal_wraps_its_label_at_the_rooms_end() { const LONG: &str = "Second option with a long name"; + const WIDTH: f32 = 160.0; let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); let out = Rc::clone(&seen); let mut fixture = Fixture::new(move |ui| { @@ -254,11 +331,96 @@ fn a_check_box_in_a_narrow_horizontal_keeps_its_label_on_one_line_under_rtl() { out.set(pair.inner); }); }); - fixture.direction(craft_i18n::Direction::Rtl).room(egui::vec2(160.0, 200.0)).settle(); + fixture.room(egui::vec2(WIDTH, 200.0)).settle(); fixture.idle(3); - let (one, two) = seen.get(); - let label = text(&fixture, LONG); - assert!(two.right() <= one.left() + ROUNDING, "Two {two:?} follows One {one:?} towards the left"); - assert!(label.height() < two.height() * 1.5, "the label {label:?} stays on one line beside its box {two:?}"); - assert!(label.right() <= two.left() + ROUNDING, "the label {label:?} runs on from its box {two:?} towards the left"); + let (_, two) = seen.get(); + let (label, one_line) = (text(&fixture, LONG), text(&fixture, "One")); + assert!(label.right() <= WIDTH + ROUNDING, "the label {label:?} ends inside the room"); + assert!(label.height() > one_line.height() * 1.5, "the label {label:?} wraps to a second line beside its box {two:?}"); +} + +/// Under right-to-left, labelled check boxes in an `egui::Grid` whose labels lengthen stay in their cells: egui lays +/// the cells out from their left edges in any direction, so on the frame the labels change, the first column's box and +/// label stay right of the grid's left edge, and once settled the second column stays clear of the first. +#[trial] +fn check_boxes_in_an_egui_grid_stay_in_their_cells_under_rtl() { + let name = |column: usize, long: bool| if long { format!("Column {column} with a longer name") } else { format!("C{column}") }; + let long = Rc::new(Cell::new(false)); + let seen = Rc::new(Cell::new([Rect::NOTHING; 3])); + let (out, lengthen) = (Rc::clone(&seen), Rc::clone(&long)); + let mut fixture = Fixture::new(move |ui| { + let (out, long) = (Rc::clone(&out), lengthen.get()); + Stack::new().fill().show(ui, move |ui, _| { + let mut boxes = [Rect::NOTHING; 3]; + // egui lays a grid out left to right only: in a right-to-left egui layout its cursor has no left edge. + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + boxes[2] = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::Vec2::ZERO); + egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { + for (column, rect) in boxes.iter_mut().take(2).enumerate() { + *rect = Checkbox::new(Bind::given(true)).label(name(column, long)).show(ui).response.rect; + } + ui.end_row(); + }); + }); + out.set(boxes); + }); + }); + fixture.direction(craft_i18n::Direction::Rtl).room(egui::vec2(400.0, 200.0)).settle(); + let left = seen.get()[2].left(); + long.set(true); + fixture.frame(vec![]); + for (part, rect) in [("box", seen.get()[0]), ("label", text(&fixture, &name(0, true)))] { + assert!(rect.left() >= left - ROUNDING, "the first column's {part} {rect:?} stays right of the grid's left edge {left}"); + } + fixture.settle(); + let first = seen.get()[0].union(text(&fixture, &name(0, true))); + let second = seen.get()[1].union(text(&fixture, &name(1, true))); + assert!(second.left() >= first.right() - ROUNDING, "the second column {second:?} is clear of the first {first:?}"); +} + +/// A labelled container in an `egui::Grid`'s first column decides its label at its own width: the label stays on one +/// line, and the two columns share the row. +#[trial] +fn a_labelled_row_in_an_egui_grid_keeps_its_label_on_one_line() { + const LONG: &str = "Spacing between the rows"; + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let fixture = settled(move |ui| { + let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(400.0, 300.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + egui::Grid::new("rows").num_columns(2).show(ui, |ui| { + let mut first = Rect::NOTHING; + Field::new(LONG).show(ui, |ui, _| first = Button::new("Go").show(ui).rect); + let second = Button::new("Next").show(ui).rect; + ui.end_row(); + out.set((first, second)); + }); + }); + }); + let (first, second) = seen.get(); + let (label, go) = (text(&fixture, LONG), text(&fixture, "Go")); + assert!(label.height() < go.height() * 1.5, "the label {label:?} stays on one line"); + assert!((first.center().y - second.center().y).abs() <= ROUNDING, "the two columns share the row: {first:?} {second:?}"); +} + +/// A small labelled check box in a plain `Lazy` in a row beside a button sits with its box on the button's line: a +/// `Lazy` runs its content as the row's direct children. +#[trial] +fn a_labelled_check_box_in_a_lazy_in_a_row_sits_on_the_rows_line() { + let seen = Rc::new(Cell::new((Rect::NOTHING, Rect::NOTHING))); + let out = Rc::clone(&seen); + let _fixture = settled(move |ui| { + let out = Rc::clone(&out); + Row::new().show(ui, |ui, _| { + let button = Button::new("Go").show(ui).rect; + let mut check = Rect::NOTHING; + craft_ui::contract::Lazy::new("check", 0.0).show(ui, |ui| { + check = Checkbox::new(Bind::given(true)).label("Snap").size(ControlSize::Sm).show(ui).response.rect; + }); + out.set((button, check)); + }); + }); + let (button, check) = seen.get(); + assert!((button.center().y - check.center().y).abs() <= ROUNDING, "the box {check:?} sits on the button's line {button:?}"); } From 017ecd683f51d9467977830c5917be881e3a7c3e Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 22:46:06 +0000 Subject: [PATCH 06/15] egui: pin storytold/egui next f5025284, whose Grid marks its Ui as UiKind::Grid and lays out left to right craft::egui_fork::REV follows the pin. --- Cargo.lock | 28 ++++++++++++++-------------- Cargo.toml | 28 ++++++++++++++-------------- crates/craft/src/egui_fork.rs | 2 +- 3 files changed, 29 insertions(+), 29 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b61f9f08b..d941f298f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5450,7 +5450,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "emath", @@ -5506,7 +5506,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5541,7 +5541,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "accesskit", "ahash", @@ -5560,7 +5560,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5579,7 +5579,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5599,7 +5599,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", "egui", @@ -5612,7 +5612,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "eframe", "egui", @@ -5689,7 +5689,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "bytemuck", ] @@ -5762,7 +5762,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" dependencies = [ "ahash", "bytemuck", @@ -5788,7 +5788,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[package]] name = "equator" @@ -15119,19 +15119,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=efd532a54d335ca5d7684f5194e7c3a39b2eeebf#efd532a54d335ca5d7684f5194e7c3a39b2eeebf" +source = "git+https://github.com/storytold/egui.git?rev=f5025284445ea19c35f746d96fc0b75468b3f560#f5025284445ea19c35f746d96fc0b75468b3f560" diff --git a/Cargo.toml b/Cargo.toml index c65ccbb18..44b4079a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -310,20 +310,20 @@ hayro-postscript = { path = "vendor/hayro-postscript" } linesweeper = { path = "vendor/linesweeper" } vello_common = { path = "vendor/vello_common" } vello_cpu = { path = "vendor/vello_cpu" } -ecolor = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -emath = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "efd532a54d335ca5d7684f5194e7c3a39b2eeebf" } +ecolor = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +emath = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-winit = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_glow = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_extras = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +eframe = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } +egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "f5025284445ea19c35f746d96fc0b75468b3f560" } winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } # symphonia's FLAC decoder restores LPC samples as `residual + (prediction as i32)`. In a valid diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index acd621c1e..3890d7981 100644 --- a/crates/craft/src/egui_fork.rs +++ b/crates/craft/src/egui_fork.rs @@ -3,7 +3,7 @@ /// The egui fork the library is built and tested with. Apps patch egui to exactly this. pub const GIT: &str = "https://github.com/storytold/egui.git"; /// The commit of [`GIT`]. -pub const REV: &str = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"; +pub const REV: &str = "f5025284445ea19c35f746d96fc0b75468b3f560"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ From 6ca8b40158f714679e9cebd97d64f0c99082f4e8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 22:46:06 +0000 Subject: [PATCH 07/15] Layout: a control finds an egui grid's cell through the UiStack, with_env is the one scope wrapper, an egui cell is decided at what its row needs - Env::of sets Scoped::egui_cell when its walk from a Ui to the entry it finds passes an egui::Grid's Ui; scopes that pass the env on keep it, a body or a component's children end it. It replaces Ui::is_grid in the label step and the container hooks. - In an egui cell the row is decided at what the label and the control at its ideal width need, from the cell's left edge, narrowed as well as widened. - flow_scope folds into with_env (Overrides::id_salt); the dock group header and the Liquify footer are craft Rows. - text_edit and the selectable text read the caller's env before they make their child Ui. - Grid docs: rows after an egui container are placed over it. --- crates/imaging/src/ui/liquify/mod.rs | 5 ++- crates/ui-contract/src/contract/body/hooks.rs | 4 +- crates/ui-contract/src/contract/body/size.rs | 10 +++-- crates/ui-contract/src/contract/cx/context.rs | 3 +- .../ui-contract/src/contract/label/place.rs | 24 +++++----- crates/ui-contract/src/contract/label/step.rs | 20 ++++++--- crates/ui-contract/src/layout/body.rs | 3 +- .../src/primitives/text_adapter.rs | 6 ++- crates/ui-contract/src/runtime/egui/child.rs | 10 +++-- crates/ui-contract/src/runtime/egui/stack.rs | 22 +++++++-- .../ui-contract/src/runtime/egui/text_edit.rs | 7 ++- crates/ui-contract/src/runtime/env.rs | 45 +++++++++++++------ .../ui-contract/src/runtime/env/overrides.rs | 20 ++++----- crates/ui-panels/src/docking/group.rs | 17 +++---- .../ui-widgets/src/layout_components/mod.rs | 5 ++- .../exceptions/craft-ui-panels/docking.toml | 8 ---- 16 files changed, 125 insertions(+), 84 deletions(-) diff --git a/crates/imaging/src/ui/liquify/mod.rs b/crates/imaging/src/ui/liquify/mod.rs index cd382c75e..708bee7dc 100644 --- a/crates/imaging/src/ui/liquify/mod.rs +++ b/crates/imaging/src/ui/liquify/mod.rs @@ -77,11 +77,12 @@ use craft_ui::dialog::{ FieldRefusal, FullWindowCanvas, FullWindowDialog, FullWindowSide, FullWindowTitle, FullWindowView, FullWindowWorkspace, RasterOverlay, WorkspaceCx, WorkspacePass, serde_fields, set_serde_field, }; +use craft_ui::layout::RowAlign; use craft_ui::layout_components::Row; use craft_ui::primitives::Checker; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::commands::{CommandSet as _, Commands as _, FirePhase}; -use craft_ui::runtime::env::{Env, flow_scope}; +use craft_ui::runtime::env::Env; use craft_ui::runtime::memory::{SaveKey, saved_value, set_saved_value}; use craft_ui::runtime::words::CommonWords; use craft_ui::sections::{DialogRole, FooterButton}; @@ -462,7 +463,7 @@ impl LiquifyWorkspace { .opened(open) .buttons([FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)]) .footer(|ui, _| { - let _ = flow_scope(ui, egui::UiBuilder::new().layout(egui::Layout::top_down(egui::Align::Center)), |ui| { + let _ = Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| { let mut guard = this.borrow_mut(); let work: &mut LiquifyWorkspace = &mut guard; let events = Checkbox::new(Bind::given(work.preview)).label(preview_label.clone()).show(ui).events; diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 701d3f3e0..595e3a217 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -297,7 +297,7 @@ impl ShapeHooks for BodyHooks<'_> { self.held = self.held(props, &env); self.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); self.in_column = label::in_column(ui); - self.egui_cell = ui.is_grid(); + self.egui_cell = env.egui_cell; self.given.1 |= self.given_room(props, &env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); let body = if self.presence.visible { Vec2::new(measured.x, measured.y * self.presence.t) } else { Vec2::ZERO }; @@ -1841,7 +1841,7 @@ impl BodyHooks<'_> { self.room.x = width; } self.in_column = label::in_column(at.ui); - self.egui_cell = at.ui.is_grid(); + self.egui_cell = at.env.egui_cell; // A body that fills the main axis of the body it sits in is measured and shown at its share of it. The first // sweep of that body's measuring run only counts it: its contents run in the second sweep, at the share. let (x, y) = (craft_behavior::Axis::X, craft_behavior::Axis::Y); diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 932b2fa41..d3b3dd972 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -29,9 +29,9 @@ pub(super) struct MeasureKey { /// Whether the body shows, and how much of it an animated collapse shows. shows: (bool, f32), env: EnvFacts, - /// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), with a rule just - /// before it (a rule above its header is not drawn), and in a cell of an `egui::Grid`. - flow: (bool, bool, bool), + /// Where its parent flow showed the container: as a row of a vertical flow (`label::in_column`), and with a rule + /// just before it (a rule above its header is not drawn). + flow: (bool, bool), } /// The props a body was measured under, compared on the fields its measure reads. @@ -61,6 +61,7 @@ pub(crate) struct EnvFacts { offered: Option, measure: Option, grid: Option, + egui_cell: bool, } impl EnvFacts { @@ -80,6 +81,7 @@ impl EnvFacts { offered: env.offered, measure: env.measure, grid: env.grid, + egui_cell: env.egui_cell, } } } @@ -95,7 +97,7 @@ impl<'b> BodyHooks<'b> { width, shows: (self.open, self.presence.t), env: EnvFacts::of(env), - flow: (self.in_column, self.after_rule, self.egui_cell), + flow: (self.in_column, self.after_rule), } } diff --git a/crates/ui-contract/src/contract/cx/context.rs b/crates/ui-contract/src/contract/cx/context.rs index 4d1fc6b8b..efb5f8c60 100644 --- a/crates/ui-contract/src/contract/cx/context.rs +++ b/crates/ui-contract/src/contract/cx/context.rs @@ -419,12 +419,13 @@ impl Under { } /// An env derived for children `PaintUi` builds: the composite's resolved `enabled` and `size`, and only the inside -/// label `under` gives. +/// label `under` gives. The composite places its children itself, so they are in no egui grid's cell. pub(crate) fn child_env(env: &Env, under: &Under) -> Env { env.derive_local(|scoped| { scoped.enabled &= under.enabled; scoped.size = under.size; scoped.inside_label = under.inside.clone().map(|inside| inside as crate::runtime::env::Held); scoped.cell_fills = false; + scoped.egui_cell = false; }) } diff --git a/crates/ui-contract/src/contract/label/place.rs b/crates/ui-contract/src/contract/label/place.rs index 11403fc5d..81aaf4a0f 100644 --- a/crates/ui-contract/src/contract/label/place.rs +++ b/crates/ui-contract/src/contract/label/place.rs @@ -95,8 +95,9 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } } let baseline = leaf.baseline.get(); - // An egui grid's cell grows at its right edge in any direction (`LabelIn::egui_cell`); a row grows at its end edge. - let grows = if input.egui_cell { Grows::Right } else { Grows::End }; + // An egui grid's cell is decided at what it needs from its left edge in any direction (`LabelIn::egui_cell`); a + // row grows at its end edge. + let grows = if input.egui_cell { Grows::Cell } else { Grows::End }; if input.side.layout == FieldLayout::Line { let number = env.control(input.size).number; let flow = if input.egui_cell { widened(flow, natural.x + gap + number, grows) } else { flow }; @@ -165,24 +166,25 @@ pub(super) fn decide(ctx: &egui::Context, env: &Env, input: &LabelIn<'_>, kids: } } -/// The edge a flow that is too narrow grows at (`widened`). +/// How a flow takes the width its label and control need (`widened`). #[derive(Clone, Copy)] enum Grows { - /// Its end edge: the left one under RTL. + /// A flow that is too narrow grows at its end edge: the left one under RTL. End, - /// Its right edge, in either direction. - Right, + /// An egui grid's cell: exactly as wide as they need from its left edge, in either direction, narrowed as well as + /// widened. egui offers a grid's last column the rest of the room, where the control would sit at its far edge + /// under RTL. + Cell, } -/// `flow` widened to `need` at the edge `grows` names, when it is narrower. +/// `flow` widened to `need` as `grows` says. fn widened(flow: Flow, need: f32, grows: Grows) -> Flow { let mut wide = flow.rect(); - if wide.width() >= need { - return flow; - } match grows { + Grows::Cell => wide.max.x = wide.min.x + need, + Grows::End if wide.width() >= need => return flow, Grows::End if flow.is_rtl() => wide.min.x = wide.max.x - need, - Grows::End | Grows::Right => wide.max.x = wide.min.x + need, + Grows::End => wide.max.x = wide.min.x + need, } Flow::new(wide, flow.is_rtl()) } diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index f81ab751f..41ca65e0c 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -33,7 +33,8 @@ pub(crate) struct LabelIn<'a> { /// since the column is as wide as the label, the gap and the control need. pub content_row: bool, /// The row is a cell of an `egui::Grid` (`LeafLabel::egui_cell`): the row is as wide as its label and control need, - /// so the label neither wraps nor stacks for want of room, and it grows at its right edge in any direction. + /// so the label neither wraps nor stacks for want of room, and the row is that wide from its left edge in any + /// direction. pub egui_cell: bool, pub text: &'a Label, pub side: &'a SideLabel, @@ -42,6 +43,7 @@ pub(crate) struct LabelIn<'a> { pub enabled: bool, pub size: craft_theme::ControlSize, /// The narrowest the control can be; a row too narrow for the label column, the gap and this stacks the label above. + /// In an egui grid's cell (`egui_cell`), the width the control takes there: a leaf's ideal width. pub control_min: f32, /// The control is a leaf child shown in the flow with its label after it, not a field's body. pub leaf: bool, @@ -85,8 +87,9 @@ pub(crate) struct LeafLabel<'a> { pub parent: Option, /// The row the label and the child share. pub row: Rect, - /// The row is a cell of an `egui::Grid`: egui places it from the cell's left edge in any direction, and gives the - /// column the width it takes from the next frame. `row` then gives only the cell's left edge, top and height. + /// The row is a cell of an `egui::Grid` (`Scoped::egui_cell`): egui places it from the cell's left edge in any + /// direction, and gives the column the width it takes from the next frame. `row` then gives only the cell's left + /// edge, top and height. pub egui_cell: bool, pub text: &'a Label, pub side: &'a SideLabel, @@ -123,7 +126,9 @@ impl LeafPlaced { pub(crate) fn decide_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided { // Read before the child measures: nothing it does there may count as a child placed in flow. let in_column = in_column(ui); - let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x; + // An egui grid's cell is as wide as the row takes, and the control shows at its ideal width there. + let proposal = if at.egui_cell { craft_behavior::Proposal::Ideal } else { craft_behavior::Proposal::Min }; + let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), proposal, Some(at.under)).x; let facts = LeafFacts { control_min, in_column, claims: C::LABELLED_AFTER }; decide_step(ui, env, &leaf_input(env, at, at.row, facts, trailing)) } @@ -401,14 +406,15 @@ fn flow_leaf_row( let row = Rect::from_min_max(avail.min, egui::pos2(avail.max.x, avail.min.y + ideal.y)); // An `egui::Grid` offers a column with no width from the last frame its least cell width, where the label would // wrap and keep the column that narrow: in its cell the label is decided at its own width. - let egui_cell = ui.is_grid(); + let egui_cell = env.egui_cell; let at = LeafLabel { id, owner, parent: None, row, egui_cell, text: &label, side: &side, under: &under }; let decided = decide_leaf(ui, &env, &at, &mut child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size)); // In a column that sizes from its content the row is the label plus the control, never the room around them. // A row of a horizontal flow is as wide as its label and control: the room it has there is unbounded. // So is a grid's cell: the room before it is the whole grid's, and a row spanning it measures its column as wide - // as the grid, so the grid could never set two such cells beside each other (two columns of check boxes). - let content = env.content.0 || ui.layout().is_horizontal() || in_cell; + // as the grid, so the grid could never set two such cells beside each other (two columns of check boxes). An egui + // grid's cell is too, also inside a scope of its own there. + let content = env.content.0 || ui.layout().is_horizontal() || in_cell || egui_cell; let control_width = if content { decided.control().width().min(ideal.x) } else { decided.control().width() }; let rtl = env.direction.is_rtl(); let span = |cell: Rect| Flow::new(Rect::from_min_size(cell.min, Vec2::new(cell.width(), ideal.y)), rtl).span(0.0, control_width); diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 909d0f76e..419419b6c 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -94,7 +94,8 @@ impl BodyLayout { /// Children row-major over `columns`: a `'static` slice, or columns built in the pass. The cells are the body's /// craft children: an egui container shown in the body is no cell, and egui places it below the cells placed so - /// far. Content that should take a cell goes in a craft body (`Row`). + /// far. The rows after it are placed over it: show it as the last child, or put it in a craft body (`Row`), which + /// takes a cell. pub fn grid(columns: impl Into>) -> Self { BodyLayout::Grid { columns: columns.into(), fit: GridFit::Stack, cells: CellAlign::Center } } diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index e9c7866fb..66e1cbf41 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -518,13 +518,13 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut _ => {} } } + let env = crate::runtime::env::Env::of(input.ui); let multiline = input.options.multiline(); let scroll = if multiline { scroll_before(ctx, widget) } else { 0.0 }; let filter = egui_focus::event_filter(input.keys.keep, false); // A single line sits on the baseline of its control's line, whatever its face: a number field's mono digits on // the body text's. let baseline = (!input.options.multiline()).then(|| { - let env = crate::runtime::env::Env::of(input.ui); let text_env = super::text::TextEnv { tokens: &env.tokens, direction: env.direction, ink: input.ink, fonts: crate::fonts::stack_facts(ctx) }; super::text::line_baseline(ctx, &text_env, input.options.role, input.rect.center().y) }); @@ -557,7 +557,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut // egui's widget moves the caret to any press, so the selection from before the press is put back. let secondary = crate::runtime::pointer::frame_raw(ctx).press.is_some_and(|press| press.button == craft_behavior::PointerButton::Secondary); let kept = selection(ctx, widget).filter(|(caret, anchor)| secondary && caret != anchor); - let shown = text_edit::show(input.ui, edit); + let shown = text_edit::show(input.ui, &env, edit); crate::runtime::pointer::record_text_widget(ctx, widget, input.id); if let Some((caret, anchor)) = kept && selection(ctx, widget).is_some_and(|(at, _)| (caret.min(anchor)..=caret.max(anchor)).contains(&at)) @@ -644,6 +644,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { let multiline = run.wrap == crate::primitives::Wrap::Wrap; let keep = if multiline { KeepKeys::BlockArrows } else { KeepKeys::InlineArrows }; let mut shown = layout.full().to_owned(); + let env = crate::runtime::env::Env::of(ui); // A line longer than its room is cut at the room's edge, as a field's is. let mut cut = (layout.size().x > rect.width()).then(|| { let mut cut = crate::runtime::egui::alloc::child(ui, egui::UiBuilder::new().max_rect(rect)); @@ -652,6 +653,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { }); text_edit::show( cut.as_mut().unwrap_or(&mut *ui), + &env, text_edit::Edit { id: widget, rect: layout.galley.rect.translate(at.to_vec2()), diff --git a/crates/ui-contract/src/runtime/egui/child.rs b/crates/ui-contract/src/runtime/egui/child.rs index 9831d7b7e..19aef6e35 100644 --- a/crates/ui-contract/src/runtime/egui/child.rs +++ b/crates/ui-contract/src/runtime/egui/child.rs @@ -43,10 +43,14 @@ pub(crate) fn column_layout(right_to_left: bool) -> Layout { stack_layout(right_to_left) } -/// Runs `body` in a child `Ui`. `disabled` disables the child and everything below it. `direction` gives the -/// child a cloned style carrying that direction and an explicit layout, never the parent's. -pub(crate) fn scope(ui: &mut Ui, disabled: bool, direction: Option, body: impl FnOnce(&mut Ui) -> R) -> R { +/// Runs `body` in a child `Ui`, with the id salt `id_salt` when given. `disabled` disables the child and everything +/// below it. `direction` gives the child a cloned style carrying that direction and an explicit layout, never the +/// parent's. +pub(crate) fn scope(ui: &mut Ui, id_salt: Option, disabled: bool, direction: Option, body: impl FnOnce(&mut Ui) -> R) -> R { let mut builder = UiBuilder::new(); + if let Some(salt) = id_salt { + builder = builder.id_salt(salt); + } if let Some(right_to_left) = direction { let mut style = (**ui.style()).clone(); style.right_to_left = right_to_left; diff --git a/crates/ui-contract/src/runtime/egui/stack.rs b/crates/ui-contract/src/runtime/egui/stack.rs index 71d3bea9a..e5cff8766 100644 --- a/crates/ui-contract/src/runtime/egui/stack.rs +++ b/crates/ui-contract/src/runtime/egui/stack.rs @@ -1,13 +1,29 @@ //! `UiStack` walks for `Env::of`. -use egui::{Id, Ui}; +use egui::{Id, Ui, UiKind}; /// The unique id of `ui`'s stack node: the key env entries are installed under. pub(crate) fn node_id(ui: &Ui) -> Id { ui.stack().unique_id } +/// What `nearest` found walking from a `Ui` outwards. +pub(crate) struct Found { + /// The first value found, and whether it was found for the `Ui`'s own node. + pub value: Option<(T, bool)>, + /// The walk passed the `Ui` of an `egui::Grid` (`UiKind::Grid`) before the node the value was found for, or + /// anywhere on the stack when none was found. + pub grid: bool, +} + /// The first value `lookup` finds walking from `ui` outwards, by the stack nodes' unique ids. -pub(crate) fn nearest(ui: &Ui, lookup: impl Fn(Id) -> Option) -> Option { - ui.stack().iter().find_map(|node| lookup(node.unique_id)) +pub(crate) fn nearest(ui: &Ui, lookup: impl Fn(Id) -> Option) -> Found { + let mut grid = false; + for (depth, node) in ui.stack().iter().enumerate() { + if let Some(value) = lookup(node.unique_id) { + return Found { value: Some((value, depth == 0)), grid }; + } + grid |= node.kind() == Some(UiKind::Grid); + } + Found { value: None, grid } } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 7a432c2b6..300e08ea4 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -65,8 +65,8 @@ pub(crate) struct Shown { pub content: f32, } -/// Runs the widget at `edit.rect`. -pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { +/// Runs the widget at `edit.rect`, under `env`, the env of the `Ui` the caller shows the field in. +pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) -> Shown { let Edit { id, rect, @@ -93,7 +93,6 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { scroll, } = edit; // The same font and optical size as a label of the same role: one text path. - let env = crate::runtime::env::Env::of(ui); let tokens = &env.tokens; // Behind selected text and the selected text itself: the field's roles. let selection = (tokens.color.accent.soft, tokens.color.text.normal); @@ -177,7 +176,7 @@ pub(crate) fn show(ui: &mut Ui, edit: Edit<'_>) -> Shown { super::style::disable_without_fade(ui); } // The placeholder is the faint text colour, the disabled one when the field is off. - let text_colors = &crate::runtime::env::Env::of(ui).tokens.color.text; + let text_colors = &tokens.color.text; super::style::set_hint_color(ui, crate::style::rgba_color(if enabled { text_colors.faint } else { text_colors.disabled })); super::style::set_text_cursor(ui, caret_visible); super::style::set_text_selection(ui, crate::style::rgba_color(selection.0), crate::style::rgba_color(selection.1)); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index fd345be5b..9c1cd92ef 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -44,7 +44,7 @@ mod view; pub use app_values::{AppValues, EnvValue, StyleValue}; pub use craft_platform::appearance::SystemReader; use host_words::{host_dates, host_format, host_words}; -pub use overrides::{Overrides, ThemeScope, WheelScope, WordsOverride, flow_scope, with_env}; +pub use overrides::{Overrides, ThemeScope, WheelScope, WordsOverride, with_env}; pub use root::{ResolvedRoot, RootEnv}; pub use system::{SystemState, system_appearance}; pub(crate) use tokens::TokenInputs; @@ -90,6 +90,7 @@ pub(crate) struct Flow { unbounded: (bool, bool), cell_fills: bool, fits: bool, + egui_cell: bool, } /// The values of an env. @@ -216,6 +217,12 @@ pub struct Scoped { /// The scope is the body of a beside label in an inspector (`LabelScheme::Inspector`): the control shown there /// fills the width the label leaves. Only that control sees it, as with `inside_label`. pub(crate) cell_fills: bool, + /// The scope lays out in a cell of an `egui::Grid` that egui code made below the body around it: the grid places + /// each child from its cell's left edge in any direction, and gives the column the width the child takes from the + /// next frame. `Env::of` sets it where the stack between a `Ui` and its entry holds a grid's `Ui`; a scope that + /// passes `Env::of` on (`with_env`, `Lazy`, a memoized view) keeps it, and a body (`start_room`) or a component's + /// children (`child_env`) end it. + pub(crate) egui_cell: bool, } /// The values of an env that a scope rarely changes: the resolved tokens, the platform, the language and the app's @@ -433,9 +440,10 @@ impl Scoped { self.shrink = None; self.column = None; self.offered = None; + self.egui_cell = false; } - /// Whether any of the facts `start_room` ends is set. + /// Whether any of the facts `start_room` ends is set, besides `egui_cell`, which `Env::of` sets. fn has_room(&self) -> bool { self.grid.is_some() || self.grid_top @@ -454,7 +462,8 @@ impl Scoped { } /// Starts the layout room of a memoized view's content (`start_room`), keeping whether the enclosing body is a - /// content-sized or a given column, as `start_room` keeps the content axes. The view's content then measures and + /// content-sized or a given column and whether the view lies in an egui grid's cell, as `start_room` keeps the + /// content axes. The view's content then measures and /// fills as it would shown without the view: a child that fills takes its measured size where the body sizes from /// content, never the open room. Where a leaf shown here would fit its room (`view_fits`), the leaves of the view's /// content fit the room the view is given (`Shrink::Fit`). A view that is a unit of a shrinking `Row` sizes from its @@ -463,9 +472,9 @@ impl Scoped { pub(crate) fn start_view_room(&mut self) { let fits = self.view_fits(); let row_unit = matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))); - let (content_column, given_column) = (self.content_column, self.given_column); + let (content_column, given_column, egui_cell) = (self.content_column, self.given_column, self.egui_cell); self.start_room(); - (self.content_column, self.given_column) = (content_column, given_column); + (self.content_column, self.given_column, self.egui_cell) = (content_column, given_column, egui_cell); if fits { self.shrink = Some(Shrink::Fit); } @@ -524,6 +533,7 @@ impl Scoped { unbounded: self.unbounded, cell_fills: self.cell_fills, fits: self.view_fits(), + egui_cell: self.egui_cell, } } @@ -675,6 +685,7 @@ impl Env { item_facts: None, inside_label: None, cell_fills: false, + egui_cell: false, }), } } @@ -687,21 +698,27 @@ impl Env { /// it shows in the `Ui` it installed its env for. A `Ui` egui code makes below that one (an `egui::Grid`, /// `ui.horizontal`, `ui.push_id` in a caller's closure) lays out its own children: an entry found for an ancestor /// of `ui` comes without those facts, so a component there takes no cell, line or shrink step of the body around it. + /// Where that stack holds an `egui::Grid`'s `Ui`, the env says the component lays out in the grid's cell + /// (`Scoped::egui_cell`). /// /// While apps still use `add_enabled_ui`, it also ANDs `ui.is_enabled()`, outside sizing passes. pub fn of(ui: &Ui) -> Env { let ctx = ui.ctx(); let viewport = pass::current_viewport(ctx); - let own = stack::node_id(ui); - let found = PerViewport::::with(ctx, viewport, |envs| { - stack::nearest(ui, |node| envs.entries.get(&node).map(|env| (env.clone(), node == own))) - .or_else(|| envs.root.clone().map(|env| (env, true))) + // The root env stands for an entry above the whole stack. + let (found, grid) = PerViewport::::with(ctx, viewport, |envs| { + let stack::Found { value, grid } = stack::nearest(ui, |node| envs.entries.get(&node).cloned()); + (value.or_else(|| envs.root.clone().map(|env| (env, false))), grid) }); - let env = match found { - Some((env, true)) => env, - Some((env, false)) if env.scoped.has_room() => env.derive_local(Scoped::start_room), - Some((env, false)) => env, - None => Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx)), + let (env, own) = found.unwrap_or_else(|| (Env::from_root(ctx, &RootEnv::fallback(ctx), None, scale::pixels_per_point(ctx)), false)); + let egui_cell = env.egui_cell || grid; + let env = if own || !(env.scoped.has_room() || egui_cell != env.egui_cell) { + env + } else { + env.derive_local(|scoped| { + scoped.start_room(); + scoped.egui_cell = egui_cell; + }) }; // egui's `invisible()` also disables the `Ui`, and a sizing `Ui` is invisible, not disabled: in a sizing pass // the env keeps the enabled state the real run has, so a memoized view keys alike in both. diff --git a/crates/ui-contract/src/runtime/env/overrides.rs b/crates/ui-contract/src/runtime/env/overrides.rs index 8be00d377..ab64df1e3 100644 --- a/crates/ui-contract/src/runtime/env/overrides.rs +++ b/crates/ui-contract/src/runtime/env/overrides.rs @@ -128,6 +128,8 @@ pub struct Overrides { pub words: Option, /// App values set for the scope. pub values: AppValues, + /// The child `Ui`'s id salt, as `ui.push_id` gives it: the ids of what it shows derive from it. + pub id_salt: Option, } /// How a scope changes the built-in text: the only override path for words. @@ -176,27 +178,25 @@ impl Overrides { } } -/// Runs `body` in a child `Ui` built from `builder`, as `ui.scope_builder` does, under the env of `ui`: the components -/// it shows are children of the body around `ui` as those shown in `ui` itself are, on its line and in its cells. The -/// craft form of `ui.scope`, `ui.push_id` (`UiBuilder::id_salt`) and `ui.with_layout` around craft content: what a -/// body sets up for its children in flow does not reach a `Ui` egui code makes below the body's own (`Env::of`). -pub fn flow_scope(ui: &mut Ui, builder: egui::UiBuilder, body: impl FnOnce(&mut Ui) -> R) -> egui::InnerResponse { - let env = Env::of(ui); - ui.scope_builder(builder, |child| Env::run_in(child, env, body)) -} - /// Runs `body` in a child `Ui` with `set`'s changes applied to the inherited values. A scope that disables /// disables its child `Ui`; one that changes direction builds the child with an explicit layout and never /// inherits the parent's. +/// +/// The components the child `Ui` shows are children of the body around `ui` as those shown in `ui` itself are, on its +/// line and in its cells. It is the craft form of `ui.scope` and +/// `ui.push_id` (`Overrides::id_salt`) around craft content: what a body sets up for its children in flow does not +/// reach a `Ui` egui code makes below the body's own (`Env::of`). Content laid out along the other axis goes in a +/// craft `Row` or `Stack`, a body of its own. pub fn with_env(ui: &mut Ui, set: impl FnOnce(&mut Overrides), body: impl FnOnce(&mut Ui) -> R) -> R { let mut overrides = Overrides::default(); set(&mut overrides); + let id_salt = overrides.id_salt.take(); let outer = Env::of(ui); let ctx = ui.ctx().clone(); let inner = outer.derive(|scoped| overrides.apply(&ctx, scoped)); let direction = (inner.direction != outer.direction).then(|| inner.direction.is_rtl()); let disabled = !inner.enabled; - child::scope(ui, disabled, direction, |child| { + child::scope(ui, id_salt, disabled, direction, |child| { let _restore = Restore { ctx: &ctx, installed: Some(Env::install_for(child, inner)) }; body(child) }) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 6f0f181aa..85eb040a6 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -9,10 +9,11 @@ use super::{PanelDrag, PanelKey, PanelTitle, Titles}; use crate::buttons::IconButton; use crate::contract::overlay::Anchor; use crate::contract::{ - Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, HeaderEdge, HeaderParts, HeaderRegion, + Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, Gap, HeaderEdge, HeaderParts, HeaderRegion, ListDrag, MeasureCx, MemoProps, MemoView, Name, Outbox, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, }; +use crate::layout_components::Row; use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; @@ -504,14 +505,11 @@ impl Container for let started = drop::started(&cx.env); let mut extra = self.extra.take(); let env = crate::runtime::env::Env::of(ui); - let rtl = env.direction.is_rtl(); - let (line, gap) = (env.tokens.size.panel_header, env.tokens.space.gap.item); - ui.set_min_height(line); + ui.set_min_height(env.tokens.size.panel_header); let surface_pressed = cx.surface_pressed(); - let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; let mut sent = Vec::new(); - let strip = crate::runtime::env::flow_scope(ui, egui::UiBuilder::new().layout(layout), |ui| { - ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) + let mut strip = None; + let _ = Row::new().fill_width().gap(Gap::Item).show(ui, |ui, _| { if let Some(hook) = extra.as_mut() { hook.run(ui, cx); } @@ -526,9 +524,8 @@ impl Container for }; // The env around the tab row holds only values its key follows (the shell, the dock's arrangement, a // floating window's layer), no handle or context rebuilt each pass, so it replays at rest. - MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui) - }) - .inner; + strip = MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui); + }); self.extra = extra; // A press on the group's empty body focuses its panel, as in Photoshop. if surface_pressed && let Some(strip) = strip { diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index 300c0996e..d75c71c8b 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -214,8 +214,9 @@ layout_component!( /// Children row-major over a column list: a child in flow takes the next cell. /// /// The cells are the grid's craft children. An egui container shown in the body (`ui.horizontal`, an - /// `egui::Grid`) is no cell: egui places it below the cells placed so far, its children are not cells, and the - /// next child takes the next cell. Content that should take a cell goes in a craft body (`Row`). + /// `egui::Grid`) is no cell: egui places it below the cells placed so far, and its children are not cells. The + /// rows after it are placed over it, since the grid's rows do not count it: show it as the last child, or put it + /// in a craft body (`Row`), which takes a cell. Grid, GridStyleKey, [] diff --git a/design/exceptions/craft-ui-panels/docking.toml b/design/exceptions/craft-ui-panels/docking.toml index 1bfc5dd49..c7dc26bf5 100644 --- a/design/exceptions/craft-ui-panels/docking.toml +++ b/design/exceptions/craft-ui-panels/docking.toml @@ -1,13 +1,5 @@ config_version = 1 -[[exception]] -name = "dock-header-gap" -kind = "marker" -rule = "style-mutation" -path = "crates/ui-panels/src/docking/group.rs" -reason = "The header lays its title cells with an egui layout and sets that layout gap." -count = 1 - [[exception]] name = "iconic-story-stage" kind = "marker" From a2cb4687ce5693ca2225516d19cb5846ee21281d Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 22:46:07 +0000 Subject: [PATCH 08/15] Trials: labelled check boxes in scopes in an egui grid cell keep one line and shared rows; an egui grid directly in a right-to-left body or row stays finite and as wide as under left-to-right --- crates/ui-widgets/tests/it/layout/row_line.rs | 148 +++++++++++++----- 1 file changed, 107 insertions(+), 41 deletions(-) diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 30256917e..e210f3331 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -172,32 +172,45 @@ const GRID_ROWS: usize = 3; type GridBoxes = [(Rect, Rect); GRID_ROWS]; /// Two columns of labelled check boxes in an `egui::Grid`, each box run through `wrap` (`ui.show` or a scope around -/// it): the box rects of each row. -fn boxes_grid(ui: &mut egui::Ui, wrap: fn(&mut egui::Ui, Checkbox<'_>) -> Rect) -> GridBoxes { +/// it) with its index: the box rects of each row. +fn boxes_grid(ui: &mut egui::Ui, wrap: Wrap) -> GridBoxes { let mut boxes = [(Rect::NOTHING, Rect::NOTHING); GRID_ROWS]; egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { for (row, rect) in boxes.iter_mut().enumerate() { - rect.0 = wrap(ui, Checkbox::new(Bind::given(true)).label(format!("Left {row}"))); - rect.1 = wrap(ui, Checkbox::new(Bind::given(false)).label(format!("Right {row}"))); + rect.0 = wrap(ui, 2 * row, Checkbox::new(Bind::given(true)).label(format!("Left {row}"))); + rect.1 = wrap(ui, 2 * row + 1, Checkbox::new(Bind::given(false)).label(format!("Right {row}"))); ui.end_row(); } }); boxes } -fn plain(ui: &mut egui::Ui, check: Checkbox<'_>) -> Rect { +/// How `boxes_grid` shows each check box in its cell. +type Wrap = fn(&mut egui::Ui, usize, Checkbox<'_>) -> Rect; + +fn plain(ui: &mut egui::Ui, _: usize, check: Checkbox<'_>) -> Rect { check.show(ui).response.rect } -fn read_only(ui: &mut egui::Ui, check: Checkbox<'_>) -> Rect { +fn read_only(ui: &mut egui::Ui, _: usize, check: Checkbox<'_>) -> Rect { with_env(ui, |set| set.read_only = Some(true), |ui| check.show(ui).response.rect) } +fn pushed(ui: &mut egui::Ui, index: usize, check: Checkbox<'_>) -> Rect { + ui.push_id(index, |ui| check.show(ui).response.rect).inner +} + /// The grid of `boxes_grid` in a 300 pt column, inside an unwrapped `Row` or a `Stack`, with a button after it. -fn grid_in(in_row: bool, wrap: fn(&mut egui::Ui, Checkbox<'_>) -> Rect) -> (GridBoxes, Rect) { +fn grid_in(in_row: bool, wrap: Wrap) -> (GridBoxes, Rect) { + let (boxes, after, _) = grid_shown(in_row, wrap); + (boxes, after) +} + +/// `grid_in`, with the fixture it ran in. +fn grid_shown(in_row: bool, wrap: Wrap) -> (GridBoxes, Rect, Fixture) { let seen = Rc::new(Cell::new(([(Rect::NOTHING, Rect::NOTHING); GRID_ROWS], Rect::NOTHING))); let out = Rc::clone(&seen); - let _fixture = settled(move |ui| { + let fixture = settled(move |ui| { let room = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::vec2(300.0, 600.0)); let out = Rc::clone(&out); Stack::new().fill().show_at(ui, room, move |ui, _| { @@ -211,7 +224,8 @@ fn grid_in(in_row: bool, wrap: fn(&mut egui::Ui, Checkbox<'_>) -> Rect) -> (Grid out.set((boxes, after)); }); }); - seen.get() + let (boxes, after) = seen.get(); + (boxes, after, fixture) } fn pitch(boxes: &GridBoxes) -> f32 { @@ -229,13 +243,26 @@ fn check_boxes_in_an_egui_grid_in_a_row_keep_their_own_rows() { assert!(after.top() >= boxes[GRID_ROWS - 1].0.bottom() - ROUNDING, "the button {after:?} is under the grid {boxes:?}"); } -/// The same check boxes, each in an env scope (`with_env`): the scope copies the env it finds in the grid's `Ui`, -/// which holds none of the row's facts, so the grid's rows stay as high as the same grid's outside a row. +/// The same check boxes, each in a scope of its own in its cell (an env scope, `with_env`, or `ui.push_id`): the scope +/// holds none of the row's facts, so the grid's rows stay as high as the same grid's outside a row, and the boxes are +/// still in the grid's cells: the labels stay on one line and the two columns share each row. #[trial] -fn check_boxes_in_env_scopes_in_an_egui_grid_in_a_row_keep_their_own_rows() { - let (alone, _) = grid_in(false, read_only); - let (boxes, _) = grid_in(true, read_only); - assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); +fn check_boxes_in_scopes_in_an_egui_grid_in_a_row_keep_their_own_rows_and_lines() { + for (scope, wrap) in [("with_env", read_only as Wrap), ("push_id", pushed)] { + let (alone, _) = grid_in(false, wrap); + let (boxes, after, fixture) = grid_shown(true, wrap); + assert!((pitch(&boxes) - pitch(&alone)).abs() <= ROUNDING, "{scope}: the grid rows in a row {boxes:?} are as high as outside one {alone:?}"); + let line = text(&fixture, "After").height(); + for (row, (left, right)) in boxes.iter().enumerate() { + for name in [format!("Left {row}"), format!("Right {row}")] { + let label = text(&fixture, &name); + assert!(label.height() < line * 1.5, "{scope}: the label {name} {label:?} stays on one line"); + } + assert!((left.center().y - right.center().y).abs() <= ROUNDING, "{scope}: the two columns share each row: {left:?} {right:?}"); + assert!(right.left() >= left.right() - ROUNDING, "{scope}: the right column {right:?} follows the left {left:?}"); + } + assert!(after.top() >= boxes[GRID_ROWS - 1].0.bottom() - ROUNDING, "{scope}: the button {after:?} is under the grid {boxes:?}"); + } } /// Two columns of labelled check boxes in an `egui::Grid` share each row: the first column's labels are decided at @@ -339,43 +366,82 @@ fn a_check_box_in_a_narrow_horizontal_wraps_its_label_at_the_rooms_end() { assert!(label.height() > one_line.height() * 1.5, "the label {label:?} wraps to a second line beside its box {two:?}"); } -/// Under right-to-left, labelled check boxes in an `egui::Grid` whose labels lengthen stay in their cells: egui lays -/// the cells out from their left edges in any direction, so on the frame the labels change, the first column's box and -/// label stay right of the grid's left edge, and once settled the second column stays clear of the first. -#[trial] -fn check_boxes_in_an_egui_grid_stay_in_their_cells_under_rtl() { - let name = |column: usize, long: bool| if long { format!("Column {column} with a longer name") } else { format!("C{column}") }; - let long = Rc::new(Cell::new(false)); +/// One row of two labelled check boxes in an `egui::Grid` shown directly in a `Stack`, or in a `Row` in it (a dialog's +/// custom row), in a 400 pt room under `direction`; `long` lengthens the labels. Records the two boxes and the grid's +/// rect. +fn one_row_grid(in_row: bool, direction: craft_i18n::Direction, long: &Rc>) -> (Fixture, Rc>) { let seen = Rc::new(Cell::new([Rect::NOTHING; 3])); - let (out, lengthen) = (Rc::clone(&seen), Rc::clone(&long)); + let (out, lengthen) = (Rc::clone(&seen), Rc::clone(long)); let mut fixture = Fixture::new(move |ui| { let (out, long) = (Rc::clone(&out), lengthen.get()); - Stack::new().fill().show(ui, move |ui, _| { + let grid = move |ui: &mut egui::Ui| { let mut boxes = [Rect::NOTHING; 3]; - // egui lays a grid out left to right only: in a right-to-left egui layout its cursor has no left edge. - ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { - boxes[2] = Rect::from_min_size(ui.available_rect_before_wrap().min, egui::Vec2::ZERO); - egui::Grid::new("boxes").num_columns(2).spacing([24.0, 6.0]).show(ui, |ui| { + boxes[2] = egui::Grid::new("boxes") + .num_columns(2) + .spacing([24.0, 6.0]) + .show(ui, |ui| { for (column, rect) in boxes.iter_mut().take(2).enumerate() { - *rect = Checkbox::new(Bind::given(true)).label(name(column, long)).show(ui).response.rect; + *rect = Checkbox::new(Bind::given(true)).label(column_name(column, long)).show(ui).response.rect; } ui.end_row(); - }); - }); + }) + .response + .rect; out.set(boxes); + }; + Stack::new().fill().show(ui, move |ui, _| { + if in_row { + Row::new().fill().show(ui, |ui, _| grid(ui)); + } else { + grid(ui); + } }); }); - fixture.direction(craft_i18n::Direction::Rtl).room(egui::vec2(400.0, 200.0)).settle(); - let left = seen.get()[2].left(); - long.set(true); - fixture.frame(vec![]); - for (part, rect) in [("box", seen.get()[0]), ("label", text(&fixture, &name(0, true)))] { - assert!(rect.left() >= left - ROUNDING, "the first column's {part} {rect:?} stays right of the grid's left edge {left}"); + fixture.direction(direction).room(egui::vec2(400.0, 200.0)).settle(); + (fixture, seen) +} + +fn column_name(column: usize, long: bool) -> String { + if long { format!("Column {column} with a longer name") } else { format!("C{column}") } +} + +/// What the cells of `one_row_grid` show: each column's box and label. +fn cells(fixture: &Fixture, boxes: [Rect; 3]) -> [Rect; 2] { + [0, 1].map(|column| boxes[column].union(text(fixture, &column_name(column, true)))) +} + +/// Under right-to-left, labelled check boxes in an `egui::Grid` shown directly in a right-to-left body, or in a row +/// there, stay in their cells: egui lays a grid out from its left edge in any direction, so the grid's rect is finite, +/// on the frame the labels lengthen the first column's box and label stay right of the grid's left edge, once settled +/// the second column stays clear of the first, and the cells take as much width as under left-to-right: the last +/// column is as wide as its box and label, not the rest of the room. +#[trial] +fn check_boxes_in_an_egui_grid_stay_in_their_cells_under_rtl() { + for in_row in [false, true] { + let ltr = { + let long = Rc::new(Cell::new(true)); + let (mut fixture, seen) = one_row_grid(in_row, craft_i18n::Direction::Ltr, &long); + fixture.settle(); + cells(&fixture, seen.get()) + }; + let long = Rc::new(Cell::new(false)); + let (mut fixture, seen) = one_row_grid(in_row, craft_i18n::Direction::Rtl, &long); + let grid = seen.get()[2]; + assert!(grid.is_finite(), "in a row {in_row}: the grid's rect {grid:?} is finite"); + long.set(true); + fixture.frame(vec![]); + for (part, rect) in [("box", seen.get()[0]), ("label", text(&fixture, &column_name(0, true)))] { + assert!( + rect.left() >= grid.left() - ROUNDING, + "in a row {in_row}: the first column's {part} {rect:?} stays right of the grid's left edge {grid:?}" + ); + } + fixture.settle(); + let [first, second] = cells(&fixture, seen.get()); + assert!(second.left() >= first.right() - ROUNDING, "in a row {in_row}: the second column {second:?} is clear of the first {first:?}"); + let (width, ltr_width) = (first.union(second).width(), ltr[0].union(ltr[1]).width()); + assert!((width - ltr_width).abs() <= ROUNDING, "in a row {in_row}: the cells take {width} under RTL, as under LTR ({ltr_width})"); } - fixture.settle(); - let first = seen.get()[0].union(text(&fixture, &name(0, true))); - let second = seen.get()[1].union(text(&fixture, &name(1, true))); - assert!(second.left() >= first.right() - ROUNDING, "the second column {second:?} is clear of the first {first:?}"); } /// A labelled container in an `egui::Grid`'s first column decides its label at its own width: the label stays on one From 8924367ed088d0ac44ab7531672600bcbf90f3c0 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 23:09:50 +0000 Subject: [PATCH 09/15] Select: a story with the searchable dropdown open --- crates/ui-widgets/src/pickers/select/stories.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/crates/ui-widgets/src/pickers/select/stories.rs b/crates/ui-widgets/src/pickers/select/stories.rs index 3c9e689c8..d87e26971 100644 --- a/crates/ui-widgets/src/pickers/select/stories.rs +++ b/crates/ui-widgets/src/pickers/select/stories.rs @@ -115,6 +115,12 @@ fn select_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { Select::new("Blend mode", data.bind("open", 1u8), &entries).show(ui).into() } +#[story(Select<'static, u8>, covers = [Open], drive = Drive::Custom(open_listbox))] +fn select_searchable_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let entries = resampling(); + Select::new("Resampling", data.bind("searchable_open", 2u8), &entries).searchable().show(ui).into() +} + #[story(Select<'static, u8>, covers = [], disabled_text = "Pick a layer first")] fn select_with_reason(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let entries = modes(); From 8ef85cc4a80eeff5f8df0973c354b1179c6e02ef Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 00:07:47 +0000 Subject: [PATCH 10/15] Dock group header: a raw egui layout again; its side-by-side items take none of the header column's flow facts, the tab row takes the rest of the line and a settled header runs no Row --- crates/ui-panels/src/docking/group.rs | 49 +++++++++++-------- .../exceptions/craft-ui-panels/docking.toml | 8 +++ 2 files changed, 36 insertions(+), 21 deletions(-) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 85eb040a6..5bdc7e57d 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -9,11 +9,10 @@ use super::{PanelDrag, PanelKey, PanelTitle, Titles}; use crate::buttons::IconButton; use crate::contract::overlay::Anchor; use crate::contract::{ - Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, Gap, HeaderEdge, HeaderParts, HeaderRegion, + Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, ContextMenuRequest, Cx, HeaderEdge, HeaderParts, HeaderRegion, ListDrag, MeasureCx, MemoProps, MemoView, Name, Outbox, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role, ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, }; -use crate::layout_components::Row; use crate::menu::{GroupItem, Menu, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; @@ -505,27 +504,35 @@ impl Container for let started = drop::started(&cx.env); let mut extra = self.extra.take(); let env = crate::runtime::env::Env::of(ui); - ui.set_min_height(env.tokens.size.panel_header); + let rtl = env.direction.is_rtl(); + let (line, gap) = (env.tokens.size.panel_header, env.tokens.space.gap.item); + ui.set_min_height(line); let surface_pressed = cx.surface_pressed(); + // A raw egui layout: the host's items and the tab row sit side by side, and the header column's flow facts are + // not theirs. The tab row takes the rest of the line, so the strip's empty room is its own, and nothing but the + // memoized tab row runs in it, so a settled header replays. + let layout = if rtl { egui::Layout::right_to_left(egui::Align::Min) } else { egui::Layout::left_to_right(egui::Align::Min) }; let mut sent = Vec::new(); - let mut strip = None; - let _ = Row::new().fill_width().gap(Gap::Item).show(ui, |ui, _| { - if let Some(hook) = extra.as_mut() { - hook.run(ui, cx); - } - let row = TabRow { - anchor: self.anchor.clone(), - panels: self.panels.clone(), - active: self.active, - closable: self.closable, - wheel_selects: self.wheel_selects_tabs, - dock: self.dock, - sent: Outbox::new(&mut sent), - }; - // The env around the tab row holds only values its key follows (the shell, the dock's arrangement, a - // floating window's layer), no handle or context rebuilt each pass, so it replays at rest. - strip = MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui); - }); + let strip = ui + .with_layout(layout, |ui| { + ui.spacing_mut().item_spacing.x = gap; // design: allow[style-mutation](the header lays its title cells with an egui layout and sets that layout's gap) + if let Some(hook) = extra.as_mut() { + hook.run(ui, cx); + } + let row = TabRow { + anchor: self.anchor.clone(), + panels: self.panels.clone(), + active: self.active, + closable: self.closable, + wheel_selects: self.wheel_selects_tabs, + dock: self.dock, + sent: Outbox::new(&mut sent), + }; + // The env around the tab row holds only values its key follows (the shell, the dock's arrangement, a + // floating window's layer), no handle or context rebuilt each pass, so it replays at rest. + MemoView::new(("tabs", cx.id), row, tab_row::

).show(ui) + }) + .inner; self.extra = extra; // A press on the group's empty body focuses its panel, as in Photoshop. if surface_pressed && let Some(strip) = strip { diff --git a/design/exceptions/craft-ui-panels/docking.toml b/design/exceptions/craft-ui-panels/docking.toml index c7dc26bf5..1bfc5dd49 100644 --- a/design/exceptions/craft-ui-panels/docking.toml +++ b/design/exceptions/craft-ui-panels/docking.toml @@ -1,5 +1,13 @@ config_version = 1 +[[exception]] +name = "dock-header-gap" +kind = "marker" +rule = "style-mutation" +path = "crates/ui-panels/src/docking/group.rs" +reason = "The header lays its title cells with an egui layout and sets that layout gap." +count = 1 + [[exception]] name = "iconic-story-stage" kind = "marker" From bf37300a17fc89165cf5f8c5bd0dd07b30b77e8f Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 02:19:01 +0000 Subject: [PATCH 11/15] ToggleCell: the empty_off test lives in the layers panel_eye trial (design-lint: no cfg(test) module in an egui-linked crate) --- crates/ui-widgets/src/list/toggle.rs | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/crates/ui-widgets/src/list/toggle.rs b/crates/ui-widgets/src/list/toggle.rs index 82f8f8149..afe5733a2 100644 --- a/crates/ui-widgets/src/list/toggle.rs +++ b/crates/ui-widgets/src/list/toggle.rs @@ -185,18 +185,3 @@ impl ToggleCell { !self.empty_off && (self.always_visible || hovered) } } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn an_empty_off_cell_never_draws_its_off_icon() { - let eye = ToggleCell::eye(ColumnKey::new("eye"), false); - assert!(!eye.shows_off(false) && eye.shows_off(true), "a plain off cell shows its off icon only under the pointer"); - assert!(eye.clone().always_visible().shows_off(false), "always_visible shows it in every row"); - let empty = eye.empty_off(); - assert!(!empty.shows_off(true), "an empty_off cell stays empty under the pointer"); - assert!(!empty.always_visible().shows_off(true), "empty_off wins over always_visible"); - } -} From ebba2b5d3009c75922a2fa984736eeff7232425a Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Sat, 21 Nov 2026 23:11:43 -0300 Subject: [PATCH 12/15] menu/ribbon: render framed Gallery with sunken well surface and restore stepper button contrast Framed galleries now render with the sunken well surface (`colors.surface.sunken`) and provide a dedicated stepper track (`colors.surface.panel`) with divider definition for the stepper buttons column to preserve contrast and hierarchy in both light and dark modes. --- crates/menu/src/ribbon/gallery.rs | 25 +++++++++++- crates/menu/tests/it/ribbon_gallery.rs | 53 ++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 2 deletions(-) diff --git a/crates/menu/src/ribbon/gallery.rs b/crates/menu/src/ribbon/gallery.rs index f26bb2528..d6b93a768 100644 --- a/crates/menu/src/ribbon/gallery.rs +++ b/crates/menu/src/ribbon/gallery.rs @@ -85,6 +85,8 @@ pub struct Gallery<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { caption: CaptionPlace, /// Each shown tile's rect. laid: Vec, + /// The column of stepper buttons, if shown. + column: Rect, picked: Option, menu: Option>, } @@ -118,6 +120,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { thumb_size: ThumbSize::Medium, caption: CaptionPlace::None, laid: Vec::new(), + column: Rect::NOTHING, picked: None, menu: None, } @@ -131,7 +134,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Gallery<'a, K> { self } - /// One rounded frame on the raised surface around the tiles and the buttons, as the old Word-style ribbon drew + /// One rounded frame on the sunken well surface around the tiles and the buttons, as the old Word-style ribbon drew /// its Styles gallery. pub fn framed(mut self) -> Self { self.framed = true; @@ -509,6 +512,9 @@ pub struct GalleryStyle { frame: (StyleColor, StyleColor, f32), /// The room inside a frame. inset: f32, + /// The stepper buttons column's track fill and divider. + track: StyleColor, + divider: StyleColor, } /// The sizes the gallery's faces measure. @@ -527,8 +533,10 @@ impl Component for Gallery<'_, K> let colors = &cx.tokens.color; GalleryStyle { metrics: Metrics::new().gap(cx.tokens.space.gap.inline), - frame: (cx.color(colors.surface.raised), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control), + frame: (cx.color(colors.surface.sunken), cx.color(colors.line.control_edge), cx.tokens.shape.radius.control), inset: cx.tokens.space.gap.inline, + track: cx.color(colors.surface.panel), + divider: cx.color(colors.line.divider), } } @@ -566,6 +574,7 @@ impl Component for Gallery<'_, K> let buttons = self.buttons(level); let rect = rect.shrink2(Vec2::new(self.inset(cx.style), 0.0)); let (column, rest) = Flow::new(rect, cx.flow.is_rtl()).take_end(if buttons { sizes.button.x } else { 0.0 }); + self.column = if buttons { column } else { Rect::NOTHING }; self.laid.clear(); for at in 0..shown { let cell = rest.span(at as f32 * (sizes.tile.x + sizes.gap), sizes.tile.x); @@ -702,6 +711,18 @@ impl Component for Gallery<'_, K> if !self.buttons(level) { return; } + if self.framed && self.column.is_positive() { + let draw = ui.draw(); + let radius = cx.style.frame.2.round().clamp(0.0, 255.0) as u8; + let track_shape = PaintShape::Rect(self.column, CornerRadius::same(radius)); + draw.fill(&track_shape, cx.style.track); + draw.stroke(&track_shape, craft_ui::primitives::StrokeWidth::Thin, cx.style.divider); + let height = self.column.height() / 3.0; + let y1 = self.column.min.y + height; + let y2 = self.column.min.y + 2.0 * height; + draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y1), egui::pos2(self.column.right(), y1)); + draw.rule(craft_ui::style::RuleKind::Divider, egui::pos2(self.column.left(), y2), egui::pos2(self.column.right(), y2)); + } ui.face(UP, IconButton::new(IconId::new("chevron_up")).label(words.up.clone()).enabled(start > 0)); ui.face(DOWN, IconButton::new(IconId::new("chevron_down")).label(words.down.clone()).enabled(start < last)); ui.face(MORE, IconButton::new(IconId::new("more")).label(words.more.clone())); diff --git a/crates/menu/tests/it/ribbon_gallery.rs b/crates/menu/tests/it/ribbon_gallery.rs index 41061fe14..8314365eb 100644 --- a/crates/menu/tests/it/ribbon_gallery.rs +++ b/crates/menu/tests/it/ribbon_gallery.rs @@ -138,3 +138,56 @@ fn a_wide_captioned_gallery_names_its_tiles_under_wide_pictures() { assert!(name.min.y >= wide.min.y + square.width() / 2.0, "the name {name:?} is under the picture in {wide:?}"); assert!(!plain.iter().any(|(text, _)| text == "Tile 0"), "a plain tile paints no name: {plain:?}"); } + +/// A framed gallery paints a sunken well fill over its bounds, and a panel fill over its stepper button track. +#[trial] +fn a_framed_gallery_paints_sunken_well_and_stepper_track() { + use craft_ui::runtime::env::Env; + use egui::Color32; + + fn fills(shapes: &[egui::Shape], out: &mut Vec<(egui::Rect, egui::Color32)>) { + for shape in shapes { + match shape { + egui::Shape::Vec(inner) => fills(inner, out), + egui::Shape::Rect(rect) => out.push((rect.rect, rect.fill)), + _ => {} + } + } + } + + let colors_and_rect = Rc::new(Cell::new((Rect::NOTHING, Color32::TRANSPARENT, Color32::TRANSPARENT))); + let held = colors_and_rect.clone(); + let mut fixture = Fixture::new(move |ui| { + let [sr, sg, sb, sa] = Env::of(ui).tokens.tokens().color.surface.sunken.0; + let [pr, pg, pb, pa] = Env::of(ui).tokens.tokens().color.surface.panel.0; + let sunken = Color32::from_rgba_unmultiplied(sr, sg, sb, sa); + let panel = Color32::from_rgba_unmultiplied(pr, pg, pb, pa); + + let paint = |_: &ContentPainterCx, _: Rect| {}; + let items: Vec> = + (0..10).map(|at| GalleryItem { key: at, label: Label::from(format!("Tile {at}")), face: GalleryFace::Paint(&paint) }).collect(); + let out = Gallery::new("Styles", &items, None).tiles(6, 3).framed().show(ui); + held.set((out.response.rect, sunken, panel)); + }); + fixture.settle(); + + let (gallery_rect, sunken, panel) = colors_and_rect.get(); + assert!(gallery_rect.is_positive(), "the gallery paints a positive rect"); + + let mut seen = Vec::new(); + fills(&fixture.frame_shapes(), &mut seen); + + assert!( + seen.iter() + .any(|(rect, fill)| *fill == sunken && rect.contains_rect(gallery_rect.shrink(1.0)) && gallery_rect.expand(1.0).contains_rect(*rect)), + "a sunken fill covers the gallery {gallery_rect:?}: {seen:?}" + ); + + let up = fixture.by_label("Previous row").expect("the up button shows"); + let down = fixture.by_label("Next row").expect("the down button shows"); + let more = fixture.by_label("More").expect("the more button shows"); + let column = up.rect.union(down.rect).union(more.rect); + let stepper_track = + seen.iter().find(|(rect, fill)| *fill == panel && rect.contains_rect(column.shrink(1.0)) && gallery_rect.contains_rect(*rect)); + assert!(stepper_track.is_some(), "a panel fill covers the stepper track column {column:?}: {seen:?}"); +} From 7c110914879a262655d57e3737749607c47d3ba4 Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Sun, 22 Nov 2026 00:20:32 -0300 Subject: [PATCH 13/15] ui-canvas, pages: allow Canvas and PageView editors to report inactive edits (#2966) --- crates/pages/src/ui/view.rs | 29 ++++++++- crates/pages/tests/it/views.rs | 47 +++++++++++++- crates/ui-canvas/src/canvas/mod.rs | 11 +++- crates/ui-canvas/tests/it/canvas/editor.rs | 73 +++++++++++++++++++++- 4 files changed, 153 insertions(+), 7 deletions(-) diff --git a/crates/pages/src/ui/view.rs b/crates/pages/src/ui/view.rs index 3d4244cb5..59bb08827 100644 --- a/crates/pages/src/ui/view.rs +++ b/crates/pages/src/ui/view.rs @@ -38,6 +38,7 @@ use craft_ui::contract::{Bind, BodyCx, Held, Props as _, Show as _, ShowContaine use craft_ui::primitives::EditorPurpose; use craft_ui::primitives::textures::ThumbSource; use craft_ui::runtime::env::{Env, Label}; +use craft_ui::runtime::focus::EditSet; use craft_ui::runtime::memory::Remember as _; use craft_ui::style::DataColor; use egui::{Rect, Ui, Vec2, pos2}; @@ -338,6 +339,7 @@ pub struct PageView<'a> { describer: Option<&'a dyn AccessDescriber>, paper: DataColor, editor: Option, + inactive_edits: EditSet, snap: Option, tool_regions: Vec, rulers: bool, @@ -362,6 +364,7 @@ impl<'a> PageView<'a> { describer: None, paper, editor: None, + inactive_edits: EditSet::NONE, snap: None, tool_regions: Vec::new(), rulers: false, @@ -404,6 +407,13 @@ impl<'a> PageView<'a> { self } + /// Edit commands the view's editor part cannot act on right now, forwarded to [`Canvas::inactive_edits`]. + #[must_use] + pub fn inactive_edits(mut self, inactive: EditSet) -> Self { + self.inactive_edits = inactive; + self + } + /// The snapping of the coordinates the pointer sets on the view, with its targets in page points. The view places /// them on the pages that show this pass, drops those of pages outside the shown row and passes the result to the /// inner canvas. @@ -455,7 +465,22 @@ impl<'a> PageView<'a> { } fn run(self, ui: &mut Ui, rect: Rect, take_room: bool, mut body: impl FnMut(&mut Ui, &PageBody<'_>)) -> PageViewOutput { - let PageView { label, source, state, options, navigation, bodies, describer, paper, editor, snap, tool_regions, rulers, reach } = self; + let PageView { + label, + source, + state, + options, + navigation, + bodies, + describer, + paper, + editor, + inactive_edits, + snap, + tool_regions, + rulers, + reach, + } = self; let spacing = PageMetrics::new().show_at(ui, Rect::from_min_size(rect.min, Vec2::ZERO)).spacing; let count = source.page_count(); @@ -485,7 +510,7 @@ impl<'a> PageView<'a> { let regions: Vec = tool_regions.iter().filter_map(|region| placed_region(region, &geo, &frame)).collect(); let mut canvas = Canvas::new(label.clone()).view(given).navigation(navigation).keys_to_body(true).tool_regions(regions); if let Some(purpose) = editor { - canvas = canvas.editor(purpose); + canvas = canvas.editor(purpose).inactive_edits(inactive_edits); } if let Some(snap) = &snap { canvas = canvas.snap(placed_snap(snap, &geo, &frame)); diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index 425a56ccf..d7ab14015 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -3,7 +3,7 @@ use craft_behavior::geometry::{CropBox, SnapKind, SnapOptions, SnapTarget}; use craft_behavior::kurbo; -use craft_behavior::{Axis, CancelReason, CanvasView}; +use craft_behavior::{Axis, CancelReason, CanvasView, EditCommand}; use craft_pages::layout::{Fit, LayoutOptions, PageDisplay}; use craft_pages::ui::fixtures::{DemoPages, PAPER}; use craft_pages::ui::{ @@ -14,7 +14,9 @@ use craft_ui::contract::{Bind, Role, Show as _}; use craft_ui::primitives::textures::TextureStoreOptions; use craft_ui::primitives::{Draw, EditorPurpose}; +use craft_ui::runtime::commands::{CommandState, EditCommands, resolve}; use craft_ui::runtime::env::Env; +use craft_ui::runtime::focus::EditSet; use craft_ui::testing::{Fixture, pointer, trial}; use egui::{Key, Modifiers, pos2, vec2}; use std::cell::{Cell, RefCell}; @@ -955,3 +957,46 @@ fn go_to_a_point_inside_a_page_puts_it_at_the_top() { assert_eq!(first, Some(5), "the first page in view is the one gone to"); assert!((offset - at).abs() < 0.01, "the view's top {offset} is the point gone to, {at}"); } + +/// `PageView::inactive_edits` forwards to its inner canvas editor: Cut resolves disabled while inactive and enabled +/// once active, and Undo/Redo fall through to app command states while inactive. +#[trial] +fn page_view_forwards_inactive_edits_to_its_editor_canvas() { + let state = Rc::new(RefCell::new(PageViewState::default())); + let inactive = Rc::new(Cell::new(EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Undo).with(EditCommand::Redo))); + let (kept_state, kept_inactive) = (Rc::clone(&state), Rc::clone(&inactive)); + let pages = DemoPages::new(2); + let mut fixture = Fixture::new(move |ui| { + let mut now = kept_state.borrow().clone(); + PageView::new("Pages", &pages, &mut now, PAPER) + .options(LayoutOptions::ACROBAT) + .editor(EditorPurpose::Text) + .inactive_edits(kept_inactive.get()) + .show(ui, |_, _| ()); + *kept_state.borrow_mut() = now; + }); + fixture.command_state(EditCommands::Cut, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(false)); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + + let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect; + fixture.click_at(canvas_rect.center()); + fixture.settle(); + assert!(fixture.focused().is_some(), "clicking the page view focuses its editor canvas"); + + assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "inactive Cut resolves disabled on focused PageView"); + assert!(!resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo falls through to disabled app state"); + assert!(!resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo falls through to disabled app state"); + + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(true)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo follows enabled app state"); + assert!(resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo follows enabled app state"); + + inactive.set(EditSet::NONE.with(EditCommand::Undo).with(EditCommand::Redo)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "active Cut resolves enabled on focused PageView"); +} diff --git a/crates/ui-canvas/src/canvas/mod.rs b/crates/ui-canvas/src/canvas/mod.rs index 1e4895efe..dea38e038 100644 --- a/crates/ui-canvas/src/canvas/mod.rs +++ b/crates/ui-canvas/src/canvas/mod.rs @@ -107,7 +107,7 @@ use crate::contract::{ use crate::primitives::{EditorPurpose, ImeStamp}; use crate::runtime::commands::{CommandSet as _, CommandState, Commands as _}; use crate::runtime::env::Label; -use crate::runtime::focus::KeyUse; +use crate::runtime::focus::{EditSet, KeyUse}; use crate::runtime::lock_keys; use crate::runtime::measure; use crate::runtime::motion::{Animate as _, spec}; @@ -217,6 +217,12 @@ pub struct Canvas<'a> { /// does not apply. The body reports its editor state through [`ToolPass::editor`]. #[prop] editor: Option, + /// Edit commands the canvas's editor part cannot act on right now (for instance Cut and Copy with nothing + /// selected, or Undo and Redo with no editor-local history). Applied to [`KeyUse::inactive`] while + /// [`editor`](Self::editor) is set: Cut, Copy, Paste and Select All stay the editor's and resolve disabled; Undo + /// and Redo fall through to the app command's state. Ignored without [`editor`](Self::editor). + #[prop] + inactive_edits: EditSet, /// The editor part's inputs of this pass, taken once in `update`: `tool_pass` is built from a shared `Cx`. editor_input: Arc<[EditorInput]>, /// The rulers' units and zero point, published to the body in its [`CanvasSpace`]. @@ -308,6 +314,7 @@ impl<'a> Canvas<'a> { ruler_output: None, keys_to_body: false, editor: None, + inactive_edits: EditSet::NONE, editor_input: Arc::from([]), pasteboard: PasteboardColor::Default, precise_cursors: false, @@ -825,7 +832,7 @@ impl Component for Canvas<'_> { /// nudges. It still marks its window as showing a document. fn keys(&self) -> KeyUse { match self.editor { - Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves(), + Some(_) => KeyUse::of(Input::Editor).with_chrome_key(true).with_moves().with_inactive(self.inactive_edits), None => Self::KEYS, } } diff --git a/crates/ui-canvas/tests/it/canvas/editor.rs b/crates/ui-canvas/tests/it/canvas/editor.rs index 48153ff5f..688d7438a 100644 --- a/crates/ui-canvas/tests/it/canvas/editor.rs +++ b/crates/ui-canvas/tests/it/canvas/editor.rs @@ -2,12 +2,15 @@ //! body through its `ToolPass`. use craft_behavior::kurbo::{Point, Size}; -use craft_behavior::{CanvasView, EditorInput, Proposal, TextPos}; +use craft_behavior::{CanvasView, EditCommand, EditorInput, Proposal, TextPos}; +use craft_ui::buttons::Button; use craft_ui::canvas::{Canvas, tool_pass}; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::primitives::{EditorPurpose, EditorState}; use craft_ui::runtime::access::Role; -use craft_ui::runtime::focus; +use craft_ui::runtime::commands::{CommandRef, CommandState, EditCommands, resolve}; +use craft_ui::runtime::focus::{self, EditSet}; +use craft_ui::runtime::frame; use craft_ui::testing::focus::egui_focused; use craft_ui::testing::{Fixture, trial}; use craft_ui::text::TextField; @@ -144,3 +147,69 @@ fn focus_has_answers_for_a_canvas_whose_editor_part_holds_focus() { assert!(focus::has(fixture.ctx(), field_id), "a click on the field moves focus there"); assert!(!focus::has(fixture.ctx(), canvas_id), "and the canvas has it no more"); } + +/// Guards `Canvas::inactive_edits` with an editor part: inactive Cut stays owned by the editor and resolves disabled +/// (even when the app's Cut is enabled), inactive Undo and Redo fall through to app command states and fire the app +/// command while keeping canvas focus, and a separate text field resolves Cut from its own selection independently. +#[trial] +fn inactive_edits_disable_cut_and_let_undo_and_redo_fall_through_to_app_state() { + let inactive = Rc::new(Cell::new(EditSet::NONE.with(EditCommand::Cut).with(EditCommand::Undo).with(EditCommand::Redo))); + let text = Rc::new(RefCell::new("hello".to_owned())); + let ids: Rc>> = Rc::default(); + let (held_inactive, held_text, shown_ids) = (Rc::clone(&inactive), Rc::clone(&text), Rc::clone(&ids)); + let mut fixture = Fixture::new(move |ui| { + let cut = Button::command(EditCommands::Cut).show(ui).id; + let undo = Button::command(EditCommands::Undo).show(ui).id; + let _ = TextField::new("Notes", Bind::bound(&mut *held_text.borrow_mut())).show(ui); + let room = ui.available_rect_before_wrap(); + let view = CanvasView::new(room, Point::new(PAGE.width / 2.0, PAGE.height / 2.0), 1.0); + let output = canvas(view).inactive_edits(held_inactive.get()).show_at(ui, room, |_, _| {}); + shown_ids.set(Some((output.output.response.id, cut, undo))); + }); + fixture.command_state(EditCommands::Cut, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(false)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(false)); + fixture.room(ROOM); + fixture.settle(); + + let (canvas_id, cut_id, undo_id) = ids.get().expect("the canvas and buttons showed"); + let canvas_rect = fixture.by_role(Role::CANVAS).into_iter().next().expect("a canvas").rect; + fixture.click_at(canvas_rect.center()); + fixture.settle(); + assert!(focus::has(fixture.ctx(), canvas_id), "the canvas has focus"); + + assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "inactive Cut resolves disabled despite app Cut state"); + assert!(fixture.tree().is_disabled(cut_id), "the Cut button reflects the inactive editor command"); + assert!(!resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo falls through to disabled app state"); + assert!(!resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo falls through to disabled app state"); + assert!(fixture.tree().is_disabled(undo_id), "the Undo button is disabled while app Undo is disabled"); + + fixture.command_state(EditCommands::Undo, CommandState::new().enabled(true)); + fixture.command_state(EditCommands::Redo, CommandState::new().enabled(true)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Undo).enabled, "inactive Undo follows enabled app state"); + assert!(resolve(fixture.ctx(), EditCommands::Redo).enabled, "inactive Redo follows enabled app state"); + assert!(!fixture.tree().is_disabled(undo_id), "the Undo button enables with app Undo"); + + frame::take_output(fixture.ctx()); + let undo_node = fixture.by_label("Undo").expect("the Undo button shows"); + fixture.click(&undo_node); + fixture.settle(); + let undo_ref = CommandRef::from(EditCommands::Undo).id; + let fired: Vec = frame::take_output(fixture.ctx()).fired.into_iter().map(|entry| entry.command.id).collect(); + assert!(fired.contains(&undo_ref), "clicking Undo while inactive on the editor fires the app command: {fired:?}"); + assert!(focus::has(fixture.ctx(), canvas_id), "the Undo button press keeps focus on the canvas"); + + inactive.set(EditSet::NONE.with(EditCommand::Undo).with(EditCommand::Redo)); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "removing Cut from inactive_edits enables Cut"); + assert!(!fixture.tree().is_disabled(cut_id), "the Cut button enables once Cut is active on the editor"); + + let field_rect = fixture.by_role(Role::TEXT_INPUT).into_iter().next().expect("the field").rect; + fixture.click_at(field_rect.center()); + fixture.settle(); + assert!(!resolve(fixture.ctx(), EditCommands::Cut).enabled, "a focused TextField with no selection disables Cut independently"); + fixture.key(Key::A, Modifiers::COMMAND); + fixture.settle(); + assert!(resolve(fixture.ctx(), EditCommands::Cut).enabled, "selecting text in the TextField enables Cut independently"); +} From 0fdbaff4435b7dbedd6cc777d696cc81a0b7952c Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Sun, 22 Nov 2026 00:20:36 -0300 Subject: [PATCH 14/15] font-manager: paint FontPicker missing-font warning icon in status.warn.fg (#2972) --- crates/font-manager/src/picker.rs | 40 ++++++++++---- crates/font-manager/tests/it/picker.rs | 75 ++++++++++++++++++++++++++ 2 files changed, 105 insertions(+), 10 deletions(-) diff --git a/crates/font-manager/src/picker.rs b/crates/font-manager/src/picker.rs index 1521d943b..1fcd06282 100644 --- a/crates/font-manager/src/picker.rs +++ b/crates/font-manager/src/picker.rs @@ -14,16 +14,18 @@ use craft_behavior::{Codec, EditEvent, IconId, Mixed, NotAValue, PartKey, Sense, use craft_behavior::{HitLevel, HitPriority, NavMove, Preview}; use craft_font_catalog::Catalog; use craft_host::Section; +use craft_theme::variant::Tone; use craft_ui::buttons::{ControlPlace, IconButton}; use craft_ui::contract::{ Bind, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, - Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + Pointer as _, Props as _, Remember as _, Role, Styled as _, WordSetCx as _, }; use craft_ui::list::{ThumbSize, TrailingPart}; use craft_ui::primitives::{IconSpec, TextKey, TextOptions, TextRun}; use craft_ui::runtime::env::{EnvView, Label}; use craft_ui::runtime::memory::StageAccess; -use craft_ui::text::{Adornment, place, reserve}; +use craft_ui::style::{ComponentStyle, Metrics, Stateful, States, StyleColor, StyleCx, SurfaceLook}; +use craft_ui::text::{Adornment, FieldStyle, place, reserve}; use egui::{Rect, Response, Vec2}; use serde::{Deserialize, Serialize}; @@ -589,18 +591,35 @@ impl<'a> FontPicker<'a> { } } +/// The style of [`FontPicker`]: the field look and the colour of the missing-font warning icon. +#[derive(Clone, Debug, PartialEq, ComponentStyle)] +#[non_exhaustive] +pub struct FontPickerStyle { + #[style(surface)] + surface: SurfaceLook, + #[style(metrics)] + metrics: Metrics, + /// The field look the adornments are placed by; `surface` and `metrics` are its own. + field: FieldStyle, + /// The ink of the missing-font warning icon (`status.warn.fg`), dimmed to `text.disabled` while disabled. + warning: Stateful, +} + impl Component for FontPicker<'_> { const ROLE: Role = Role::COMBO_BOX; const INPUT: Input = Input::Text; const KEYS: craft_ui::runtime::focus::KeyUse = craft_ui::runtime::focus::KeyUse::of(Input::Text).with_moves(); - type Style = craft_ui::text::FieldStyle; + type Style = FontPickerStyle; type Output = FontPickerOutput; /// A field; in a ribbon (`ControlPlace::Ribbon`) held at the small field length (`size.length.field.sm`), as a /// ribbon's font box is: wide enough for a family name and its menu arrow, the same width whichever it shows. - fn style(cx: &craft_ui::style::StyleCx<'_>, _: FontPickerStyleKey) -> craft_ui::text::FieldStyle { - let field = craft_ui::text::FieldStyle::at(cx); - if cx.env::() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field } + fn style(cx: &StyleCx<'_>, _: FontPickerStyleKey) -> FontPickerStyle { + let field = FieldStyle::at(cx); + let field = if cx.env::() == ControlPlace::Ribbon { field.held_at(cx.tokens.size.length.field.sm) } else { field }; + let warn = cx.tone(Tone::Warn); + let off = cx.color(cx.tokens.color.text.disabled); + FontPickerStyle { surface: cx.field(), metrics: field.metrics(), field, warning: Stateful::new(warn).off(States::new(warn, warn, warn, off)) } } /// The wheel steps the family through the list. @@ -620,7 +639,7 @@ impl Component for FontPicker<'_> { let widest = if ribbon { Vec2::new(cx.tokens.size.length.short, widest.y) } else { widest }; let name = cx.words::().list.clone(); let note = self.missing_note(current, &cx.words::()); - Vec2::new(widest.x + reserve(cx.style, &[], &Self::trailing(name, note.is_some())), widest.y) + Vec2::new(widest.x + reserve(&cx.style.field, &[], &Self::trailing(name, note.is_some())), widest.y) } fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) { @@ -628,7 +647,7 @@ impl Component for FontPicker<'_> { let family = cx.value().cloned().unwrap_or_default(); let note = self.missing_note(&family, &cx.words::()); let trailing = Self::trailing(name, note.is_some()); - let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.flow.is_rtl()); + let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.flow.is_rtl()); if let (Some(note), Some(at)) = (note, placed.trailing.first()) { cx.part(WARNING, *at).tooltip(note); } @@ -708,9 +727,10 @@ impl Component for FontPicker<'_> { let family = cx.value().cloned().unwrap_or_default(); let missing = self.missing_note(&family, &cx.words::()).is_some(); let trailing = Self::trailing(name.clone(), missing); - let placed = place(cx.content_rect, cx.style, &[], &trailing, cx.env.direction().is_rtl()); + let placed = place(cx.content_rect, &cx.style.field, &[], &trailing, cx.env.direction().is_rtl()); if let (true, Some(at)) = (missing, placed.trailing.first()) { - ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON))); + let color = cx.resolve(&cx.style.warning); + ui.draw().icon(*at, &IconSpec::svg(IconId::new(WARNING_ICON)).color(color)); } ui.face(CHEVRON, IconButton::new(IconId::new(CHEVRON_ICON)).label(name)); } diff --git a/crates/font-manager/tests/it/picker.rs b/crates/font-manager/tests/it/picker.rs index 8ef2bc258..195bf3a1b 100644 --- a/crates/font-manager/tests/it/picker.rs +++ b/crates/font-manager/tests/it/picker.rs @@ -400,3 +400,78 @@ fn a_picker_handed_another_catalog_at_the_same_generation_builds_its_family_data fx.frame(vec![]); assert_eq!(family_builds(&fx), 1, "the second catalog builds the data once"); } + +/// Every non-transparent vertex colour of textured meshes whose centre falls inside `rect`. +fn mesh_tints(shapes: &[egui::Shape], rect: egui::Rect, out: &mut Vec) { + for shape in shapes { + match shape { + egui::Shape::Vec(inner) => mesh_tints(inner, rect, out), + egui::Shape::Mesh(mesh) if rect.contains(mesh.calc_bounds().center()) => { + out.extend(mesh.vertices.iter().map(|vertex| vertex.color).filter(|color| color.a() > 0)); + } + _ => {} + } + } +} + +/// The painted tint colours of the missing-font warning icon in `mode`/`contrast`, enabled or disabled, together with +/// the theme's `status.warn.fg`, `text.normal` and `text.disabled` colours. +fn missing_warning_colors( + mode: craft_theme::Mode, + contrast: craft_theme::Contrast, + enabled: bool, +) -> (Vec, egui::Color32, egui::Color32, egui::Color32) { + use craft_ui::contract::Props as _; + use craft_ui::runtime::env::Env; + use egui::Color32; + use std::cell::Cell; + + let catalog = catalog_of(&[INTER_REGULAR]); + let seen = Rc::new(Cell::new((None, Color32::TRANSPARENT, Color32::TRANSPARENT, Color32::TRANSPARENT))); + let held = Rc::clone(&seen); + let mut family = "Gotham".to_owned(); + let mut fx = Fixture::new(move |ui| { + let color = |[r, g, b, a]: [u8; 4]| Color32::from_rgba_unmultiplied(r, g, b, a); + let env = Env::of(ui); + let tokens = &env.tokens.tokens().color; + let out = FontPicker::new("Font family", Bind::bound(&mut family), &catalog) + .kind(FontPickerKind::Plain) + .shown_as("Inter") + .enabled(enabled) + .show(ui); + held.set((Some(out.edit.response.id), color(tokens.status.warn.fg.0), color(tokens.text.normal.0), color(tokens.text.disabled.0))); + }); + fx.theme(mode, contrast); + fx.in_room(Room::Window); + fx.settle(); + let (id, warn_fg, text_normal, text_disabled) = seen.get(); + let picker = id.expect("the picker"); + let mark = fx.part_rect(picker, PartKey::new("missing")).expect("the field carries a mark while the family is not installed"); + let mut tints = Vec::new(); + mesh_tints(&fx.frame_shapes(), mark, &mut tints); + tints.dedup(); + (tints, warn_fg, text_normal, text_disabled) +} + +#[trial] +fn the_missing_font_warning_icon_paints_in_status_warn_fg_and_dims_when_disabled() { + use craft_theme::{Contrast, Mode}; + + for (mode, contrast) in [(Mode::Light, Contrast::Standard), (Mode::Dark, Contrast::Standard), (Mode::Dark, Contrast::High)] { + let (tints, warn_fg, text_normal, _) = missing_warning_colors(mode, contrast, true); + assert_ne!(warn_fg, text_normal, "{mode:?} {contrast:?}: warning ink differs from neutral text ink"); + assert!(!tints.is_empty(), "{mode:?} {contrast:?}: the missing-font warning icon paints"); + assert!( + tints.iter().all(|tint| *tint == warn_fg), + "{mode:?} {contrast:?}: the warning icon paints in status.warn.fg {warn_fg:?}, not {tints:?}" + ); + } + + let (tints, warn_fg, _, text_disabled) = missing_warning_colors(Mode::Dark, Contrast::Standard, false); + assert_ne!(text_disabled, warn_fg, "disabled ink differs from warning ink"); + assert!(!tints.is_empty(), "a disabled picker still paints its warning icon"); + assert!( + tints.iter().all(|tint| *tint == text_disabled), + "a disabled picker paints its warning icon in text.disabled {text_disabled:?}, not {tints:?}" + ); +} From e71898caae31596e5b174634faccfab61b57401c Mon Sep 17 00:00:00 2001 From: batistalucasv Date: Sun, 22 Nov 2026 00:49:50 -0300 Subject: [PATCH 15/15] pages: derive PageView spacing from ComponentSet (#2952) (#2967) Co-authored-by: Dylan M. Taylor --- crates/pages/src/layout.rs | 13 ++- crates/pages/src/ui/view/pictures.rs | 35 +++++--- crates/pages/tests/it/views.rs | 117 ++++++++++++++++++++++++++- 3 files changed, 148 insertions(+), 17 deletions(-) diff --git a/crates/pages/src/layout.rs b/crates/pages/src/layout.rs index ed571bfa7..1189ba99f 100644 --- a/crates/pages/src/layout.rs +++ b/crates/pages/src/layout.rs @@ -7,13 +7,12 @@ //! out), with a markup column beside each page and Hide White Space. [`PageDisplay`] holds both, //! and [`LayoutOptions`] carries each app's switches ([`LayoutOptions::ACROBAT`], //! [`LayoutOptions::WORD`]). The screen spacing ([`PageSpacing`]: gap, margin, side gutter, Hide -//! White Space's pad and seam) is not a constant here: the page view reads it from the `pages.*` -//! size tokens (`PageView::style`), which an app overrides in its `sizes.json` (WordCraft's wider -//! gap and no side gutter). +//! White Space's pad and seam) is not a constant here: the page view derives it from the scope's +//! semantic tokens and `ComponentSet` (`Creative` keeps the tool-rail side gutter; `Productivity` +//! uses a wider gap and matching margin/side without the rail gutter). //! //! ```ignore //! let sizes: Vec = doc.pages.iter().map(|p| p.size()).collect(); -//! let spacing = PageView::style(&tokens).spacing; //! let scale = fit_scale(&sizes, viewport, view.fit, &options, &spacing, view.current).unwrap_or(view.zoom * SCREEN_POINTS_PER_POINT); //! let laid = place_pages(&sizes, scale, viewport, &options, &spacing); //! let shown = if options.continuous { 0..sizes.len() } else { shown_row(sizes.len(), view.current, &options) }; @@ -118,9 +117,9 @@ impl LayoutOptions { } /// The spacing of a page layout: screen points, except [`white_space_pad`](Self::white_space_pad), -/// which is in points at 100 % zoom and is multiplied by the zoom. The page view takes it from the `pages.*` size tokens -/// (`craft_pages::ui::PageView::style`); this crate's core has no tokens, so the layout functions -/// take it as a value. +/// which is in points at 100 % zoom and is multiplied by the zoom. The page view derives it from the +/// scope's semantic tokens and `ComponentSet`; this crate's core has no tokens, so the layout +/// functions take it as a value. #[derive(Clone, Copy, Debug, PartialEq)] pub struct PageSpacing { /// Between pages, and between rows (the page view's gap); unused with diff --git a/crates/pages/src/ui/view/pictures.rs b/crates/pages/src/ui/view/pictures.rs index 3a6d0c0f8..ad9cd40c5 100644 --- a/crates/pages/src/ui/view/pictures.rs +++ b/crates/pages/src/ui/view/pictures.rs @@ -5,6 +5,7 @@ use super::{PageSource, PlacedPage}; use crate::layout::PageSpacing; use crate::ui::access::{AccessDescriber, describe}; use craft_behavior::{Input, Metrics, PixelSize, Sense}; +use craft_theme::ComponentSet; use craft_ui::canvas::DetailPlan; use craft_ui::canvas::PixelRect; use craft_ui::contract::{Access, Common, Component, Cx, DisabledLook, MeasureCx, NoValue, Outcome, PaintUi, Role}; @@ -15,8 +16,12 @@ use craft_ui::runtime::memory::Remember as _; use craft_ui::style::{ComponentStyle, DataColor, StyleCx}; use egui::{Rect, Response, Vec2, pos2}; +/// Productivity inter-page gap as a multiple of `space.gap.section`: 18 pt in Compact (Word's gap) and 24 pt in +/// Comfortable. +const PRODUCTIVITY_GAP_RATIO: f32 = 1.5; + /// The style of the page view's spacing: the gap between pages, the margin, the side column, Hide White Space's pad -/// and its seam, all from the tokens. +/// and its seam, from the tokens and the scope's [`ComponentSet`]. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct PageMetricsStyle { @@ -74,14 +79,26 @@ impl Component for PageMetrics { fn style(cx: &StyleCx<'_>, _: PageMetricsStyleKey) -> PageMetricsStyle { let tokens = cx.tokens; - let pad = tokens.space.pad; - PageMetricsStyle { - metrics: Metrics::new(), - gap: tokens.space.gap.section, - margin: pad.roomy, - side: tokens.size.rail.width, - white_space_pad: tokens.space.gap.inline, - seam: tokens.stroke.thin, + match cx.set() { + ComponentSet::Creative => PageMetricsStyle { + metrics: Metrics::new(), + gap: tokens.space.gap.section, + margin: tokens.space.pad.roomy, + side: tokens.size.rail.width, + white_space_pad: tokens.space.gap.inline, + seam: tokens.stroke.thin, + }, + ComponentSet::Productivity => { + let gap = tokens.space.gap.section * PRODUCTIVITY_GAP_RATIO; + PageMetricsStyle { + metrics: Metrics::new(), + gap, + margin: gap, + side: gap, + white_space_pad: tokens.space.gap.stack, + seam: tokens.stroke.thin, + } + } } } diff --git a/crates/pages/tests/it/views.rs b/crates/pages/tests/it/views.rs index d7ab14015..8a8f04cd6 100644 --- a/crates/pages/tests/it/views.rs +++ b/crates/pages/tests/it/views.rs @@ -4,11 +4,12 @@ use craft_behavior::geometry::{CropBox, SnapKind, SnapOptions, SnapTarget}; use craft_behavior::kurbo; use craft_behavior::{Axis, CancelReason, CanvasView, EditCommand}; -use craft_pages::layout::{Fit, LayoutOptions, PageDisplay}; +use craft_pages::layout::{Fit, LayoutOptions, PageDisplay, PagedLayout}; use craft_pages::ui::fixtures::{DemoPages, PAPER}; use craft_pages::ui::{ PagePreview, PageRegion, PageSnap, PageSource, PageView, PageViewState, PageViewWords, PlacedPage, ReadingNav, ReadingState, ReadingView, }; +use craft_theme::ComponentSet; use craft_ui::canvas::{CanvasTool, CropOverlay, ToolAction, ToolContext, ToolHost, ToolPath, ToolPointer}; use craft_ui::contract::{Bind, Role, Show as _}; @@ -958,6 +959,120 @@ fn go_to_a_point_inside_a_page_puts_it_at_the_top() { assert!((offset - at).abs() < 0.01, "the view's top {offset} is the point gone to, {at}"); } +/// Lays out three pages under `set` with `start`, returning the layout and the scope's `space.gap.section` token. +fn layout_in_set(set: ComponentSet, options: LayoutOptions, start: PageViewState, bodies: Option<&'static [(f64, f64)]>) -> (PagedLayout, f32) { + let state = Rc::new(RefCell::new(start)); + let seen: Rc> = Rc::default(); + let (kept, recorded) = (Rc::clone(&state), Rc::clone(&seen)); + let pages = DemoPages::new(3); + let mut fixture = Fixture::new(move |ui| { + let section_gap = Env::of(ui).tokens.space.gap.section; + let mut now = kept.borrow().clone(); + let mut view = PageView::new("Pages", &pages, &mut now, PAPER).options(options); + if let Some(bodies) = bodies { + view = view.bodies(bodies); + } + let out = view.show(ui, |_, _| ()); + *recorded.borrow_mut() = (out.layout, section_gap); + *kept.borrow_mut() = now; + }); + fixture.set(set); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + seen.borrow().clone() +} + +/// The productivity component set gives pages a wider inter-page gap, no tool-rail side gutter under Fit Width (without +/// overflowing the viewport), and wider Hide White Space padding than the creative set, while leaving `space.gap.section` +/// untouched for other components. +#[trial] +fn the_component_set_picks_the_page_spacing_without_changing_section_gap() { + let fixed = state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }); + let (creative, creative_section) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fixed.clone(), None); + let (productivity, productivity_section) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fixed, None); + let creative_gap = creative.rects[1].y0 - creative.rects[0].y1; + let productivity_gap = productivity.rects[1].y0 - productivity.rects[0].y1; + assert_eq!(productivity_section, creative_section, "space.gap.section is unchanged by the component set"); + assert!(productivity_gap > creative_gap, "productivity inter-page gap ({productivity_gap}) is wider than creative ({creative_gap})"); + assert!( + productivity.rects[0].y0 > creative.rects[0].y0, + "productivity top margin ({}) is wider than creative ({})", + productivity.rects[0].y0, + creative.rects[0].y0 + ); + + let fit_width = state_with(|s| { + s.fit = Fit::Width; + s.display = PageDisplay::Columns; + }); + let (creative_fit, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::WORD, fit_width.clone(), None); + let (productivity_fit, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::WORD, fit_width, None); + assert!( + productivity_fit.rects[0].width() > creative_fit.rects[0].width(), + "productivity Fit Width fills more of the viewport ({}) than creative with its rail gutter ({})", + productivity_fit.rects[0].width(), + creative_fit.rects[0].width() + ); + assert!( + productivity_fit.size.width <= 900.0 + 0.5, + "productivity Fit Width stays within the viewport width without horizontal overflow: {}", + productivity_fit.size.width + ); + + const BODIES: [(f64, f64); 3] = [(72.0, 720.0); 3]; + let hidden = state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Single; + s.hide_white_space = true; + }); + let (creative_hidden, _) = layout_in_set(ComponentSet::Creative, LayoutOptions::ACROBAT, hidden.clone(), Some(&BODIES)); + let (productivity_hidden, _) = layout_in_set(ComponentSet::Productivity, LayoutOptions::ACROBAT, hidden, Some(&BODIES)); + assert!( + productivity_hidden.bands[1].0 < creative_hidden.bands[1].0 && productivity_hidden.bands[1].1 > creative_hidden.bands[1].1, + "productivity Hide White Space keeps more pad around the text body: {:?} vs {:?}", + productivity_hidden.bands[1], + creative_hidden.bands[1] + ); +} + +/// Switching the component set updates the page view's inter-page spacing on the frame of the change and settles. +#[trial] +fn a_component_set_change_updates_the_page_view_spacing() { + let state = Rc::new(RefCell::new(state_with(|s| { + s.fit = Fit::None; + s.zoom = 1.0; + s.display = PageDisplay::Columns; + }))); + let gap = Rc::new(Cell::new(0.0_f64)); + let (kept, seen) = (Rc::clone(&state), Rc::clone(&gap)); + let pages = DemoPages::new(3); + let mut fixture = Fixture::new(move |ui| { + let mut now = kept.borrow().clone(); + let out = PageView::new("Pages", &pages, &mut now, PAPER).options(LayoutOptions::WORD).show(ui, |_, _| ()); + seen.set(out.layout.rects[1].y0 - out.layout.rects[0].y1); + *kept.borrow_mut() = now; + }); + fixture.set(ComponentSet::Creative); + fixture.room(vec2(900.0, 600.0)); + fixture.settle(); + let creative_gap = gap.get(); + + fixture.set(ComponentSet::Productivity); + fixture.frame(Vec::new()); + let productivity_gap = gap.get(); + assert!( + productivity_gap > creative_gap, + "switching to productivity widens the page gap on the frame of the change: {productivity_gap} vs {creative_gap}" + ); + fixture.idle(1); + assert_eq!(gap.get(), productivity_gap, "an idle frame after the switch keeps the new gap"); +} + /// `PageView::inactive_edits` forwards to its inner canvas editor: Cut resolves disabled while inactive and enabled /// once active, and Undo/Redo fall through to app command states while inactive. #[trial]