From d67796f4697ac366dcb50c4707b63451c6d96e25 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 09:20:09 +0000 Subject: [PATCH 01/40] focus: trials for the focus after a removed stop and after a closed canvas text editor Both fail on this branch: a stop that inherits the focus from a removed one is revealed, and a closed editor on a canvas with rulers hands the focus to the rulers' corner instead of the canvas. --- crates/text/tests/it/editor.rs | 48 ++++++++++++++++++++ crates/ui-contract/tests/it/runtime/focus.rs | 48 ++++++++++++++++++++ crates/ui-contract/tests/it/runtime/mod.rs | 1 + 3 files changed, 97 insertions(+) create mode 100644 crates/ui-contract/tests/it/runtime/focus.rs diff --git a/crates/text/tests/it/editor.rs b/crates/text/tests/it/editor.rs index f23eb21f19..7abc5e2139 100644 --- a/crates/text/tests/it/editor.rs +++ b/crates/text/tests/it/editor.rs @@ -346,3 +346,51 @@ fn formatting_keys_follow_the_flow_and_fall_back_to_caret_moves() { assert!(!plain.host.borrow().styles.is_empty(), "the host was asked for the leading step"); assert_eq!(plain.selection.borrow().caret, before.saturating_sub(LINE), "the step the host did not take moved the caret a line up"); } + +/// #15555: a session the app ends (Cmd+Enter, then the editor is not shown) on a canvas with rulers hands the focus back +/// to the canvas it came from, not to the stop before the editor (the rulers' corner, whose arrows move the zero point), +/// and the view stays where it was. Without rulers the canvas is that stop anyway. +#[trial] +fn an_ended_session_returns_the_focus_to_the_canvas_and_the_view_stays() { + const EDITOR: craft_behavior::DocKey = craft_behavior::DocKey::new("trial.type-editor"); + use craft_ui::canvas::Rulers; + use craft_ui::contract::Props as _; + use craft_ui::runtime::focus::{FocusTarget, request}; + use craft_ui::testing::access::{focused_key, name}; + + for rulers in [true, false] { + let editing = Rc::new(Cell::new(false)); + let view = Rc::new(Cell::new(None::)); + let (shown_editing, shown_view) = (Rc::clone(&editing), Rc::clone(&view)); + let mut host = Host { text: "abc".to_owned(), ..Host::default() }; + let mut selection = TextSelection::caret_at(3); + let mut zero = Point::ZERO; + let mut fixture = Fixture::new(move |ui| { + let room = ui.available_rect_before_wrap(); + let given = shown_view.get().unwrap_or_else(|| CanvasView::new(room, Point::new(100.0, 100.0), 1.0)); + let strips = rulers.then(|| Rulers::new("Rulers", Bind::bound(&mut zero))); + let canvas = Canvas::new("Document").view(given).with_rulers(strips).show(ui, |ui, body| { + if shown_editing.get() { + let bounds = Rect::from_min_size(body.rect.min + vec2(40.0, 40.0), vec2(200.0, 20.0)); + drop(TextEditor::new("Text", &mut host, Bind::bound(&mut selection)).doc_key(EDITOR).show_at(ui, bounds)); + } + }); + shown_view.set(Some(canvas.output.view.unwrap_or(given))); + }); + fixture.room(vec2(600.0, 400.0)).settle(); + let focused = |fixture: &Fixture| name(fixture.tree(), focused_key(fixture.tree())).map(str::to_owned); + // A press on the canvas focuses it, and the session that press starts asks for the editor's focus. + fixture.click_at(pos2(400.0, 300.0)).settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the press focused the canvas"); + editing.set(true); + fixture.settle(); + request(fixture.ctx(), FocusTarget::Doc(EDITOR)); + fixture.settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Text"), "rulers {rulers}: the editor took the focus"); + let before = view.get(); + editing.set(false); + fixture.settle(); + assert_eq!(focused(&fixture).as_deref(), Some("Document"), "rulers {rulers}: the focus went back to the canvas"); + assert_eq!(view.get(), before, "rulers {rulers}: the view stays"); + } +} diff --git a/crates/ui-contract/tests/it/runtime/focus.rs b/crates/ui-contract/tests/it/runtime/focus.rs new file mode 100644 index 0000000000..760df0268f --- /dev/null +++ b/crates/ui-contract/tests/it/runtime/focus.rs @@ -0,0 +1,48 @@ +//! Focus after the focused stop goes away. + +use craft_ui::contract::{ContainerProps, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft_ui::runtime::focus::{FocusTarget, request}; +use craft_ui::testing::layout::{Block, in_region}; +use craft_ui::testing::{Frames, trial}; +use craft_ui_test_kit::body::Slab; +use craft_ui_test_kit::contract::{Probe, Seen}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::{Cell, RefCell}; + +const ORIGIN: Pos2 = Pos2::new(10.0, 10.0); +const VIEW: Vec2 = Vec2::new(200.0, 100.0); + +/// The focused stop goes away and hands the focus to the next stop in its scope, far below a scrolling body's view: +/// the stop takes the focus and the body stays where it is. A neighbour that inherits the focus was not shown by +/// anyone, so nothing reveals it (#15555: the rulers' corner panned the canvas when a closed text editor handed it the +/// focus). +#[trial] +fn a_stop_that_inherits_the_focus_from_a_removed_one_is_not_revealed() { + let (first, next) = (RefCell::new(Seen::default()), RefCell::new(Seen::default())); + let shown = Cell::new(true); + let top = Cell::new(0.0f32); + let mut show = |ui: &mut Ui| { + in_region(ui, Rect::from_min_size(ORIGIN, VIEW), |ui| { + Slab::new(ContainerProps::new().scroll(Scroll::vertical())).id_salt("panel").show(ui, |ui, _| { + top.set(ui.next_widget_position().y); + if shown.get() { + Probe::new(&first).label("First").id_salt("first").show(ui); + } + Block::new(Vec2::new(VIEW.x, VIEW.y * 4.0)).show(ui); + Probe::new(&next).label("Next").id_salt("next").show(ui); + }); + }); + }; + let mut frames = Frames::new(); + frames.idle(3, &mut show); + let first_id = first.borrow().id.expect("the first stop ran"); + request(&frames.ctx, FocusTarget::Id(first_id)); + frames.idle(3, &mut show); + assert_eq!(craft_ui::testing::focus::egui_focused(&frames.ctx), Some(first_id), "the first stop took the focus"); + let start = top.get(); + shown.set(false); + frames.idle(6, &mut show); + let next_id = next.borrow().id.expect("the next stop ran"); + assert_eq!(craft_ui::testing::focus::egui_focused(&frames.ctx), Some(next_id), "the next stop inherits the focus"); + assert!((top.get() - start).abs() < 0.5, "the body keeps its offset: content top {} from {start}", top.get()); +} diff --git a/crates/ui-contract/tests/it/runtime/mod.rs b/crates/ui-contract/tests/it/runtime/mod.rs index 2567420c8a..a662980d95 100644 --- a/crates/ui-contract/tests/it/runtime/mod.rs +++ b/crates/ui-contract/tests/it/runtime/mod.rs @@ -7,6 +7,7 @@ pub(crate) mod cursor; pub(crate) mod derived; pub(crate) mod elapsed; pub(crate) mod env; +pub(crate) mod focus; pub(crate) mod frame; pub(crate) mod latch; pub(crate) mod memory; From 9de310681e441ac72d085eb26b19fe4eab59e828 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 09:21:49 +0000 Subject: [PATCH 02/40] focus: a stop that inherits the focus from a removed one is not revealed A removal hands the focus to a neighbour nobody chose to show, so no scroll owner reveals it: a deleted guide or a closed canvas text editor no longer pans the canvas to the stop beside it (photocraft#15555). --- crates/ui-contract/src/runtime/focus.rs | 3 ++- crates/ui-contract/src/runtime/focus/nav.rs | 7 +++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/runtime/focus.rs b/crates/ui-contract/src/runtime/focus.rs index 1adf515be0..459af9354a 100644 --- a/crates/ui-contract/src/runtime/focus.rs +++ b/crates/ui-contract/src/runtime/focus.rs @@ -780,7 +780,8 @@ pub(crate) enum FocusOrigin { /// it counts as an arrival by key, and a text part selects its whole text so typing replaces it. Open, /// The focused stop went away and handed focus to its neighbour: neither the keyboard nor a request chose it, so - /// it is no arrival by key (a deleted guide selects no other guide). + /// it is no arrival by key (a deleted guide selects no other guide) and no scroll owner reveals it (a closed canvas + /// text editor does not pan the canvas to the stop before it). Removal, } diff --git a/crates/ui-contract/src/runtime/focus/nav.rs b/crates/ui-contract/src/runtime/focus/nav.rs index c8a60dd788..32e9b9dcf2 100644 --- a/crates/ui-contract/src/runtime/focus/nav.rs +++ b/crates/ui-contract/src/runtime/focus/nav.rs @@ -168,11 +168,14 @@ impl State { self.focus_stop_from(rec, FocusOrigin::Request) } - /// [`focus_stop`](Self::focus_stop) with what moved focus there. + /// [`focus_stop`](Self::focus_stop) with what moved focus there. A stop that inherits the focus from a removed one + /// is not revealed: nothing chose to show it. fn focus_stop_from(&mut self, rec: StopRec, origin: FocusOrigin) -> Vec { let key = rec.stop.key(); let acts = self.enter_stop(rec, origin); - self.revealed = Some(key); + if origin != FocusOrigin::Removal { + self.revealed = Some(key); + } acts } From e826abef73ace7979b25c041b992d9a75c7cf25d Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 09:26:12 +0000 Subject: [PATCH 03/40] focus: a leaf can open a focus scope; the canvas text editor returns the focus to the canvas Component::FOCUS_SCOPE gives a leaf the scope ContainerProps::focus gives a container, through the leaf shape's focus hook. TextEditor opens a scope that restores (FocusPolicy::TAB_LAYER), so a session that ends hands the focus back to the stop it came from, the canvas, instead of the stop before the editor (the rulers' corner, whose arrows moved the zero point after a commit; photocraft#15555). Regenerates docs/contract-api.md. --- crates/text/src/ui/editor.rs | 4 +++- crates/ui-contract/src/contract/mod.rs | 6 ++++++ crates/ui-contract/src/contract/run.rs | 4 ++++ docs/contract-api.md | 1 + 4 files changed, 14 insertions(+), 1 deletion(-) diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index fad53f0831..8d8a85a0ed 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -40,7 +40,7 @@ use craft_ui::contract::{ use craft_ui::primitives::{EditorLine, EditorPurpose, EditorRun, EditorState, PaintShape, StrokeWidth}; use craft_ui::runtime::commands::ClipItem; use craft_ui::runtime::env::Label; -use craft_ui::runtime::focus::KeyUse; +use craft_ui::runtime::focus::{FocusPolicy, KeyUse}; use craft_ui::runtime::pending::Pending; use craft_ui::style::{ComponentStyle, StyleColor, StyleCx}; use egui::{Pos2, Rect, Response, Vec2}; @@ -461,6 +461,8 @@ impl Component for TextEditor<'_> { const INPUT: craft_ui::contract::Input = craft_ui::contract::Input::Editor; /// Escape always ends the session, so the editor keeps it from its row and from the shortcuts while focused. const KEYS: KeyUse = KeyUse::CODE.with_claims(&[ESCAPE]); + /// When the session ends, focus goes back to the stop it came from (the canvas), not to the stop before the editor. + const FOCUS_SCOPE: FocusPolicy = FocusPolicy::TAB_LAYER; type Style = TextEditorStyle; type Output = TextEditorOutput; diff --git a/crates/ui-contract/src/contract/mod.rs b/crates/ui-contract/src/contract/mod.rs index 7b44688d67..84cf4a8d78 100644 --- a/crates/ui-contract/src/contract/mod.rs +++ b/crates/ui-contract/src/contract/mod.rs @@ -356,6 +356,12 @@ pub trait Component: Meta + Sized { /// Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except /// for the roving group of a body the shape declares. const STOPS: bool = true; + /// The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its + /// parts lie inside it, and `FocusPolicy::NONE` (the default) opens none. A scope that restores + /// (`FocusPolicy::TAB_LAYER`) makes the stop focus came from its opener, so focus goes back there when the leaf + /// goes away with focus inside (a canvas text editor hands it back to the canvas). Containers and collections take + /// their scope from their props, not from this. + const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy = crate::runtime::focus::FocusPolicy::NONE; /// Keys the focused component keeps from egui and the shortcut dispatcher. const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(Self::INPUT); /// The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index caa4288235..2cb5c7baeb 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -317,6 +317,10 @@ impl ShapeHooks for LeafHooks { self.scope } + fn focus(&self, _: &C) -> Option { + (C::FOCUS_SCOPE != crate::runtime::focus::FocusPolicy::NONE).then_some(C::FOCUS_SCOPE) + } + fn sized(&self, comp: &C, ui: &Ui, id: Id, size: Vec2) -> Vec2 { use craft_behavior::Axis; let room = crate::layout::leaf_fill_room(ui); diff --git a/docs/contract-api.md b/docs/contract-api.md index 70e62b5117..5d27b1e546 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -1837,6 +1837,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `const OVERLAYS: bool`. Whether the component hosts popups: `false` skips the overlay bookkeeping of steps 9, 10, 12, 15 and 16. - `const PARTS: bool`. Whether the component declares parts, a text part or an editor part: `false` skips the parts step (the parts - `const STOPS: bool`. Whether the component or its parts can take key focus: `false` skips the stop registration of step 7, except + - `const FOCUS_SCOPE: crate::runtime::focus::FocusPolicy`. The focus scope a leaf runs in, as `ContainerProps::focus` gives a container's: the leaf's own stop and its - `const KEYS: crate::runtime::focus::KeyUse`. Keys the focused component keeps from egui and the shortcut dispatcher. - `fn keys(&self) -> crate::runtime::focus::KeyUse`. The keys this instance keeps in its current state. The default is `KEYS`; a component whose key use depends - `const SHOWS_LABEL: bool`. Whether the component paints its label as visible text. `false` for a face that shows only an icon or a From 2d8b8429548e3f4b05acbee0f9ed1882762ce7f9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 19:48:46 +0000 Subject: [PATCH 04/40] A content-sized shell slot runs its content in the room it can grow into A SlotSize::Content slot ran its content in the rect it was laid out at, the extent its content took in the last pass. A child that fills its height there is capped at that room, so content of fill-height containers (the ribbon's groups) could never grow the slot past its first height, and their controls ran past their containers' feet. The slot's pane is now as large as its content from its outer edge (ShellPane::at_content_extent, which covers bottom and side panes as well as the top), in the room from that edge to the far edge of what the slots before it leave. The window is still laid out at the kept extent, and remeasure lays it out again when the pane's extent differs. --- crates/ui-contract/src/contract/body/hooks.rs | 4 +- crates/ui-contract/src/contract/body/size.rs | 9 +- crates/ui-contract/src/contract/container.rs | 19 ++-- crates/ui-contract/src/contract/mount.rs | 15 ++- crates/ui-shell/src/shell/app_shell.rs | 46 ++++----- crates/ui-shell/src/shell/regions.rs | 11 ++- crates/ui-shell/tests/it/shell/app_shell.rs | 98 ++++++++++++++++++- 7 files changed, 158 insertions(+), 44 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index bf9e23c47b..2ff1164aaa 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -1787,10 +1787,10 @@ impl BodyHooks<'_> { fn measure_room(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>) -> Result { let props = &self.props; // A mount outside the flow takes no room in a parent's sizing pass, so its regions run only when it is - // measured itself. A pane as tall as its content takes its height in the flow. + // measured itself. A pane as large as its content takes its extent in the flow. let flows = match &props.mount { Mount::Inline => true, - Mount::Pane(pane) => pane.content_height, + Mount::Pane(pane) => pane.content_extent, _ => false, }; if !flows && at.ui.is_sizing_pass() { diff --git a/crates/ui-contract/src/contract/body/size.rs b/crates/ui-contract/src/contract/body/size.rs index 1cb5f02c7a..6111db5111 100644 --- a/crates/ui-contract/src/contract/body/size.rs +++ b/crates/ui-contract/src/contract/body/size.rs @@ -5,7 +5,7 @@ use super::placement::overlay_of; use super::regions::{RegionSizes, end_full_height, footer_in_body, footer_in_end}; use super::scroll::scroll_of; use crate::contract::run::ShowAt; -use crate::contract::{ContainerProps, Mount, PadEdges, ShellPane, Sizing}; +use crate::contract::{ContainerProps, Mount, PadEdges, PaneEdge, ShellPane, Sizing}; use crate::runtime::egui::areas; use crate::runtime::env::Env; use crate::runtime::layout_memory; @@ -103,7 +103,8 @@ impl<'b> BodyHooks<'b> { /// from its content until the user sizes it; an inline container follows its props. pub(super) fn sizing(&self, props: &ContainerProps) -> Sizing { match &props.mount { - Mount::Pane(pane) if pane.content_height => Sizing::FillWidth, + Mount::Pane(pane) if pane.content_extent && matches!(pane.edge, PaneEdge::Start | PaneEdge::End) => Sizing::FillHeight, + Mount::Pane(pane) if pane.content_extent => Sizing::FillWidth, Mount::Pane(_) | Mount::Window { .. } => Sizing::Fill, Mount::Layer(_) | Mount::Viewport { .. } | Mount::FullWindow if self.fixed => Sizing::Fill, Mount::Layer(_) | Mount::Viewport { .. } => Sizing::Content, @@ -327,9 +328,9 @@ impl<'b> BodyHooks<'b> { None => room, } } - // A pane as tall as its content runs in the rect its caller laid out. + // A pane as large as its content runs in the rect its caller laid out. _ => match (&props.mount, at) { - (Mount::Pane(ShellPane { at: Some(rect), content_height: true, .. }), _) => rect.size(), + (Mount::Pane(ShellPane { at: Some(rect), content_extent: true, .. }), _) => rect.size(), (_, ShowAt::Rect(rect)) => rect.size(), (_, ShowAt::Flow) => { let room = crate::layout::flow_room(ui); diff --git a/crates/ui-contract/src/contract/container.rs b/crates/ui-contract/src/contract/container.rs index 13a48e3c98..3273987815 100644 --- a/crates/ui-contract/src/contract/container.rs +++ b/crates/ui-contract/src/contract/container.rs @@ -72,8 +72,10 @@ impl Mount { /// its siblings (so a pane can overlay another) and ignores the extent. Otherwise an edge pane takes /// [`extent`](Self::extent) along its edge from the room left, or, without an extent, the size it first took, which it /// keeps in pane memory until the user resizes it. The central pane fills what the edge panes leave. A pane at a rect -/// that is as tall as its content (a content-sized embedded shell's body) takes the rect's width, its content's height -/// from the rect's top, and that room in the flow of its parent. +/// that is as large as its content along its edge (a content-sized embedded shell's body, a slot sized by its content) +/// takes the rect's cross extent, its content's extent from the rect's outer edge, and that room in the flow of its +/// parent: a top or central pane its height from the rect's top, a bottom pane its height from the rect's bottom, a +/// start or end pane its width from that side. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct ShellPane { @@ -85,14 +87,14 @@ pub struct ShellPane { pub extent: Option, /// The rect the caller laid the pane out in. pub at: Option, - /// The pane at `at` is as tall as its content. - pub(crate) content_height: bool, + /// The pane at `at` is as large as its content along its edge. + pub(crate) content_extent: bool, } impl ShellPane { /// The central pane named `name`. pub const fn new(name: &'static str) -> Self { - ShellPane { name, edge: PaneEdge::Center, extent: None, at: None, content_height: false } + ShellPane { name, edge: PaneEdge::Center, extent: None, at: None, content_extent: false } } /// The pane at `edge`. @@ -113,11 +115,12 @@ impl ShellPane { self } - /// The pane at `rect`, as tall as its content from the rect's top, taking that room in its parent's flow. + /// The pane in `rect`, as large as its content along its edge from the rect's outer edge, taking that room in its + /// parent's flow. `rect` is the room the content may take. #[doc(hidden)] - pub const fn at_content_height(mut self, rect: Rect) -> Self { + pub const fn at_content_extent(mut self, rect: Rect) -> Self { self.at = Some(rect); - self.content_height = true; + self.content_extent = true; self } } diff --git a/crates/ui-contract/src/contract/mount.rs b/crates/ui-contract/src/contract/mount.rs index 34137bf9a5..fc2e44b89f 100644 --- a/crates/ui-contract/src/contract/mount.rs +++ b/crates/ui-contract/src/contract/mount.rs @@ -143,11 +143,20 @@ pub(super) fn pane_grip_id(id: Id) -> Id { impl Host for PaneHost { fn run(&mut self, id: Id, parent: &mut Ui, env: &Env, pass: &mut HostPass<'_>) { - // A pane the caller laid out shows in its rect and leaves the room of its siblings alone; one as tall as its - // content flows from the rect's top and takes its height in the parent's flow. + // A pane the caller laid out shows in its rect and leaves the room of its siblings alone; one as large as its + // content flows from the rect's outer edge and takes its extent in the parent's flow. if let Some(rect) = self.0.at { - if self.0.content_height { + if self.0.content_extent { + let rtl = env.direction.is_rtl(); let builder = egui::UiBuilder::new().max_rect(rect); + let builder = match self.0.edge { + PaneEdge::Bottom => builder.layout(egui::Layout::bottom_up(egui::Align::Min)), + PaneEdge::Start | PaneEdge::End if (self.0.edge == PaneEdge::Start) == rtl => { + builder.layout(egui::Layout::right_to_left(egui::Align::Min)) + } + PaneEdge::Start | PaneEdge::End => builder.layout(egui::Layout::left_to_right(egui::Align::Min)), + _ => builder, + }; let mut ui = crate::runtime::egui::alloc::child(parent, builder); pass(&mut ui, Some(ShowAt::Flow), None); crate::runtime::egui::alloc::advance_past(parent, ui.min_rect()); diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index 12105351e1..3265508d7c 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -653,6 +653,15 @@ impl<'a, S> AppShell<'a, S> { let panels_hidden = kept.reveal.panels_hidden(); let rect_of = |key| regions.slots.iter().find(|(shown, _)| *shown == key).map_or(Rect::ZERO, |(_, rect)| *rect); + // The room a content slot can grow into: from its outer edge to the far edge of what the slots before it + // leave. Its content runs there, so it measures at its own extent, never at the extent it was laid out at. + let window_rect = cx.rect; + let grow_room = |key: SlotKey| { + let Some(at) = claims.iter().position(|claim| claim.key == key) else { return Rect::ZERO }; + let mut claimed = claims[..=at].to_vec(); + claimed[at].extent = f32::INFINITY; + layout(window_rect, &claimed, rtl).slots.get(at).map_or(Rect::ZERO, |(_, rect)| *rect) + }; // The extents the content slots were laid out at, and what their content took in this pass. let measured_before = kept.measured.clone(); let mut measured_now: Vec<(SlotKey, f32)> = Vec::new(); @@ -667,7 +676,7 @@ impl<'a, S> AppShell<'a, S> { } if let Some((scope, SlotBody(page))) = page.as_mut() { let pane = ShellPane::new("page"); - let pane = if content_room.is_some() { pane.at_content_height(regions.body) } else { pane.at(regions.body) }; + let pane = if content_room.is_some() { pane.at_content_extent(regions.body) } else { pane.at(regions.body) }; let mut region = ShellRegion::pane(pane).label(body_label.clone()); region.props = region.props.command_scope(*scope); let shown = region.show(ui, |ui, bcx| page(ui, bcx, app)); @@ -690,8 +699,10 @@ impl<'a, S> AppShell<'a, S> { let by_content = placed.sized_by_content(); let along_x = placed.along_x(); let Placed { slot, edge, named, add, .. } = placed; - let at = rect_of(slot.key()); - let pane = ShellPane::new(slot.key()).edge(*edge).extent(extent).at(at); + // A slot sized by its content is as large as its content from its outer edge, in the room it + // can grow into; any other slot fills its rect. + let pane = ShellPane::new(slot.key()).edge(*edge).extent(extent); + let pane = if by_content { pane.at_content_extent(grow_room(slot.key())) } else { pane.at(rect_of(slot.key())) }; // Every slot is a chrome pane: it paints the surface under its bar or rail and the rule toward // the body. let mut region = ShellRegion::chrome(pane).id_salt(("slot", slot.key())); @@ -709,28 +720,19 @@ impl<'a, S> AppShell<'a, S> { region.show(ui, |ui, bcx| add(ui, bcx, app)); continue; } - // The slot's extent along its edge: what its content allocated, plus what the pane keeps + // The slot's extent along its edge is the pane's: its content's, with what the pane keeps // around its body (its rule). A top or bottom slot's content fills its width and is as tall - // as it is; a rail's is as wide as it is. The content is read from the `Ui` it allocated in, - // never from the stack's response: a response rect is clipped to the pane (`sense_root`), so - // it can never report more than the extent the slot was laid out at. - let took = region + // as it is; a rail's is as wide as it is. + let pane = region .show(ui, |ui, bcx| { - let room = ui.max_rect(); - let inset = (if along_x { at.width() - room.width() } else { at.height() - room.height() }).max(0.0); let stack = if along_x { Stack::new() } else { Stack::new().fill_width() }; - stack - .show(ui, |ui, _| { - add(ui, bcx, app); - let content = ui.min_rect(); - if along_x { content.width() } else { content.height() } - }) - .inner - .map(|content| content + if inset.is_finite() { inset } else { 0.0 }) + stack.show(ui, |ui, _| add(ui, bcx, app)); }) - .inner - .flatten(); - if let Some(took) = took.filter(|took| took.is_finite() && *took > 0.0) { + .output + .response + .rect; + let took = if along_x { pane.width() } else { pane.height() }; + if took.is_finite() && took > 0.0 { measured_now.push((key, took)); } } @@ -740,7 +742,7 @@ impl<'a, S> AppShell<'a, S> { // mode's surround (Focus's black). Otherwise the body paints what it shows, and the gaps between its parts // (the dock's gutters) show the window's background; Immersive's body fills the room with its own canvas. let pane = ShellPane::new("body"); - let pane = if content_room.is_some() { pane.at_content_height(regions.body) } else { pane.at(regions.body) }; + let pane = if content_room.is_some() { pane.at_content_extent(regions.body) } else { pane.at(regions.body) }; let mut center = ShellRegion::pane(pane).label(body_label.clone()); let surround = if only && !host_only { Some(SurfaceKind::Scrim) } else { mode.surround() }; if let Some(surface) = surround { diff --git a/crates/ui-shell/src/shell/regions.rs b/crates/ui-shell/src/shell/regions.rs index 332644a378..ade4209785 100644 --- a/crates/ui-shell/src/shell/regions.rs +++ b/crates/ui-shell/src/shell/regions.rs @@ -22,10 +22,13 @@ pub enum SlotSize { OptionsBarNarrow, /// `size.rail.width`: the default extent of a start or end slot. RailWidth, - /// As tall (a top or bottom slot) or as wide (a start or end slot) as its content: the extent the content took the - /// last time the slot showed, and the edge's default until it first shows. The slot stacks its content from its - /// outer edge instead of centring one line in it, so content of more than one line (a ribbon: a tab strip over a - /// group row) gets its own height and the slot's full width. Outside a shell it resolves to `size.bar.options`. + /// As tall (a top or bottom slot) or as wide (a start or end slot) as its content. The window is laid out at the + /// extent the content took the last time the slot showed (the edge's default until it first shows), while the + /// content runs in the room the slot can grow into, from its outer edge to the far edge of what the slots before it + /// leave: it measures at its own extent, and when that differs the shell lays the window out again in the same + /// frame. The slot stacks its content from its outer edge instead of centring one line in it, so content of more + /// than one line (a ribbon: a tab strip over a group row) gets its own height and the slot's full width. Outside a + /// shell it resolves to `size.bar.options`. Content, } diff --git a/crates/ui-shell/tests/it/shell/app_shell.rs b/crates/ui-shell/tests/it/shell/app_shell.rs index 0ae4eb7783..5dd6ab6724 100644 --- a/crates/ui-shell/tests/it/shell/app_shell.rs +++ b/crates/ui-shell/tests/it/shell/app_shell.rs @@ -3,10 +3,11 @@ //! body, and its band keeps the window's ends and moves the window. use craft_host::target::ShellInfo; +use craft_theme::Size; use craft_ui::bars::{Bar, BarKind}; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; -use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; use craft_ui::dialog::Dialog; use craft_ui::display::Text; use craft_ui::layout_components::{Row, Stack}; @@ -138,6 +139,101 @@ fn a_top_slot_sized_by_its_content_stacks_it_and_takes_its_height() { assert!(body.min.y >= row.max.y - SLACK, "the body {body:?} starts under the row {row:?}"); } +/// The labels of a column of buttons taller than a slot's default extent. +const TALL: [&str; 6] = ["Paste", "Cut", "Copy", "Format Painter", "Clipboard", "Styles"]; + +/// The rect of the fill-height column a content slot holds and of each of its buttons, from the last run. +type Column = Rc)>>; + +fn column() -> Column { + Rc::new(RefCell::new((Rect::NOTHING, Vec::new()))) +} + +/// A column of `labels` that fills its height, as a ribbon group does, recording its rects in `seen`. +fn fill_column(ui: &mut Ui, labels: &[&'static str], seen: &Column) { + let mut buttons = Vec::new(); + let column = Stack::new() + .sizing(Sizing::FillHeight) + .show(ui, |ui, _| { + for label in labels { + buttons.push(Button::new(*label).show(ui).rect); + } + }) + .output + .rect; + *seen.borrow_mut() = (column, buttons); +} + +/// A content slot whose content fills its height grows to that content, at the top and at the bottom edge: its +/// content runs in the room the slot can grow into, not in the extent it was first laid out at, so the column takes +/// its buttons' height and the slot takes the column's. +#[trial] +fn a_slot_sized_by_its_content_grows_to_a_child_that_fills_its_height() { + let (top, bottom) = (column(), column()); + let regions = Rc::new(RefCell::new(None)); + let (top_seen, bottom_seen, out) = (Rc::clone(&top), Rc::clone(&bottom), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| fill_column(ui, &TALL, &top_seen)) + .bottom(Slot::new("findBar").size(SlotSize::Content), |ui, _, _: &mut ()| fill_column(ui, &TALL, &bottom_seen)) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.room(Vec2::new(600.0, 700.0)).settle(); + let regions = regions.borrow().clone().expect("the shell shows"); + const SLACK: f32 = 1.0; + for (key, seen) in [("ribbon", &top), ("findBar", &bottom)] { + let slot = regions.slots.iter().find(|(shown, _)| *shown == key).map(|(_, rect)| *rect).expect("the slot shows"); + let (column, buttons) = seen.borrow().clone(); + assert_eq!(buttons.len(), TALL.len(), "{key}: every button shows"); + for button in &buttons { + assert!(column.expand(SLACK).contains_rect(*button), "{key}: the button {button:?} lies in its column {column:?}"); + } + assert!(slot.expand(SLACK).contains_rect(column), "{key}: the slot {slot:?} holds its column {column:?}"); + } + let (top_slot, bottom_slot) = (regions.slots[0].1, regions.slots[1].1); + assert!( + regions.body.min.y >= top_slot.max.y - SLACK && regions.body.max.y <= bottom_slot.min.y + SLACK, + "the body {:?} lies between the slots", + regions.body + ); + assert!((bottom_slot.max.y - 700.0).abs() <= SLACK, "the bottom slot {bottom_slot:?} stands on the window's bottom edge"); +} + +/// A settled frame runs a content slot's content once, in one pass: its measure is reused while its inputs are +/// unchanged. A frame where the content grows (a denser theme makes every button taller) lays the window out again at +/// most once and shows the new extent in that frame. +#[trial] +fn a_content_slot_runs_its_content_once_per_settled_frame_and_grows_in_one_frame() { + let runs = Rc::new(Cell::new(0_u32)); + let seen = column(); + let regions = Rc::new(RefCell::new(None)); + let (count, column, out) = (Rc::clone(&runs), Rc::clone(&seen), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| { + count.set(count.get() + 1); + fill_column(ui, &TALL, &column); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.room(Vec2::new(600.0, 700.0)).density(Size::Compact).settle(); + let before = seen.borrow().0; + runs.set(0); + fixture.frame(Vec::new()); + assert_eq!(fixture.passes(), 1, "a settled frame runs one pass"); + assert_eq!(runs.get(), 1, "a settled frame runs the slot's content once"); + fixture.density(Size::Comfortable).frame(Vec::new()); + assert!(fixture.passes() <= 2, "the frame the content grows in lays the window out again at most once: {} passes", fixture.passes()); + let slot = regions.borrow().as_ref().and_then(|regions| regions.slots.first().map(|(_, rect)| *rect)).expect("the slot shows"); + let grown = seen.borrow().0; + assert!(grown.height() > before.height() + 1.0, "the denser theme makes the column taller: {before:?} to {grown:?}"); + assert!(slot.expand(1.0).contains_rect(grown), "in the frame it grows in, the slot {slot:?} holds the grown column {grown:?}"); +} + /// A check box with its label after it sits on the options slot's middle, as a button beside it does: the slot is /// shorter than the bar asks for, and the bar centres its members in it. #[trial] From aae6c5a458e138aee1e579c2d41cd72f0c43d7c8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 20:15:40 +0000 Subject: [PATCH 05/40] 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 bf9e23c47b..9cda37695f 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 1cb5f02c7a..cae3774d6b 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 bb622ea9fc..6594e2b687 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 f65e44ecc1..57accbccc2 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 c9afb1e1d7..77090807d0 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 9708a392ef..a76a73908d 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 92a3cd6b83..b77106fb88 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 54255f5927cc98267fac763c82b70e673bb04b89 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 15:27:58 -0500 Subject: [PATCH 06/40] Keep checkbox sweep runtime below the contract layer --- crates/ui-contract/src/contract/cx/pointer.rs | 9 +++- .../ui-contract/src/runtime/toggle_sweep.rs | 41 +++++++++++-------- 2 files changed, 31 insertions(+), 19 deletions(-) diff --git a/crates/ui-contract/src/contract/cx/pointer.rs b/crates/ui-contract/src/contract/cx/pointer.rs index f9afcf9e59..f666b3800f 100644 --- a/crates/ui-contract/src/contract/cx/pointer.rs +++ b/crates/ui-contract/src/contract/cx/pointer.rs @@ -255,7 +255,14 @@ impl Cx<'_, C> { /// participate. A control that uses this must sense both clicks and drags. pub fn swept_toggle(&self, on: Option) -> Option { let group = self.pointer_group?; - crate::runtime::toggle_sweep::value(self, group, on) + let target = crate::runtime::toggle_sweep::ToggleTarget { + id: self.id, + layer: self.response.layer_id, + visible: self.visible, + enabled: self.resolved.enabled && !self.resolved.read_only, + press: self.press().phase, + }; + crate::runtime::toggle_sweep::value(&self.ctx, target, group, on) } } diff --git a/crates/ui-contract/src/runtime/toggle_sweep.rs b/crates/ui-contract/src/runtime/toggle_sweep.rs index 644d7b9eae..4c151ffb6d 100644 --- a/crates/ui-contract/src/runtime/toggle_sweep.rs +++ b/crates/ui-contract/src/runtime/toggle_sweep.rs @@ -3,9 +3,8 @@ use std::sync::Arc; use craft_behavior::{PointerButton, PointerEvent, PressPhase, PressStart}; -use egui::{Context, Id, IdSet, LayerId, Pos2, Rect}; +use egui::{Context, Id, IdSet, Pos2, Rect}; -use crate::contract::{CxCore, Pointer as _}; use crate::runtime::egui::{areas, pass}; use crate::runtime::frame::{PerViewport, Stored}; use crate::runtime::pointer::{self, PassPointer}; @@ -143,50 +142,56 @@ impl Record { } } -pub(crate) fn value(cx: &CxCore<'_>, group: Id, on: Option) -> Option { - let ctx = &cx.ctx; +pub(crate) struct ToggleTarget { + pub id: Id, + pub layer: areas::Layer, + pub visible: Rect, + pub enabled: bool, + pub press: PressPhase, +} + +pub(crate) fn value(ctx: &Context, target: ToggleTarget, group: Id, on: Option) -> Option { + let ToggleTarget { id, layer, visible, enabled, press } = target; let viewport = pass::current_viewport(ctx); let pass = pointer::pass_of(ctx); let input = pointer::pass_pointer(ctx); let cancelled = pointer::cancel_of_pass(ctx).is_some(); - let layer = cx.response.layer_id; - let enabled = cx.resolved.enabled && !cx.resolved.read_only; let eligible = |sweep: &Sweep| enabled && sweep.group == group && sweep.travel.dragging; let completed = PerViewport::::with(ctx, viewport, |record| { record.advance(pass, &input, cancelled); let finished = record.completed.as_ref().filter(|finished| eligible(&finished.sweep))?; let sweep = &finished.sweep; - if sweep.owner == cx.id { + if sweep.owner == id { return Some((sweep.on, None)); } - (!sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&finished.path)))) + (!sweep.visited.contains(&id)).then(|| (sweep.on, Some(Arc::clone(&finished.path)))) }) .and_then(|(on, path)| { if let Some(path) = path { - if !crosses_visible(ctx, layer, cx.visible, &path) { + if !crosses_visible(ctx, layer, visible, &path) { return None; } PerViewport::::with(ctx, viewport, |record| { if let Some(finished) = &mut record.completed { - finished.sweep.visited.insert(cx.id); + finished.sweep.visited.insert(id); } }); } Some(on) }); let ready = PerViewport::::with(ctx, viewport, |record| { - match cx.press().phase { + match press { PressPhase::Down { start, .. } if start.button == PointerButton::Primary && enabled => { - record.start(cx.id, group, start, !completed.or(on).unwrap_or(false), &input); + record.start(id, group, start, !completed.or(on).unwrap_or(false), &input); } - PressPhase::Cancel { .. } if record.sweep.as_ref().is_some_and(|sweep| sweep.owner == cx.id) => record.sweep = None, + PressPhase::Cancel { .. } if record.sweep.as_ref().is_some_and(|sweep| sweep.owner == id) => record.sweep = None, _ => {} } let sweep = record.sweep.as_ref().filter(|sweep| eligible(sweep))?; - if sweep.owner == cx.id { + if sweep.owner == id { return Some((sweep.on, None, record.replay_first_path)); } - (!record.path.is_empty() && !sweep.visited.contains(&cx.id)).then(|| (sweep.on, Some(Arc::clone(&record.path)), false)) + (!record.path.is_empty() && !sweep.visited.contains(&id)).then(|| (sweep.on, Some(Arc::clone(&record.path)), false)) }); let Some(ready) = ready else { return completed }; let (on, path, replay) = ready; @@ -194,12 +199,12 @@ pub(crate) fn value(cx: &CxCore<'_>, group: Id, on: Option) -> Option::with(ctx, viewport, |record| { if let Some(sweep) = &mut record.sweep { - sweep.visited.insert(cx.id); + sweep.visited.insert(id); } }); } @@ -227,7 +232,7 @@ fn clipped((from, to): Segment, rect: Rect) -> Option { (start <= end).then(|| (from + delta * start, from + delta * end)) } -pub(crate) fn crosses_visible(ctx: &Context, layer: LayerId, rect: Rect, path: &[Segment]) -> bool { +pub(crate) fn crosses_visible(ctx: &Context, layer: areas::Layer, rect: Rect, path: &[Segment]) -> bool { let map = areas::layer_map(ctx, layer); let rect = map.map_or(rect, |map| Rect::from_min_max(map.to_screen(rect.min), map.to_screen(rect.max))); path.iter().copied().filter_map(|segment| clipped(segment, rect)).any(|(from, to)| areas::layer_between(ctx, layer, from, to)) From 5366157e63ea58feb3f2d093acdd7022426ed4d9 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 20:37:02 +0000 Subject: [PATCH 07/40] A content slot records its extent only from its own real run The shell recorded a content slot's extent from any run of its content, including the scope's measuring run, which alone runs for an embedded shell out of sight. The slot's own body now says whether it ran for real, and only that run records. A content slot's pane no longer carries an extent: a pane at a rect ignores it. The out-of-sight trial also holds a content slot, which does not run. --- crates/ui-shell/src/shell/app_shell.rs | 33 +++++++++++--------- crates/ui-shell/tests/it/dialog/contained.rs | 15 +++++++-- 2 files changed, 30 insertions(+), 18 deletions(-) diff --git a/crates/ui-shell/src/shell/app_shell.rs b/crates/ui-shell/src/shell/app_shell.rs index 3265508d7c..4b93f560d4 100644 --- a/crates/ui-shell/src/shell/app_shell.rs +++ b/crates/ui-shell/src/shell/app_shell.rs @@ -695,14 +695,17 @@ impl<'a, S> AppShell<'a, S> { if !*shown || covers(&placed.slot, only) != covering { continue; } - let extent = placed.extent(&tokens, &measured_before); let by_content = placed.sized_by_content(); let along_x = placed.along_x(); - let Placed { slot, edge, named, add, .. } = placed; // A slot sized by its content is as large as its content from its outer edge, in the room it - // can grow into; any other slot fills its rect. - let pane = ShellPane::new(slot.key()).edge(*edge).extent(extent); - let pane = if by_content { pane.at_content_extent(grow_room(slot.key())) } else { pane.at(rect_of(slot.key())) }; + // can grow into; any other slot takes its extent and fills its rect. + let pane = ShellPane::new(placed.slot.key()).edge(placed.edge); + let pane = if by_content { + pane.at_content_extent(grow_room(placed.slot.key())) + } else { + pane.extent(placed.extent(&tokens, &measured_before)).at(rect_of(placed.slot.key())) + }; + let Placed { slot, named, add, .. } = placed; // Every slot is a chrome pane: it paints the surface under its bar or rail and the rule toward // the body. let mut region = ShellRegion::chrome(pane).id_salt(("slot", slot.key())); @@ -722,17 +725,17 @@ impl<'a, S> AppShell<'a, S> { } // The slot's extent along its edge is the pane's: its content's, with what the pane keeps // around its body (its rule). A top or bottom slot's content fills its width and is as tall - // as it is; a rail's is as wide as it is. - let pane = region - .show(ui, |ui, bcx| { - let stack = if along_x { Stack::new() } else { Stack::new().fill_width() }; - stack.show(ui, |ui, _| add(ui, bcx, app)); - }) - .output - .response - .rect; + // as it is; a rail's is as wide as it is. Only the slot's own real run records it: a run in a + // sizing pass (the scope's measuring run, which alone runs for a shell out of sight) is not + // what shows. + let shown = region.show(ui, |ui, bcx| { + let stack = if along_x { Stack::new() } else { Stack::new().fill_width() }; + stack.show(ui, |ui, _| add(ui, bcx, app)); + !ui.is_sizing_pass() + }); + let pane = shown.output.response.rect; let took = if along_x { pane.width() } else { pane.height() }; - if took.is_finite() && took > 0.0 { + if shown.inner == Some(true) && took.is_finite() && took > 0.0 { measured_now.push((key, took)); } } diff --git a/crates/ui-shell/tests/it/dialog/contained.rs b/crates/ui-shell/tests/it/dialog/contained.rs index e049c8daa1..70a82595e5 100644 --- a/crates/ui-shell/tests/it/dialog/contained.rs +++ b/crates/ui-shell/tests/it/dialog/contained.rs @@ -6,7 +6,7 @@ use craft_ui::dialog::Dialog; use craft_ui::layout_components::Stack; use craft_ui::runtime::env::WindowKey; use craft_ui::sections::{DialogRole, FooterButton}; -use craft_ui::shell::AppShell; +use craft_ui::shell::{AppShell, Slot, SlotSize}; use craft_ui::testing::contract::clicked; use craft_ui::testing::{Fixture, trial}; use egui::{Rect, Ui}; @@ -87,16 +87,24 @@ fn a_dialog_in_an_embedded_region_is_placed_in_it_and_blocks_only_it() { } /// An embedded shell scrolled out of sight with its dialog open shows nothing and does not fail: its region has no -/// room, so neither its body nor its dialog runs in that pass. +/// room, so neither its body, its dialog nor a slot sized by its content runs in that pass. #[trial] fn an_embedded_shell_out_of_sight_shows_nothing() { - let mut fixture = Fixture::new(|ui| { + let real = Rc::new(Cell::new(0_u32)); + let count = Rc::clone(&real); + let mut fixture = Fixture::new(move |ui| { Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { let _ = Button::new("Top").show(ui); let view = ui.clip_rect(); let below = Rect::from_min_size(egui::pos2(view.min.x, view.max.y + view.height()), egui::vec2(view.width(), view.height())); let mut open = true; AppShell::embedded(WindowKey::new("out-of-sight")) + .top(Slot::new("ribbon").size(SlotSize::Content), |ui, _, _: &mut ()| { + if !ui.is_sizing_pass() { + count.set(count.get() + 1); + } + let _ = Button::new("Slot").show(ui); + }) .body(|ui, _, _| { let _ = Button::new("Hidden").show(ui); Dialog::new("Out of sight").opened(Bind::bound(&mut open)).show(ui, |_, _| {}); @@ -108,4 +116,5 @@ fn an_embedded_shell_out_of_sight_shows_nothing() { assert!(fixture.by_label("Top").is_some(), "the visible part is shown"); assert!(fixture.by_role(Role::DIALOG).is_empty(), "the dialog of a shell out of sight is not shown"); assert!(fixture.by_label("Hidden").is_none(), "the body of a shell out of sight does not run"); + assert!(fixture.by_label("Slot").is_none() && real.get() == 0, "the content slot of a shell out of sight does not run"); } From 0aa781ecf0e979163fa847f8e65d8fb5fd884cc4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 20:37:02 +0000 Subject: [PATCH 08/40] Trials for content rails, scrolling lists and the settled frame after a grow Content start and end rails sit at their sides in left-to-right and right-to-left windows, hold their content and settle in one pass with each rail's content run once. A content slot holding a vertically scrolling list, content-sized or filling its height, is as tall as the list's rows and the body keeps the rest of the window. The count trial's grow half also checks that the next frame is settled. SlotSize::Content documents that the slot never takes more than the room the window leaves it, and that raw egui content allocates its own extent along the slot's edge. --- crates/ui-shell/src/shell/regions.rs | 8 +- crates/ui-shell/tests/it/shell/app_shell.rs | 102 +++++++++++++++++++- 2 files changed, 105 insertions(+), 5 deletions(-) diff --git a/crates/ui-shell/src/shell/regions.rs b/crates/ui-shell/src/shell/regions.rs index ade4209785..150a55d64b 100644 --- a/crates/ui-shell/src/shell/regions.rs +++ b/crates/ui-shell/src/shell/regions.rs @@ -27,8 +27,12 @@ pub enum SlotSize { /// content runs in the room the slot can grow into, from its outer edge to the far edge of what the slots before it /// leave: it measures at its own extent, and when that differs the shell lays the window out again in the same /// frame. The slot stacks its content from its outer edge instead of centring one line in it, so content of more - /// than one line (a ribbon: a tab strip over a group row) gets its own height and the slot's full width. Outside a - /// shell it resolves to `size.bar.options`. + /// than one line (a ribbon: a tab strip over a group row) gets its own height and the slot's full width. + /// + /// The slot never takes more than the room the window leaves it: content larger than that, unless it scrolls, + /// is cut at the window's edge. Raw egui content allocates its own extent along the slot's edge; content that takes whatever room it is + /// offered (`ui.available_size()`) takes the whole room the slot can grow into. Outside a shell it resolves to + /// `size.bar.options`. Content, } diff --git a/crates/ui-shell/tests/it/shell/app_shell.rs b/crates/ui-shell/tests/it/shell/app_shell.rs index 5dd6ab6724..fa4eda93d4 100644 --- a/crates/ui-shell/tests/it/shell/app_shell.rs +++ b/crates/ui-shell/tests/it/shell/app_shell.rs @@ -202,8 +202,8 @@ fn a_slot_sized_by_its_content_grows_to_a_child_that_fills_its_height() { } /// A settled frame runs a content slot's content once, in one pass: its measure is reused while its inputs are -/// unchanged. A frame where the content grows (a denser theme makes every button taller) lays the window out again at -/// most once and shows the new extent in that frame. +/// unchanged. A frame where the content grows (a roomier density makes every button taller) lays the window out again +/// at most once, shows the new extent in that frame and leaves the next frame settled. #[trial] fn a_content_slot_runs_its_content_once_per_settled_frame_and_grows_in_one_frame() { let runs = Rc::new(Cell::new(0_u32)); @@ -230,8 +230,104 @@ fn a_content_slot_runs_its_content_once_per_settled_frame_and_grows_in_one_frame assert!(fixture.passes() <= 2, "the frame the content grows in lays the window out again at most once: {} passes", fixture.passes()); let slot = regions.borrow().as_ref().and_then(|regions| regions.slots.first().map(|(_, rect)| *rect)).expect("the slot shows"); let grown = seen.borrow().0; - assert!(grown.height() > before.height() + 1.0, "the denser theme makes the column taller: {before:?} to {grown:?}"); + assert!(grown.height() > before.height() + 1.0, "the roomier density makes the column taller: {before:?} to {grown:?}"); assert!(slot.expand(1.0).contains_rect(grown), "in the frame it grows in, the slot {slot:?} holds the grown column {grown:?}"); + runs.set(0); + fixture.frame(Vec::new()); + assert_eq!(fixture.passes(), 1, "the frame after the grow is settled: one pass"); + assert_eq!(runs.get(), 1, "the frame after the grow runs the slot's content once"); +} + +/// Content rails sit at their own sides in either reading direction, each as wide as the column it holds, and a +/// settled frame runs one pass with each rail's content once: the start rail at the reading start, the end rail at the +/// reading end, the body between them. +#[trial] +fn content_rails_sit_at_their_sides_and_settle_in_one_pass() { + const RAIL: [&str; 3] = ["Move", "Brush", "Eraser"]; + for rtl in [false, true] { + let direction = if rtl { craft_i18n::Direction::Rtl } else { craft_i18n::Direction::Ltr }; + let (start, end) = (column(), column()); + let (start_runs, end_runs) = (Rc::new(Cell::new(0_u32)), Rc::new(Cell::new(0_u32))); + let regions = Rc::new(RefCell::new(None)); + let (start_seen, end_seen, start_count, end_count, out) = + (Rc::clone(&start), Rc::clone(&end), Rc::clone(&start_runs), Rc::clone(&end_runs), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .start(Slot::new("tools").size(SlotSize::Content), |ui, _, _: &mut ()| { + start_count.set(start_count.get() + 1); + fill_column(ui, &RAIL, &start_seen); + }) + .end(Slot::new("inspector").size(SlotSize::Content), |ui, _, _: &mut ()| { + end_count.set(end_count.get() + 1); + fill_column(ui, &RAIL, &end_seen); + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.direction(direction).room(Vec2::new(600.0, 400.0)).settle(); + let regions = regions.borrow().clone().expect("the shell shows"); + const SLACK: f32 = 1.0; + let rect_of = |key| regions.slots.iter().find(|(shown, _)| *shown == key).map(|(_, rect)| *rect).expect("the rail shows"); + let (start_rail, end_rail) = (rect_of("tools"), rect_of("inspector")); + for (key, rail, seen) in [("tools", start_rail, &start), ("inspector", end_rail, &end)] { + let (column, buttons) = seen.borrow().clone(); + assert_eq!(buttons.len(), RAIL.len(), "RTL {rtl}, {key}: every button shows"); + for button in &buttons { + assert!(column.expand(SLACK).contains_rect(*button), "RTL {rtl}, {key}: the button {button:?} lies in its column {column:?}"); + } + assert!(rail.expand(SLACK).contains_rect(column), "RTL {rtl}, {key}: the rail {rail:?} holds its column {column:?}"); + } + let body = regions.body; + let (left, right) = if rtl { (end_rail, start_rail) } else { (start_rail, end_rail) }; + assert!(left.max.x <= body.min.x + SLACK, "RTL {rtl}: the rail {left:?} lies left of the body {body:?}"); + assert!(right.min.x >= body.max.x - SLACK, "RTL {rtl}: the rail {right:?} lies right of the body {body:?}"); + (start_runs.set(0), end_runs.set(0)); + fixture.frame(Vec::new()); + assert_eq!(fixture.passes(), 1, "RTL {rtl}: a settled frame runs one pass"); + assert_eq!((start_runs.get(), end_runs.get()), (1, 1), "RTL {rtl}: a settled frame runs each rail's content once"); + } +} + +/// A content slot holding a list that scrolls along its height is as tall as the list's rows, whether the list sizes +/// from its content or fills its height: the slot offers its content no bound along its edge, so the list shows all +/// of its rows instead of taking the window's height, and the body keeps the rest of the window. +#[trial] +fn a_content_slot_holding_a_scrolling_list_takes_the_list_height() { + for sizing in [Sizing::Content, Sizing::FillHeight, Sizing::Fill] { + let rows = Rc::new(RefCell::new(Vec::new())); + let regions = Rc::new(RefCell::new(None)); + let (seen, out) = (Rc::clone(&rows), Rc::clone(®ions)); + let mut fixture = Fixture::new(move |ui| { + let shown = AppShell::new(WindowKey::main()) + .top(Slot::new("findBar").size(SlotSize::Content), |ui, _, _: &mut ()| { + let mut buttons = Vec::new(); + Stack::new().sizing(sizing).scroll(Scroll::vertical()).show(ui, |ui, _| { + for label in ["First", "Second", "Third"] { + buttons.push(Button::new(label).show(ui).rect); + } + }); + *seen.borrow_mut() = buttons; + }) + .body(|_, _, _| {}) + .show(ui, &mut ()); + *out.borrow_mut() = Some(shown.regions); + }); + fixture.room(Vec2::new(600.0, 700.0)).settle(); + let regions = regions.borrow().clone().expect("the shell shows"); + let slot = regions.slots.iter().find(|(key, _)| *key == "findBar").map(|(_, rect)| *rect).expect("the slot shows"); + let rows = rows.borrow().iter().fold(Rect::NOTHING, |all, row| all.union(*row)); + const SLACK: f32 = 1.0; + // The rule toward the body, the stack's padding and rounding. + const AROUND: f32 = 24.0; + assert!(slot.expand(SLACK).contains_rect(rows), "{sizing:?}: the slot {slot:?} holds the list's rows {rows:?}"); + assert!(slot.height() <= rows.height() + AROUND, "{sizing:?}: the slot {slot:?} is as tall as the list's rows {rows:?}, not the window"); + let body = regions.body; + assert!( + body.min.y >= slot.max.y - SLACK && (body.max.y - 700.0).abs() <= SLACK, + "{sizing:?}: the body {body:?} keeps the window under the slot {slot:?}" + ); + } } /// A check box with its label after it sits on the options slot's middle, as a button beside it does: the slot is From 7547d34702128c7a71bfd36946ef5cd3471c079b Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 20:43:45 +0000 Subject: [PATCH 09/40] 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 9cda37695f..2e46f888b4 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 f86ab6e67f..ca9c882593 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 e9126f28ba..c186c28c67 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 f60372b59e..1e61f4d8fc 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 b77106fb88..b198a9369e 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 f36b91287220d5783fb23c445c2b03fb226b6c29 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 20:59:54 +0000 Subject: [PATCH 10/40] Shell trial: reset the rail run counters as two statements --- crates/ui-shell/tests/it/shell/app_shell.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/ui-shell/tests/it/shell/app_shell.rs b/crates/ui-shell/tests/it/shell/app_shell.rs index fa4eda93d4..cd4bc8a6e2 100644 --- a/crates/ui-shell/tests/it/shell/app_shell.rs +++ b/crates/ui-shell/tests/it/shell/app_shell.rs @@ -282,7 +282,8 @@ fn content_rails_sit_at_their_sides_and_settle_in_one_pass() { let (left, right) = if rtl { (end_rail, start_rail) } else { (start_rail, end_rail) }; assert!(left.max.x <= body.min.x + SLACK, "RTL {rtl}: the rail {left:?} lies left of the body {body:?}"); assert!(right.min.x >= body.max.x - SLACK, "RTL {rtl}: the rail {right:?} lies right of the body {body:?}"); - (start_runs.set(0), end_runs.set(0)); + start_runs.set(0); + end_runs.set(0); fixture.frame(Vec::new()); assert_eq!(fixture.passes(), 1, "RTL {rtl}: a settled frame runs one pass"); assert_eq!((start_runs.get(), end_runs.get()), (1, 1), "RTL {rtl}: a settled frame runs each rail's content once"); From 6e5490edc32f9812b29a21ba9e4254cdb66fa603 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 22:23:59 +0100 Subject: [PATCH 11/40] WIP: Layers panel: a hidden layer's eye box stays empty under the pointer (photocraft#16321) From 0f096d6d69f113045ec06e451a30f3efd2e1aa01 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Sat, 21 Nov 2026 16:37:10 -0500 Subject: [PATCH 12/40] Remove stale layout design-lint exceptions --- crates/ui-widgets/src/layout_components/mod.rs | 1 - design/exceptions/craft-ui-widgets/display.toml | 8 -------- 2 files changed, 9 deletions(-) diff --git a/crates/ui-widgets/src/layout_components/mod.rs b/crates/ui-widgets/src/layout_components/mod.rs index a869191b7e..a658ea805e 100644 --- a/crates/ui-widgets/src/layout_components/mod.rs +++ b/crates/ui-widgets/src/layout_components/mod.rs @@ -329,7 +329,6 @@ impl Row { /// The row's line is at least `points` high, as a child of more than one line that high would make it: the /// children that fill the line's height take at least it. A row of command groups keeps the height of its /// rows of controls while its groups are shorter. Ignored by a row that wraps. - // design: allow[props/point-size](the least line of a row is the caller's measured extent (three control rows of a look and a title line), not a chosen size) pub fn least_height(mut self, points: f32) -> Self { self.props = self.props.least_height(points); self diff --git a/design/exceptions/craft-ui-widgets/display.toml b/design/exceptions/craft-ui-widgets/display.toml index 3669a55bfe..88f56e78b1 100644 --- a/design/exceptions/craft-ui-widgets/display.toml +++ b/design/exceptions/craft-ui-widgets/display.toml @@ -1,9 +1 @@ config_version = 1 - -[[exception]] -name = "divider-length-content-extent" -kind = "marker" -rule = "props/point-size" -path = "crates/ui-widgets/src/display/divider.rs" -reason = "The length is the measured extent of the owner's content (a group as tall as its content and title), not a chosen size." -count = 1 From d9686ea983c685742578a1410c45081a9ac5d69e Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 22:49:56 +0100 Subject: [PATCH 13/40] WIP: About: set the About tab's blocks apart and centre the button and links (photocraft#16325) Co-Authored-By: Claude Opus 5.5 From 7843e29364f507689ceefc3bfb5b55dbced5ffcb Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 22:50:45 +0100 Subject: [PATCH 14/40] Layers panel: a hidden layer's eye box stays empty under the pointer (photocraft#16321) A list toggle cell drew its off icon under the pointer, so hiding a layer showed a crossed-out eye in its box until the pointer left. The reference application leaves a hidden layer's box empty in every state. ToggleCell gains `empty_off()`, which never draws the off icon, and the Layers panel's layer and sub-row eye cells use it. Co-Authored-By: Claude Opus 5.5 --- crates/layers/src/ui/panel/row.rs | 5 +-- crates/layers/tests/it/main.rs | 1 + crates/layers/tests/it/panel_eye.rs | 47 +++++++++++++++++++++++++ crates/ui-widgets/src/list/row/paint.rs | 2 +- crates/ui-widgets/src/list/toggle.rs | 31 ++++++++++++++++ 5 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 crates/layers/tests/it/panel_eye.rs diff --git a/crates/layers/src/ui/panel/row.rs b/crates/layers/src/ui/panel/row.rs index 1f45b557a6..4be0ab4ea4 100644 --- a/crates/layers/src/ui/panel/row.rs +++ b/crates/layers/src/ui/panel/row.rs @@ -249,7 +249,8 @@ fn layer_row<'r, T: LayerTree>(cx: &'r PanelContext<'r, T>, id: &T::Id) -> ListR let contents = cx.options.thumbnail_contents; let active = cx.selection.active.as_ref() == Some(id); - let mut eye = ToggleCell::eye(EYE, info.visible).name(named(&words.visibility, &info.name)); + // A hidden layer's eye box stays empty, also under the pointer (the reference application, photocraft#16321). + let mut eye = ToggleCell::eye(EYE, info.visible).empty_off().name(named(&words.visibility, &info.name)); if let Some(color) = info.label { eye = eye.fill(DataColor::new(paint_color(color.fill()))); } @@ -369,7 +370,7 @@ fn sub_row<'r, T: LayerTree>(cx: &'r PanelContext<'r, T>, id: &T::Id, group: Sub row = row.ink(RowInk::Dimmed); } if sub.eye_shown { - row = row.toggle(ToggleCell::eye(EYE, sub.on).name(named(&words.visibility, &sub.label))); + row = row.toggle(ToggleCell::eye(EYE, sub.on).empty_off().name(named(&words.visibility, &sub.label))); } let size = cx.options.thumbnail_size; let header_mask = group == SubRowGroup::SmartFilters && index.is_none() && sub.mask && size != ThumbSize::None; diff --git a/crates/layers/tests/it/main.rs b/crates/layers/tests/it/main.rs index cc236b5a08..36c2b8fa5b 100644 --- a/crates/layers/tests/it/main.rs +++ b/crates/layers/tests/it/main.rs @@ -3,6 +3,7 @@ pub(crate) mod blend_rows; pub(crate) mod comps; pub(crate) mod panel_drag_menu; +pub(crate) mod panel_eye; pub(crate) mod panel_filter; pub(crate) mod panel_input; pub(crate) mod panel_memo; diff --git a/crates/layers/tests/it/panel_eye.rs b/crates/layers/tests/it/panel_eye.rs new file mode 100644 index 0000000000..54d74cbf19 --- /dev/null +++ b/crates/layers/tests/it/panel_eye.rs @@ -0,0 +1,47 @@ +//! `LayersPanel` eye boxes: a hidden layer's box stays empty, also under the pointer (photocraft#16321). + +use craft_layers::ui::mock::FakeLayers; +use craft_layers::ui::panel::LayersPanel; +use craft_layers::ui::tree::{LayerInfo, LayerKind}; +use craft_ui::contract::Tracked; +use craft_ui::testing::{Fixture, pointer, trial}; +use egui::{Rect, Vec2}; +use std::cell::RefCell; +use std::rc::Rc; + +/// A visible layer over a hidden one. +fn rig() -> Fixture { + let mut tree = FakeLayers::default(); + tree.add(None, LayerInfo::new("Shown", LayerKind::Pixel), false); + let mut hidden = LayerInfo::new("Hidden", LayerKind::Pixel); + hidden.visible = false; + tree.add(None, hidden, false); + let tree = Rc::new(RefCell::new(Tracked::new(tree))); + let mut fixture = Fixture::new(move |ui| { + let tree = tree.borrow(); + let _ = LayersPanel::new(&tree).show(ui); + }); + fixture.room(Vec2::new(420.0, 560.0)); + fixture.settle(); + fixture +} + +/// How many shapes the frame paints wholly inside the eye box `cell`: its icon, not the row's fill around it. +fn drawn_in(fixture: &mut Fixture, cell: Rect) -> usize { + fixture.frame_shapes().iter().filter(|shape| cell.contains_rect(shape.visual_bounding_rect())).count() +} + +/// The pointer over a hidden layer's eye box draws nothing there (no crossed-out eye), while a visible layer's box +/// under the pointer draws its eye. +#[trial] +fn a_hidden_layers_eye_box_stays_empty_under_the_pointer() { + let mut fixture = rig(); + let shown = fixture.by_label("Visibility Shown").unwrap_or_else(|| panic!("no eye box for Shown")).rect; + let hidden = fixture.by_label("Visibility Hidden").unwrap_or_else(|| panic!("no eye box for Hidden")).rect; + + fixture.frame(vec![pointer::moved(shown.center())]).idle(2); + assert!(drawn_in(&mut fixture, shown) > 0, "the visible layer's eye is drawn"); + + fixture.frame(vec![pointer::moved(hidden.center())]).idle(2); + assert_eq!(drawn_in(&mut fixture, hidden), 0, "the hidden layer's box stays empty under the pointer"); +} diff --git a/crates/ui-widgets/src/list/row/paint.rs b/crates/ui-widgets/src/list/row/paint.rs index 2a1db4a3fc..fd98cf4437 100644 --- a/crates/ui-widgets/src/list/row/paint.rs +++ b/crates/ui-widgets/src/list/row/paint.rs @@ -91,7 +91,7 @@ impl ListRow<'_> { ToggleFace::Icons { on, off } => { let shown = match toggle.state { ToggleState::On | ToggleState::Mixed => Some(on), - ToggleState::Off if toggle.always_visible || cx.part(part).hovered => Some(off), + ToggleState::Off if toggle.shows_off(cx.part(part).hovered) => Some(off), ToggleState::Off => None, }; if let Some(id) = shown { diff --git a/crates/ui-widgets/src/list/toggle.rs b/crates/ui-widgets/src/list/toggle.rs index 3cfeee1490..82f8f81491 100644 --- a/crates/ui-widgets/src/list/toggle.rs +++ b/crates/ui-widgets/src/list/toggle.rs @@ -80,6 +80,9 @@ pub struct ToggleCell { pub fill: Option, /// The off icon shows in every row, not only under the pointer. No effect on a check face. pub always_visible: bool, + /// The off icon never shows, also under the pointer: an off cell stays empty (a hidden layer's eye box). Wins + /// over `always_visible`. No effect on a check face. + pub empty_off: bool, /// A screen reader announces a check box instead of a toggle button: for a setting the row carries rather than /// an action on the row. pub check_box: bool, @@ -99,6 +102,7 @@ impl ToggleCell { tooltip: None, fill: None, always_visible: false, + empty_off: false, check_box: false, row_press: false, } @@ -162,10 +166,37 @@ impl ToggleCell { self } + /// The off icon never shows, also under the pointer: an off cell stays an empty box. + #[must_use] + pub fn empty_off(mut self) -> Self { + self.empty_off = true; + self + } + /// A press on the row's own area shows on the cell, for a row whose click turns on what the cell shows. #[must_use] pub fn row_press(mut self) -> Self { self.row_press = true; self } + + /// Whether an off cell draws its off icon, under the pointer when `hovered`. + pub(super) fn shows_off(&self, hovered: bool) -> bool { + !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 f6b98be494c4d9873c13739f0d7ada6aa7a375b4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 21:50:53 +0000 Subject: [PATCH 15/40] 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 96a9f4e107..b61f9f08b2 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 8afdc685c5..c65ccbb18c 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 16/40] 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 61e2304ebd..cd382c75ee 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 e03be55cbd..82d220de40 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 2e46f888b4..701d3f3e02 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 cae3774d6b..932b2fa41c 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 ca9c882593..11403fc5d6 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 c186c28c67..f81ab751f7 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 6594e2b687..f5d4ab15dc 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 34137bf9a5..06b25e3d6e 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 28c7b09161..02d0fb37fa 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 1e61f4d8fc..5ad18430c3 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 57accbccc2..909d0f76e6 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 77090807d0..c9afb1e1d7 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 79e573ffb5..e4f26734b9 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 a76a73908d..fd345be5b7 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 cb9e7d2c41..8be00d3771 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 237c1014af..6f0f181aa1 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 a869191b7e..300c0996e3 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 d8819c9414..0ebb83cd18 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 8aec2a378b..f236204753 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 17/40] 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 b198a9369e..30256917e0 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 c1a34f7d8d3ce1faf87d585fe978483491065461 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 22:58:36 +0100 Subject: [PATCH 18/40] WIP: menu bar: Space on the focused bar leaves it and reaches the Hand (photocraft#16327) From ca3d21835d3a3f61634a42f2b2f379c0dbeaf3b6 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 23:00:28 +0100 Subject: [PATCH 19/40] WIP: Canvas scroll bars: pasteboard range and a thumb that stays under the pointer (photocraft#16328, photocraft#16329) From 0712064ab1058cb2980fc42a54ab1a9e88945834 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 23:02:38 +0100 Subject: [PATCH 20/40] Canvas scroll bars: pasteboard range, thumb stays under the pointer (photocraft#16328, photocraft#16329) With Overscroll on, the bars' range takes in the pasteboard: at either end of a track 100 screen points of the document stay in view at the opposite edge, at any zoom and for documents larger or smaller than the window, as measured in the reference application. Overscroll off is unchanged. A thumb drag keeps the range the bar had at the press and maps the pointer's movement from the press onto it, so the thumb stays under the pointer: past a track's end the view waits, and moving back moves it again in the same drag. Co-Authored-By: Claude Opus 5.5 --- crates/ui-canvas/src/canvas/scrollbars/mod.rs | 148 +++++++++++++++--- .../ui-canvas/tests/it/canvas/scrollbars.rs | 110 +++++++++++++ 2 files changed, 232 insertions(+), 26 deletions(-) diff --git a/crates/ui-canvas/src/canvas/scrollbars/mod.rs b/crates/ui-canvas/src/canvas/scrollbars/mod.rs index a4311c53b5..6b64e16245 100644 --- a/crates/ui-canvas/src/canvas/scrollbars/mod.rs +++ b/crates/ui-canvas/src/canvas/scrollbars/mod.rs @@ -3,9 +3,13 @@ //! thickness at rest and under the pointer. Document chrome uses inset thumbs, step buttons and a corner. //! The thumb is the visible fraction of //! the scrollable extent (the document, plus wherever the view has been scrolled past it); drag it to scroll, or press -//! the track to page by one screenful. With overscroll on, a document smaller than the window can also be scrolled from -//! one edge of the window to the other. With overscroll off the app clamps the view before it draws -//! ([`CanvasScrollbars::clamp`]). +//! the track to page by one screenful. With overscroll on, the extent also takes in the pasteboard around the document, +//! as in the reference application: at either end of a track [`KEPT_IN_VIEW`] points of the document stay in view at +//! the opposite edge, whether the document is larger or smaller than the window. With overscroll off the app clamps the +//! view before it draws ([`CanvasScrollbars::clamp`]). +//! +//! A thumb drag keeps the extent it began with and follows the pointer from the press: the thumb stays under the +//! pointer, also after the pointer went past a track's end and came back. //! //! The bars measure the view along the screen axes, so on a rotated view they show the extent of the unrotated //! document. @@ -44,6 +48,10 @@ const ARROW_STEP_PIXELS: f64 = 16.0; const ARROW_HOLD_DELAY: f64 = 0.4; const ARROW_HOLD_INTERVAL: f64 = 0.06; +/// With overscroll on, how much of the document stays in view, in screen points, when a thumb is at either end of its +/// track: the reference application keeps 100 screen pixels at every zoom, on both axes. +const KEPT_IN_VIEW: f64 = 100.0; + /// The popup of the tip beside a dragged vertical thumb. const TIP: &str = "tip"; @@ -76,26 +84,30 @@ struct Span { /// First and last visible coordinate. v0: f64, v1: f64, + /// [`KEPT_IN_VIEW`] in document units on this axis. + kept: f64, } impl Span { - /// The axis of a view: `size` screen points at `zoom` around `center`. - fn of(len: f64, center: f64, size: f64, zoom: f64) -> Option { + /// The axis of a view: `size` screen points at `zoom` around `center`; `kept` is [`KEPT_IN_VIEW`] in the same + /// points (the horizontal axis divides both by the pixel aspect). + fn of(len: f64, center: f64, size: f64, zoom: f64, kept: f64) -> Option { let zoom = if zoom.is_finite() && zoom > 0.0 { zoom } else { return None }; let half = size / zoom / 2.0; - let span = Span { len, v0: center - half, v1: center + half }; + let span = Span { len, v0: center - half, v1: center + half, kept: kept / zoom }; (span.len.is_finite() && span.len > 0.0 && span.v0.is_finite() && span.v1.is_finite() && span.v1 > span.v0).then_some(span) } - /// The scrollable extent: the document and the visible span. With `overscroll`, a document shorter than the span - /// may slide edge to edge within it. + /// The scrollable extent: the document and the visible span. With `overscroll` also the pasteboard on both sides, + /// up to where only [`KEPT_IN_VIEW`] of the document (all of a shorter one) is left in view at the opposite edge. fn content(&self, overscroll: bool) -> Range { let (lo, hi) = (self.v0.min(0.0), self.v1.max(self.len)); if !overscroll { return lo..hi; } - let visible = self.v1 - self.v0; - lo.min(self.len - visible)..hi.max(visible) + let kept = if self.kept.is_finite() { self.kept.clamp(0.0, self.len) } else { self.len }; + let room = (self.v1 - self.v0 - kept).max(0.0); + lo.min(-room)..hi.max(self.len + room) } fn scroll(&self, overscroll: bool) -> ScrollSpan { @@ -142,6 +154,26 @@ impl Bar { } } +/// A pressed thumb: the extent and the visible range it was pressed at. Its drag maps the pointer's movement from the +/// press onto that extent, so the track does not grow or shrink under the pointer while the view moves, and the thumb +/// stays under the pointer. +#[derive(Clone, Debug, Default, PartialEq)] +struct HeldThumb { + horizontal: bool, + content: Range, + visible: Range, +} + +impl HeldThumb { + fn of(axis: Axis, span: &ScrollSpan) -> Self { + HeldThumb { horizontal: axis == Axis::X, content: span.content.clone(), visible: span.visible.clone() } + } + + fn on(&self, axis: Axis) -> bool { + self.horizontal == (axis == Axis::X) + } +} + /// The bars of a view over a document, in the order horizontal, vertical. struct Bars { horizontal: Option, @@ -198,6 +230,11 @@ fn paint_arrow(draw: &Draw<'_>, rect: Rect, axis: Axis, after: bool, color: Styl draw.stroke(&path, StrokeWidth::Thin, color); } +/// The length of a scroll bar's track along `axis`. +fn scroll_track_length(track: Rect, axis: Axis) -> f32 { + if axis == Axis::X { track.width() } else { track.height() } +} + /// How the document's x axis runs on screen: with the view flipped, backwards. fn along_x(view: &CanvasView, width: f64, c: f64) -> f64 { if view.flip_x { width - c } else { c } @@ -208,20 +245,43 @@ fn aspect(view: &CanvasView) -> f64 { } impl Bars { - /// The bars inside `rect` (bottom and right edges), `width` thick, for `view` over the document `doc`. - fn of(view: &CanvasView, doc: DocRect, overscroll: bool, horizontal: bool, rect: Rect, style: &ScrollbarsStyle) -> Bars { + /// The bars inside `rect` (bottom and right edges), `width` thick, for `view` over the document `doc`. A `held` + /// thumb's bar keeps the extent the thumb was pressed at. + fn of( + view: &CanvasView, + doc: DocRect, + overscroll: bool, + horizontal: bool, + rect: Rect, + style: &ScrollbarsStyle, + held: Option<&HeldThumb>, + ) -> Bars { let document_chrome = style.document.is_some(); let mut width = style.look.thickness; if document_chrome { width = width.min(rect.width().max(0.0)).min(rect.height().max(0.0)); } - let x = Span::of(doc.width(), along_x(view, doc.width(), view.center.x - doc.x0), f64::from(view.rect.width()) / aspect(view), view.zoom) - .filter(|_| horizontal); - let y = Span::of(doc.height(), view.center.y - doc.y0, f64::from(view.rect.height()), view.zoom); + let x = Span::of( + doc.width(), + along_x(view, doc.width(), view.center.x - doc.x0), + f64::from(view.rect.width()) / aspect(view), + view.zoom, + KEPT_IN_VIEW / aspect(view), + ) + .filter(|_| horizontal); + let y = Span::of(doc.height(), view.center.y - doc.y0, f64::from(view.rect.height()), view.zoom, KEPT_IN_VIEW); let right = if y.is_some() { rect.right() - width } else { rect.right() }; let bottom = if x.is_some() { rect.bottom() - width } else { rect.bottom() }; let corner = (document_chrome && x.is_some() && y.is_some()).then(|| Rect::from_min_max(pos2(right, bottom), rect.max)); - let bar = |span: Option, axis, rect| span.map(|span| Bar::new(rect, axis, span.scroll(overscroll), document_chrome)); + let bar = |span: Option, axis, rect| { + span.map(|span| { + let mut scroll = span.scroll(overscroll); + if let Some(held) = held.filter(|held| held.on(axis)) { + scroll.content = held.content.start.min(scroll.visible.start)..held.content.end.max(scroll.visible.end); + } + Bar::new(rect, axis, scroll, document_chrome) + }) + }; Bars { horizontal: bar(x, Axis::X, Rect::from_min_max(pos2(rect.left(), bottom), pos2(right, rect.bottom()))), vertical: bar(y, Axis::Y, Rect::from_min_max(pos2(right, rect.top()), pos2(rect.right(), bottom))), @@ -298,13 +358,24 @@ pub struct CanvasScrollbars<'a> { /// thumb on the reading-start side. #[prop] tip: Option<&'a dyn Fn(&CanvasView) -> Label>, + /// The thumb pressed in this pass, as `update` read it from the press slot, for `paint` and `access`. + held: Option, } impl<'a> CanvasScrollbars<'a> { /// Scroll bars named `label` that edit `view`, a view over the document `document` (document units). pub fn new(label: impl Into

{ /// The grip of `unit`, whose shown panel is `active`. pub fn new(unit: DragUnit

, active: PanelKey) -> Self { - GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, double: false, started: false } + GroupGrip { common: Common::new(), unit, active, ghost: None, movable: true, ticks: false, double: false, started: false } } } @@ -92,8 +138,8 @@ impl Component for GroupGrip

{ type Style = GroupGripStyle; type Output = GroupGripOutput; - fn style(_: &StyleCx<'_>, _: GroupGripStyleKey

) -> GroupGripStyle { - GroupGripStyle { metrics: Metrics::new() } + fn style(cx: &StyleCx<'_>, _: GroupGripStyleKey

) -> GroupGripStyle { + GroupGripStyle { metrics: Metrics::new(), marks: GripMarks::style(cx) } } fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { @@ -112,6 +158,12 @@ impl Component for GroupGrip

{ } } + fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { + if self.ticks { + cx.style.marks.paint(ui, cx.rect.center()); + } + } + fn finish(self, cx: Cx<'_, Self>) -> GroupGripOutput { GroupGripOutput { response: cx.response.clone(), double_pressed: self.double, drag_started: self.started } } diff --git a/crates/ui-panels/src/docking/iconic.rs b/crates/ui-panels/src/docking/iconic.rs index 3a850af217..673f0d7400 100644 --- a/crates/ui-panels/src/docking/iconic.rs +++ b/crates/ui-panels/src/docking/iconic.rs @@ -4,6 +4,7 @@ use super::divider::{self, Divider, Drag}; use super::dock_column::{ BarRecord, CHEVRON, ColumnArrow, ColumnBar, bar_band, bar_slots, column_grip, describe_chevron, paint_chevron, register_edges, show_bar, }; +use super::group::GripMarks; use super::{DockSizes, DockSpot, DockTargets, DockWords, DragUnit, Flyout, GroupAt, PanelKey, PanelSpec, Splitter, start_icon_drag}; use crate::buttons::IconButton; use crate::contract::overlay::Anchor; @@ -16,7 +17,7 @@ use crate::menu::GroupItem; use crate::primitives::{IconSpec, TextRun}; use crate::runtime::env::Label; use crate::runtime::focus::KeyUse; -use crate::style::{ComponentStyle, Corners, GlyphRole, RuleLook, RuleWidth, StyleColor, StyleCx, SurfaceKind}; +use crate::style::{ComponentStyle, Corners, GlyphRole, StyleColor, StyleCx, SurfaceKind}; use craft_behavior::dock::{Column, DockEdge, Group}; use craft_behavior::overlay::Side; use craft_behavior::{Axis, CursorIcon, DockSide, Metrics, PartKey, PressPhase, Sense, Value}; @@ -54,12 +55,6 @@ pub struct IconicSizes { /// The column width, in rail widths, from which the cells show their panels' names: 96 points at the Compact size. const LABELS_IN_RAIL_WIDTHS: f32 = 2.4; -/// The length of a group's grip line, in icon cell heights: half a cell, 15 points at the Compact size (18 at -/// Comfortable). That holds several dots, so it reads as a handle and not as a dot, and in a rail-wide column (40 -/// points at Compact) it leaves more than a quarter of the width free on each side, so it does not read as a rule -/// between the groups. -const GRIP_LINE_IN_CELLS: f32 = 0.5; - impl IconicSizes { /// The sizes of the style context `cx`. pub fn style(cx: &StyleCx<'_>) -> Self { @@ -149,21 +144,15 @@ pub struct IconicColumnStyle { name_open: StyleColor, /// The room between an icon and its name. name_gap: f32, - /// The ink of a group's grip line. - grip: StyleColor, - /// The ink of a group's grip line while the pointer is over it or drags it. - grip_active: StyleColor, - /// The grip line's length across the group. - grip_length: f32, - /// The side of the grip line's dots, and the gap between two of them. - grip_dot: f32, + /// The marks of a group's grip. + grip: GripMarks, } /// A column collapsed to icons: the column bar over icon groups, one cell per panel. A panel without an icon shows the /// first letter of its name in a box. A column widened past `IconicSizes::labels` shows each panel's name beside its /// icon, cut with an ellipsis to the cell; a click or drag on the name acts as one on the icon. A click or Enter on an icon /// opens the flyout of its panel beside the column, switches it to that panel or closes it; one flyout is open at a -/// time. A drag of an icon starts a move of its panel, a drag of the grip line on top of a group a move of the group, a +/// time. A drag of an icon starts a move of its panel, a drag of the grip on top of a group a move of the group, a /// drag of the bar beside its button a move of the column; each starts through the drag session, and a press outside /// the flyout closes it. Escape and a press /// outside close the flyout; with `auto_collapse` the focus leaving it does too. @@ -422,12 +411,8 @@ impl Component for IconicColumn<'_, P> { name: cx.color(colors.text.normal), name_open: cx.color(colors.accent.text), name_gap: cx.tokens.space.gap.item, - // A handle that is found when looked for, as the references' faint grips: hairline dots one dot apart in - // the faint ink, the normal ink under the pointer. - grip: cx.color(colors.text.faint), - grip_active: cx.color(colors.text.normal), - grip_length: cx.tokens.size.rail.button * GRIP_LINE_IN_CELLS, - grip_dot: cx.tokens.stroke.thin, + // The references' grip: a row of upright ticks a little darker than the panel. + grip: GripMarks::style(cx), } } @@ -577,12 +562,8 @@ impl Component for IconicColumn<'_, P> { ui.face(CELL.at(at as u64), cell); } let style = &cx.style; - for (group, strip) in self.laid.as_ref().map_or(&[][..], |plan| &plan.grips[..]) { - let part = cx.part(GRIP.at(*group as u64)); - let ink = if part.hovered || part.pressed() { style.grip_active } else { style.grip }; - let half = Vec2::new(style.grip_length.min(strip.width()) / 2.0, 0.0); - let look = RuleLook { color: ink.egui(), width: RuleWidth::Points(style.grip_dot) }; - ui.draw().dotted_rule_with(&look, strip.center() - half, strip.center() + half, style.grip_dot); + for (_, strip) in self.laid.as_ref().map_or(&[][..], |plan| &plan.grips[..]) { + style.grip.paint(ui, strip.center()); } // The edge's line lies on the column's inner edge; its handle stays inside the column. A floating window's // edges are the window's. diff --git a/crates/ui-panels/src/docking/iconic/trials.rs b/crates/ui-panels/src/docking/iconic/trials.rs index 3b5519ee9e..538de5b954 100644 --- a/crates/ui-panels/src/docking/iconic/trials.rs +++ b/crates/ui-panels/src/docking/iconic/trials.rs @@ -429,3 +429,57 @@ fn icon_groups_take_the_drops_of_an_expanded_columns_groups() { assert_eq!(found[3], Some(DockSpot::group(3, DockSide::Center)), "a one-icon group keeps its middle for the join"); assert_eq!(found[4], Some(DockSpot::group(3, DockSide::Bottom)), "the foot under the icons stacks below the last group"); } + +/// The ticks of a grip strip in `shapes`: the quads of the one mesh that lies inside `strip`, and their colour. +pub(crate) fn grip_ticks(shapes: &[egui::Shape], strip: Rect) -> Option<(Vec, egui::Color32)> { + shapes.iter().find_map(|shape| { + let egui::Shape::Mesh(mesh) = shape else { return None }; + let quads: Vec = mesh.vertices.chunks(4).map(|quad| Rect::from_points(&quad.iter().map(|v| v.pos).collect::>())).collect(); + let inside = !quads.is_empty() && quads.iter().all(|quad| strip.expand(0.01).contains_rect(*quad)); + inside.then(|| (quads, mesh.vertices.first().map_or(egui::Color32::TRANSPARENT, |v| v.color))) + }) +} + +/// Checks the ticks of a grip strip: ten upright marks, one point wide, four tall, one point apart, centred on the +/// strip and darker than the panel `panel`. +pub(crate) fn assert_grip_ticks(ticks: &[Rect], ink: egui::Color32, strip: Rect, panel: craft_theme::Rgba, what: &str) { + assert_eq!(ticks.len(), 10, "{what}: ten ticks: {ticks:?}"); + for tick in ticks { + assert!((tick.width() - 1.0).abs() < 0.01 && (tick.height() - 4.0).abs() < 0.01, "{what}: a tick is 1 x 4 points: {tick:?}"); + } + assert!(ticks.windows(2).all(|w| (w[1].min.x - w[0].max.x - 1.0).abs() < 0.01), "{what}: one point apart: {ticks:?}"); + let run = ticks.iter().fold(Rect::NOTHING, |run, tick| run.union(*tick)); + assert!((run.center().x - strip.center().x).abs() <= 0.5, "{what}: centred across the strip: {run:?} in {strip:?}"); + assert!((run.center().y - strip.center().y).abs() <= 0.5, "{what}: centred in the strip's height: {run:?} in {strip:?}"); + let [r, g, b, _] = panel.0; + assert!(ink.r() < r && ink.g() < g && ink.b() < b && ink.r() >= r / 2, "{what}: the ticks are a little darker than the panel {panel:?}: {ink:?}"); +} + +/// The grip above each icon group is the references' row of upright ticks, not a line: ten separate marks a little +/// darker than the panel, the same under the pointer. +#[trial] +fn a_groups_grip_is_a_row_of_upright_ticks_darker_than_the_panel() { + let mut fixture = + Fixture::hosted(|ui| { + let mut column = Column::new(vec![Group::new(vec![1, 2], 0), Group::new(vec![3], 0)]); + column.iconic = true; + let place = Rect::from_min_size(Pos2::ZERO, Vec2::new(RAIL, SCREEN.y)); + let output = IconicColumn::new("Panels", global("iconic column", "ticks"), &column, Bind::kept(), &named) + .within(screen()) + .show_flyouts_at(ui, place, |_, _, _, _| None); + Some(output.into()) + }); + fixture.room(SCREEN).settle(); + let id = fixture.root_id().expect("the column shows"); + let panel = StyleCx::with_root(fixture.ctx(), |cx| cx.tokens.color.surface.panel); + for group in [0, 1] { + let strip = fixture.part_rect(id, GRIP.at(group)).expect("each group has its grip"); + let shapes = fixture.frame_shapes(); + let (ticks, ink) = grip_ticks(&shapes, strip).expect("the grip paints its ticks"); + assert_grip_ticks(&ticks, ink, strip, panel, &format!("group {group}")); + fixture.frame(vec![egui::Event::PointerMoved(strip.center())]); + let hovered = fixture.frame_shapes(); + let (_, hover_ink) = grip_ticks(&hovered, strip).expect("the grip paints its ticks under the pointer"); + assert_eq!(hover_ink, ink, "group {group}: the ticks keep their ink under the pointer"); + } +} diff --git a/crates/ui-panels/src/docking/targets.rs b/crates/ui-panels/src/docking/targets.rs index ab44830f87..3c20611ee5 100644 --- a/crates/ui-panels/src/docking/targets.rs +++ b/crates/ui-panels/src/docking/targets.rs @@ -80,6 +80,10 @@ pub struct DockSizes { pub rail_first: f32, /// The width each further column of a tool rail adds: a rail button and the tight gap before it. pub rail_step: f32, + /// The height of a grip strip, the band with the dock's grip marks: above each icon group of a collapsed column, + /// and under the column bar of a tool rail (a group whose panel has a [`DockGrid`](super::DockGrid)) that the host + /// shows itself (the least hit size). + pub grip: f32, } impl DockSizes { @@ -124,6 +128,7 @@ impl DockSizes { column: size.dock.column, rail_first: size.rail.button + 2.0 * cx.tokens.space.pad.control, rail_step: size.rail.button + cx.tokens.space.gap.tight, + grip: size.hit.target, } } diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 954fc901f1..4abd26459d 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -5,16 +5,17 @@ use super::hide::{self, PruneKey}; use crate::contract::Revision; use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ - Bind, BindMut, BodyCx, Cx, Entry, MemoKey, NoValue, Outcome, Pad, Pointer as _, Props as _, ShowContainer as _, Sizing, Tracked, WordSetCx as _, + Bind, BindMut, BodyCx, Cx, Entry, MemoKey, NoValue, Outcome, Pad, Pointer as _, Props as _, Show as _, ShowContainer as _, Sizing, Tracked, + WordSetCx as _, }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; use crate::docking::{Arrangement, close_requests, cross_window, end_replaced_drags, float_drop, native, open_requests}; use crate::docking::{ ColumnArrow, ColumnBar, DockColumn, DockCommands, DockConfig, DockDropTarget, DockDropped, DockEvent, DockGroup, DockPanels, DockRoot, DockScene, - DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, HidePanels, - IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, Titles, WindowColumn, actions, - column_cells, dock_states, frame, move_actions, with_area_rules, + DockSizes, DockSpot, DockTargets, DockTo, DockWords, DragUnit, FloatSpace, FloatingGroup, FlyoutResize, GroupAt, GroupDrag, GroupGrip, + HidePanels, IconicColumn, IconicSizes, PanelDrag, PanelKey, PanelSpec, PanelSpecs, PanelTitle, Placing, SpecSource, SplitArea, Titles, + WindowColumn, actions, column_cells, dock_states, frame, move_actions, with_area_rules, }; use crate::menu::{GroupItem, MenuWords, PanelMenu, PanelRow}; use crate::runtime::commands::{CommandRef, CommandSet as _, CommandState, Commands as _, focus_within}; @@ -915,16 +916,35 @@ impl Pass<'_, P> { } } + /// The grip strip on top of a tool rail the host shows itself: the dock's grip marks over a band that drags the + /// group, which floats at `size`, the group's size. + fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) { + let scene = self.scene; + let label = Label::from(scene.spec(shown).label.as_str().to_owned()); + let held = GroupGrip::new(DragUnit::Group(anchor.clone()), PanelKey::of(shown)) + .ticks(true) + .movable(scene.permissions(shown).movable) + .ghost(label.clone()) + .label(label) + .show_at(ui, strip); + if held.drag_started { + drag::amend::>(ui.ctx(), |drag| drag.source = Some(size)); + } + } + /// One group, by the host's `group_view` when it takes the group, else as a `DockGroup` over the host's panels: /// shown in a rect, or measured at a width the way it would show, returning its height. fn group(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>, members: &[P], active: usize, look: Look, at: GroupAt) -> Option { let scene = self.scene; let anchor = members.first()?; let active = active.min(members.len() - 1); + // A tool rail (a panel with a grid) that the host shows itself gets the dock's grip strip on top, under its + // column bar, as the references' toolbar: the host's view takes the room under it. + let grip = if members.get(active).is_some_and(|panel| scene.spec(panel).grid.is_some()) { scene.sizes.grip } else { 0.0 }; if let GroupAt::Measure(_) = at && let Some(height) = self.panels.group_view(members, active, ui, at, body) { - return Some(height); + return Some(height + grip); } let shown = &members[active]; let words = body.words::(); @@ -994,12 +1014,13 @@ impl Pass<'_, P> { // the group's room, never in the room the area has left. Where the host leaves the group to the dock, the // group shows in its place. Both run every pass; the host memoizes inside its view, the group inside its // header and its bodies. + let (strip, view) = if grip > 0.0 { rect.split_top_bottom_at_y(rect.top() + grip.min(rect.height())) } else { (Rect::NOTHING, rect) }; let output = ui .scope_builder(UiBuilder::new().max_rect(rect), |ui| { let taken = ui - .scope_builder(UiBuilder::new().max_rect(rect), |ui| { - ui.shrink_clip_rect(rect); - panels.borrow_mut().group_view(members, active, ui, at, body) + .scope_builder(UiBuilder::new().max_rect(view), |ui| { + ui.shrink_clip_rect(view); + panels.borrow_mut().group_view(members, active, ui, GroupAt::Show(view), body) }) .inner; match taken { @@ -1008,8 +1029,13 @@ impl Pass<'_, P> { } }) .inner; - // A host view took the group. - let output = output?; + // A host view took the group: a rail's grip drags the group, as the band of a group's header does. + let Some(output) = output else { + if strip.is_positive() { + self.rail_grip(ui, anchor, shown, strip, rect.size()); + } + return None; + }; // The size `panel` floats at out of this group: the group's width, and the height the group measures at with // `panel` shown in a floating window's room, so content that fills the body takes that room. let fitted = |ui: &Ui, panel: &P| { diff --git a/crates/ui-patterns/tests/it/docking/group_view.rs b/crates/ui-patterns/tests/it/docking/group_view.rs index 62d980cc5e..616e18b577 100644 --- a/crates/ui-patterns/tests/it/docking/group_view.rs +++ b/crates/ui-patterns/tests/it/docking/group_view.rs @@ -1,13 +1,15 @@ -//! A group the host takes with `group_view` lays out in the group's rect, not in the room the dock area has left. +//! A group the host takes with `group_view` lays out in the group's rect, not in the room the dock area has left; a +//! tool rail the host takes has the dock's grip strip on top. use craft_behavior::Axis; -use craft_behavior::dock::{Layout, Node, SplitSize, Workspace}; +use craft_behavior::dock::{Column, DockEdge, Group, Layout, Node, SplitSize, Workspace}; use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; -use craft_ui::docking::{DockConfig, DockPanels, GroupAt, PanelSpec, PanelSpecs}; +use craft_ui::docking::{DockConfig, DockGrid, DockPanels, DockSizes, DragUnit, GroupAt, GroupDrag, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; +use craft_ui::runtime::drag; use craft_ui::testing::{Fixture, trial}; -use egui::{Rect, Ui, Vec2}; -use std::cell::Cell; +use egui::{Rect, Shape, Ui, Vec2}; +use std::cell::{Cell, RefCell}; use std::rc::Rc; use std::sync::Arc; @@ -59,3 +61,86 @@ fn a_group_view_lays_out_and_clips_to_its_group_rect() { assert!(rect.contains_rect(room), "the view's room {room:?} lies in its group's rect {rect:?}"); assert!(rect.contains_rect(clip), "the view's clip {clip:?} lies in its group's rect {rect:?}"); } + +/// The tool rail of the grip trial: a panel with a rail grid, which the host shows itself. +const RAIL: usize = 7; +/// The height the host's rail measures at. +const RAIL_HEIGHT: f32 = 200.0; + +/// The rail is a tool rail; the rest are plain panels. +#[derive(PlainData)] +struct RailSpecs; + +impl PanelSpecs for RailSpecs { + fn spec(&self, panel: &usize) -> PanelSpec { + let spec = PanelSpec::new(format!("Panel {panel}")); + if *panel == RAIL { spec.grid(DockGrid::rail(4)) } else { spec } + } +} + +/// The host shows the rail itself and records the rect it was given. +struct RailPanels { + seen: Rc>>, +} + +impl DockPanels for RailPanels { + fn body(&mut self, _: &usize, _: &mut Ui, _: &mut BodyCx<'_>) {} + + fn group_view(&mut self, panels: &[usize], _: usize, _: &mut Ui, at: GroupAt, _: &mut BodyCx<'_>) -> Option { + if !panels.contains(&RAIL) { + return None; + } + match at { + GroupAt::Measure(_) => Some(RAIL_HEIGHT), + GroupAt::Show(rect) => { + self.seen.set(Some(rect)); + Some(rect.height()) + } + } + } +} + +/// A tool rail the host shows itself has the dock's grip under its column bar, as the references' toolbar: a strip of +/// ten upright ticks, a little darker than the panel, above the host's view, which keeps the height it measured at; a +/// drag on the strip moves the rail's group. +#[trial] +fn a_tool_rail_shown_by_its_host_has_a_grip_strip_that_drags_it() { + let seen = Rc::new(Cell::new(None)); + let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![RAIL], 0)]).with_steps(1)]); + let root = Node::split(Axis::X, SplitSize::FixedFirst(120.0), dock, Node::tabs(vec![1], 0)); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let (mut panels, specs) = (RailPanels { seen: seen.clone() }, Tracked::new(RailSpecs)); + let columns: Rc>> = Rc::default(); + let placed = Rc::clone(&columns); + let mut fixture = Fixture::new(move |ui| { + let out = DockArea::new("Rail dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + *placed.borrow_mut() = out.columns; + }); + fixture.room(Vec2::new(800.0, 600.0)).settle(); + let sizes = DockSizes::of(fixture.ctx()); + let view = seen.get().expect("the host showed the rail"); + let column = columns.borrow().iter().find(|(panel, _)| *panel == RAIL).map(|(_, rect)| *rect).expect("the rail's column shows"); + let strip = Rect::from_min_max(egui::pos2(view.left(), view.top() - sizes.grip), egui::pos2(view.right(), view.top())); + assert!(sizes.grip > 0.0 && column.top() < strip.top(), "the strip lies under the column bar: {strip:?} in {column:?}"); + assert!((view.height() - RAIL_HEIGHT).abs() < 0.5, "the host's view keeps the height it measured at: {view:?}"); + + // The strip's ticks: one mesh inside it of ten upright marks. + let shapes = fixture.frame_shapes(); + let ticks: Vec = shapes + .iter() + .find_map(|shape| { + let Shape::Mesh(mesh) = shape else { return None }; + let quads: Vec = mesh.vertices.chunks(4).map(|quad| Rect::from_points(&quad.iter().map(|v| v.pos).collect::>())).collect(); + (!quads.is_empty() && quads.iter().all(|quad| strip.expand(0.01).contains_rect(*quad))).then_some(quads) + }) + .expect("the strip paints its ticks"); + assert_eq!(ticks.len(), 10, "ten ticks: {ticks:?}"); + assert!(ticks.iter().all(|tick| tick.height() > tick.width()), "the ticks stand upright: {ticks:?}"); + let run = ticks.iter().fold(Rect::NOTHING, |run, tick| run.union(*tick)); + assert!((run.center().x - strip.center().x).abs() <= 0.5, "the ticks are centred across the rail: {run:?} in {strip:?}"); + + fixture.drag_hold_at(strip.center(), Vec2::new(200.0, 0.0)); + let unit = drag::active::>(fixture.ctx()).map(|drag| drag.unit.clone()); + assert_eq!(unit, Some(DragUnit::Group(RAIL)), "a drag on the grip moves the rail's group"); + fixture.release_at(strip.center() + Vec2::new(200.0, 0.0)).settle(); +} diff --git a/docs/contract-api.md b/docs/contract-api.md index 70e62b5117..49b52c58c0 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -2910,7 +2910,9 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `pub fn scroll_bar(&self, look: &crate::style::ScrollBarLook, track: Rect, axis: craft_behavior::Axis, rtl: bool, span: &craft_behavior::ScrollSpan, state: &crate::style::StateSet,)`. Paints the scroll bar in `track` along `axis` for `span`, in the bar's `state` (`ScrollBar::shapes`; - `pub fn rule_width(&self, kind: RuleKind) -> f32`. The width in points of the line `rule` paints for `kind`. - `pub fn rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2)`. Paints the line `look` from `from` to `to`, snapped to physical pixels as `rule` is: a rule in a component's own - - `pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32)`. Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a grip's dotted line. + - `pub fn dotted_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32)`. Paints the line `look` from `from` to `to` as dots `gap` points apart (`Rule::dotted`): a dotted line. + - `pub fn ticked_rule_with(&self, look: &crate::style::RuleLook, from: Pos2, to: Pos2, gap: f32, across: f32)`. Paints the line `look` from `from` to `to` as ticks `across` points long, `gap` points apart (`Rule::ticks`): + - `pub fn grip_ticks(&self, look: &crate::style::RuleLook, centre: Pos2, count: u16, gap: f32, across: f32)`. Paints `count` upright ticks of `look` centred on `centre`, side by side on a level line, `gap` points apart and - `pub fn surface(&self, rect: Rect, kind: SurfaceKind, corners: Corners)`. Paints a surface of `kind` (tracks, plot wells). - `pub fn surface_styled(&self, rect: Rect, style: &SurfaceStyle)`. Paints a surface of an already resolved `style` (a kind's look with one field changed, as a knob's round radius). - `pub fn surface_look(&self, rect: Rect, look: &crate::style::SurfaceLook, state: &crate::style::StateSet)`. Paints `look` over `rect` in `state`, as the paint step paints a component's surface: a part's own surface (an @@ -3050,6 +3052,7 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`. - `craft_ui::primitives::Rule`: `pub struct Rule`. The rule painter. - `pub fn shapes(look: &RuleLook, from: Pos2, to: Pos2, pixels_per_point: f32) -> Vec`. The line from `from` to `to`, snapped across its direction: a line whose physical width is odd sits on a - `pub fn dotted(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, pixels_per_point: f32) -> Vec`. The dotted form of the line from `from` to `to`: square dots as wide as the line, `gap` points apart, the run + - `pub fn ticks(look: &RuleLook, from: Pos2, to: Pos2, gap: f32, across: f32, pixels_per_point: f32) -> Vec`. The line from `from` to `to` as a run of ticks: marks as wide as the line along it and `across` points long - `pub fn edge(look: &RuleLook, rect: Rect, side: RectSide, pixels_per_point: f32) -> Vec`. The line along the `side` edge of `rect`, on the physical pixels just inside it: a row's bottom rule or a - `craft_ui::primitives::RuleKind`: `pub enum RuleKind { Divider, Edge, Grid, DropMark }`. Which rule a look is for. - `craft_ui::primitives::RulerFace`: `pub enum RulerFace { Edge, Centred }`. How a ruler lays out its marks and numbers. A ruler takes a face from its `face` prop, else from the scope's From 06238616d482b566aa1956303d36fa9a8b7fe3ff Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 23:44:58 +0100 Subject: [PATCH 26/40] Dialogs: a layer's body leaves its footer room when it fills (photocraft#16326) A layer's measuring run lays its body out before the footer runs, so a body that fills the layer's room (a scrolling list, About's Contributors grab bag) took the footer's height too. The layer came out taller than its room by the footer, with empty space under the buttons, and in a small window it ran past the window's bottom edge. When what a layer with a footer took is taller than its room, the run is now taken back and the body laid out again beside the footer that run measured, as a capped inline body already is. Co-Authored-By: Claude Opus 5.5 --- crates/ui-contract/src/contract/body/hooks.rs | 21 +++++++++++ .../ui-panels/tests/it/body/footer_reserve.rs | 29 ++++++++++++++- .../tests/it/form_dialogs/about.rs | 36 +++++++++++++++++++ 3 files changed, 85 insertions(+), 1 deletion(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index bf9e23c47b..61385d00cc 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -329,6 +329,7 @@ impl ShapeHooks for BodyHooks<'_> { // is laid out as given the room, at the footer and header this run measured, so the children that fill share // it; its record of the content height lets later runs of the pass and kept transcripts lay it out the same. None if self.capped(&self.props, at.env, at.at) => self.measure_capped(comp, at, cx, plan), + None if self.footed_layer() => self.measure_footed_layer(comp, at, cx, plan), None => self.measure_run(comp, at, cx, plan.key, None), }; self.measured_took(took, pad, vertical) @@ -1924,6 +1925,26 @@ impl BodyHooks<'_> { } } + /// Whether the container is a layer with a footer: its body is laid out before the footer runs, so a body that + /// fills the layer's room takes the footer's height too, unless the run knows the footer from an earlier one. + fn footed_layer(&self) -> bool { + overlay_of(&self.props).is_some() && self.props.footer.is_some() && self.room.y.is_finite() + } + + /// The measuring run of a layer with a footer (photocraft#16326): while what the regions took fits the room it + /// stands; taller (a body that fills, such as a scrolling list, took the room the footer needs), the run is taken + /// back and the body is laid out again beside the footer this run measured, so the layer keeps to its room with + /// the footer as its last row. + fn measure_footed_layer(&mut self, comp: &mut C, at: &Measuring<'_, '_>, cx: &mut Cx<'_, C>, plan: MeasurePlan) -> Vec2 { + let fits = self.room.y + plan.tolerance; + let (took, kept) = crate::contract::draft(&plan.ctx, || self.measure_run(comp, at, cx, plan.key.clone(), None), |took| took.y <= fits); + if kept { + return took; + } + self.measured_footer = self.footer_size.unwrap_or(Vec2::ZERO); + self.measure_run(comp, at, cx, plan.key, None) + } + /// The extent a measuring run reports from what its regions `took`. fn measured_took(&mut self, took: Vec2, pad: Vec2, vertical: bool) -> Vec2 { // A layer hung from an opener or a rect is at least as wide as its overlay asks for, in the measuring run too, diff --git a/crates/ui-panels/tests/it/body/footer_reserve.rs b/crates/ui-panels/tests/it/body/footer_reserve.rs index 66006f2834..88816c9a9b 100644 --- a/crates/ui-panels/tests/it/body/footer_reserve.rs +++ b/crates/ui-panels/tests/it/body/footer_reserve.rs @@ -2,8 +2,10 @@ use craft_behavior::{DisplayOrder, ItemSource}; use craft_ui::contract::{Bind, ShowCollection as _, ShowContainer as _}; +use craft_ui::contract::{Scroll, Show as _}; use craft_ui::dialog::Dialog; -use craft_ui::layout_components::Row; +use craft_ui::display::Text; +use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::{List, ListRow}; use craft_ui::sections::{DialogRole, FooterButton}; use craft_ui::testing::{Fixture, trial}; @@ -53,3 +55,28 @@ fn a_dialog_with_a_filling_body_keeps_its_footer_below_the_body_and_inside_the_s assert!(craft_ui::testing::relations::above(body, button.rect), "{label} is below the body: {:?} under {body:?}", button.rect); } } + +/// photocraft#16326: a dialog whose body holds a scrolling stack that fills, under a line of other content, keeps to +/// its share of the screen with the footer as its last row: the body leaves the footer its height instead of taking +/// the whole room and pushing the footer past it. +#[trial] +fn a_dialog_with_a_filling_scroll_body_keeps_to_its_room_with_the_footer_last() { + let mut fixture = Fixture::new(move |ui| { + let mut open = true; + Dialog::new("Pick").opened(Bind::bound(&mut open)).buttons([FooterButton::new("OK", DialogRole::Accept)]).show(ui, |ui, _| { + Text::new("Pick a row").show(ui); + Stack::new().scroll(Scroll::vertical()).fill().show(ui, |ui, _| { + for at in 0..ROWS { + Text::new(format!("Row {at}")).show(ui); + } + }); + }); + }); + fixture.room(egui::Vec2::new(1200.0, 700.0)).settle(); + let screen = fixture.ctx().content_rect(); + let dialog = fixture.by_role(craft_ui::contract::Role::DIALOG).first().expect("the dialog shows").rect; + let ok = fixture.by_label("OK").expect("the footer's OK").rect; + assert!(screen.contains_rect(dialog), "the dialog is inside the screen: {dialog:?} in {screen:?}"); + assert!(dialog.height() <= 0.9 * screen.height() + 1.0, "the dialog keeps to its share of the screen: {dialog:?} in {screen:?}"); + assert!(dialog.bottom() - ok.bottom() < 20.0, "OK is the dialog's last row: {ok:?} in {dialog:?}"); +} diff --git a/crates/ui-patterns/tests/it/form_dialogs/about.rs b/crates/ui-patterns/tests/it/form_dialogs/about.rs index 18a8d39283..464999d56e 100644 --- a/crates/ui-patterns/tests/it/form_dialogs/about.rs +++ b/crates/ui-patterns/tests/it/form_dialogs/about.rs @@ -255,3 +255,39 @@ fn names_sort_without_at_and_case_and_undated_contributors_sort_last_both_ways() sort_by(&mut fixture, "Name"); assert_eq!(rows(&fixture, &["@zed", "Ann", "@alice", "@carol"]), ["@alice", "Ann", "@carol", "@zed"], "a display name sorts among the usernames"); } + +/// A crowd of contributors whose grab bag is taller than a small window. +static CROWD: LazyLock = LazyLock::new(|| { + let people: Vec = (0..400).map(|at| Contributor::new(format!("contributor-number-{at}")).counts(1, 1)).collect(); + Credits::new(people, Vec::new(), 400) +}); + +/// photocraft#16326: in a small window the Contributors tab, whose grab bag fills the room it is offered, keeps the +/// About dialog inside the window, and back on About the dialog stands centred again, as it opened. +#[trial] +fn about_stays_inside_a_small_window_on_contributors_and_comes_back_to_the_middle() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let shown = Rc::clone(&host); + let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui)); + fixture.room(Vec2::new(1200.0, 700.0)); + let id = host.borrow_mut().open(HostedAbout::new(AboutInfo::new("PhotoCraft", "An image editor.", "1.0"), CROWD.clone())); + fixture.settle(); + let screen = fixture.ctx().content_rect(); + let dialog = |fixture: &Fixture| fixture.by_role(Role::DIALOG).first().expect("the dialog shows").rect; + let opened = dialog(&fixture); + assert!((opened.center().y - screen.center().y).abs() < 1.0, "About opens centred: {opened:?} in {screen:?}"); + + let ctx = fixture.ctx().clone(); + host.borrow_mut().set_json_field(&ctx, id, "tab", json!("contributors")).expect("`tab` takes Contributors"); + fixture.settle(); + let tall = dialog(&fixture); + assert!(screen.contains_rect(tall), "Contributors keeps the dialog inside the window: {tall:?} in {screen:?}"); + let ok = fixture.by_label("OK").expect("the footer's OK").rect; + assert!(tall.bottom() - ok.bottom() < 20.0, "OK is the dialog's last row: {ok:?} in {tall:?}"); + assert!(tall.height() <= 0.9 * screen.height() + 1.0, "the dialog keeps to its share of the window: {tall:?} in {screen:?}"); + + host.borrow_mut().set_json_field(&ctx, id, "tab", json!("about")).expect("`tab` takes About"); + fixture.settle(); + let back = dialog(&fixture); + assert!((back.center().y - screen.center().y).abs() < 1.0, "back on About the dialog is centred again: {back:?} in {screen:?}"); +} From 017ecd683f51d9467977830c5917be881e3a7c3e Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 22:46:06 +0000 Subject: [PATCH 27/40] 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 b61f9f08b2..d941f298f2 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 c65ccbb18c..44b4079a65 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 acd621c1e8..3890d79811 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 28/40] 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 cd382c75ee..708bee7dc1 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 701d3f3e02..595e3a2179 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 932b2fa41c..d3b3dd9724 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 4d1fc6b8bf..efb5f8c605 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 11403fc5d6..81aaf4a0fd 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 f81ab751f7..41ca65e0ce 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 909d0f76e6..419419b6c2 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 e9c7866fbf..66e1cbf418 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 9831d7b7e8..19aef6e356 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 71d3bea9ad..e5cff8766e 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 7a432c2b6f..300e08ea4c 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 fd345be5b7..9c1cd92efc 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 8be00d3771..ab64df1e35 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 6f0f181aa1..85eb040a6a 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 300c0996e3..d75c71c8bc 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 1bfc5dd497..c7dc26bf55 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 29/40] 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 30256917e0..e210f33310 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 30/40] 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 3c9e689c80..d87e26971e 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 2749cb5229ad29a17748455fa0c30b004d1a7dc4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 00:24:21 +0100 Subject: [PATCH 31/40] Docking: no doc link from the public grip option to the private marks style (photocraft#16332) Co-Authored-By: Claude Opus 5.5 --- crates/ui-panels/src/docking/group.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/ui-panels/src/docking/group.rs b/crates/ui-panels/src/docking/group.rs index 6de32b7903..be2673f53d 100644 --- a/crates/ui-panels/src/docking/group.rs +++ b/crates/ui-panels/src/docking/group.rs @@ -116,7 +116,7 @@ pub struct GroupGrip { /// A drag on the grip drags the unit. #[prop] movable: bool, - /// The grip shows the dock's row of grip marks ([`GripMarks`]) in its middle; else it is an unmarked band. + /// The grip shows the dock's row of grip marks in its middle; else it is an unmarked band. #[prop] ticks: bool, double: bool, From 8ef85cc4a80eeff5f8df0973c354b1179c6e02ef Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 00:07:47 +0000 Subject: [PATCH 32/40] 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 85eb040a6a..5bdc7e57d4 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 c7dc26bf55..1bfc5dd497 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 058df7d51a92e366f0cd291f30cce92efc0e6ad4 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sun, 22 Nov 2026 02:20:51 +0100 Subject: [PATCH 33/40] Docking: a tool rail's grip strip is a memoized view (photocraft#16333) The grip strip under a host-shown rail's column bar (#2934) ran its GroupGrip in every pass, also when the only input was the pointer moving elsewhere, where the column bars and tab rows replay. It is now a MemoView held to the strip, keyed by the rail's group, with the drag's start leaving through an outbox; the group's size goes on the drag outside the view as the column bar does it. Co-Authored-By: Claude Opus 5.5 --- crates/ui-patterns/src/patterns/dock/area.rs | 55 +++++++++++++++---- .../tests/it/docking/group_view.rs | 23 +++++++- 2 files changed, 67 insertions(+), 11 deletions(-) diff --git a/crates/ui-patterns/src/patterns/dock/area.rs b/crates/ui-patterns/src/patterns/dock/area.rs index 4abd26459d..e8f460b834 100644 --- a/crates/ui-patterns/src/patterns/dock/area.rs +++ b/crates/ui-patterns/src/patterns/dock/area.rs @@ -5,8 +5,8 @@ use super::hide::{self, PruneKey}; use crate::contract::Revision; use crate::contract::overlay::{PlacementChange, PlacementKind}; use crate::contract::{ - Bind, BindMut, BodyCx, Cx, Entry, MemoKey, NoValue, Outcome, Pad, Pointer as _, Props as _, Show as _, ShowContainer as _, Sizing, Tracked, - WordSetCx as _, + Bind, BindMut, BodyCx, Cx, Entry, MemoKey, MemoProps, MemoView, NoValue, Outbox, Outcome, Pad, Pointer as _, Props as _, Show as _, + ShowContainer as _, Sizing, Tracked, WordSetCx as _, }; use crate::docking::SplitFramesCx as _; use crate::docking::stack::{StackSection, StackSections, section_heights}; @@ -917,17 +917,25 @@ impl Pass<'_, P> { } /// The grip strip on top of a tool rail the host shows itself: the dock's grip marks over a band that drags the - /// group, which floats at `size`, the group's size. + /// group, which floats at `size`, the group's size. A memoized view ([`rail_grip`]) held to the strip, so a frame + /// whose input is elsewhere replays it, as the column bars and the groups' tab rows replay. fn rail_grip(&mut self, ui: &mut Ui, anchor: &P, shown: &P, strip: Rect, size: Vec2) { let scene = self.scene; let label = Label::from(scene.spec(shown).label.as_str().to_owned()); - let held = GroupGrip::new(DragUnit::Group(anchor.clone()), PanelKey::of(shown)) - .ticks(true) - .movable(scene.permissions(shown).movable) - .ghost(label.clone()) - .label(label) - .show_at(ui, strip); - if held.drag_started { + let mut sent = Vec::new(); + ui.scope_builder(UiBuilder::new().max_rect(strip), |ui| { + let props = RailGrip { + unit: DragUnit::Group(anchor.clone()), + active: PanelKey::of(shown), + movable: scene.permissions(shown).movable, + label, + sent: Outbox::new(&mut sent), + }; + // Keyed by the rail's group: unique among the rails a dock area shows. + let _ = MemoView::new(("rail grip", PanelKey::of(anchor)), props, rail_grip::

).show(ui); + }); + // The group's size goes on the drag here, outside the view, whose measuring runs see no size. + if !sent.is_empty() { drag::amend::>(ui.ctx(), |drag| drag.source = Some(size)); } } @@ -1560,3 +1568,30 @@ fn window_edit( fn panel_body<'p, P: Hash>(panels: &RefCell<&mut (dyn DockPanels

+ 'p)>, panel: &P, ui: &mut Ui, body: &mut BodyCx<'_>) { panels.borrow_mut().body(panel, ui, body); } + +/// The props of a tool rail's grip strip: the group it drags, its name, and the outbox the drag's start goes to. +#[derive(MemoProps)] +struct RailGrip<'a, P> { + #[memo_props(hash = "a dock's panels are plain values it keys by their hash")] + unit: DragUnit

, + active: PanelKey, + movable: bool, + label: Label, + sent: Outbox<'a, ()>, +} + +/// A tool rail's grip strip: the dock's grip marks over the view's room, which a drag moves the rail's group by. +fn rail_grip(props: &mut RailGrip<'_, P>, ui: &mut Ui) { + let strip = ui.max_rect(); + let held = GroupGrip::new(props.unit.clone(), props.active) + .ticks(true) + .movable(props.movable) + .ghost(props.label.clone()) + .label(props.label.clone()) + .show_at(ui, strip); + if held.drag_started { + props.sent.send(()); + } + // The grip takes no room in flow; the run covers the strip, so the pointer over it runs it again. + ui.expand_to_include_rect(strip); +} diff --git a/crates/ui-patterns/tests/it/docking/group_view.rs b/crates/ui-patterns/tests/it/docking/group_view.rs index 616e18b577..048a81508f 100644 --- a/crates/ui-patterns/tests/it/docking/group_view.rs +++ b/crates/ui-patterns/tests/it/docking/group_view.rs @@ -7,7 +7,7 @@ use craft_ui::contract::{Bind, BodyCx, PlainData, Tracked}; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, DockSizes, DragUnit, GroupAt, GroupDrag, PanelSpec, PanelSpecs}; use craft_ui::patterns::dock::DockArea; use craft_ui::runtime::drag; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::{Fixture, last_pass_runs, pointer, trial}; use egui::{Rect, Shape, Ui, Vec2}; use std::cell::{Cell, RefCell}; use std::rc::Rc; @@ -144,3 +144,24 @@ fn a_tool_rail_shown_by_its_host_has_a_grip_strip_that_drags_it() { assert_eq!(unit, Some(DragUnit::Group(RAIL)), "a drag on the grip moves the rail's group"); fixture.release_at(strip.center() + Vec2::new(200.0, 0.0)).settle(); } + +/// The rail's grip strip is a memoized view: a pointer moving elsewhere in the window replays it, as it replays the +/// column bars and the tab rows, and runs no grip (photocraft#16333). +#[trial] +fn a_tool_rails_grip_strip_replays_while_the_pointer_moves_elsewhere() { + let seen = Rc::new(Cell::new(None)); + let dock = Node::dock(DockEdge::Start, vec![Column::new(vec![Group::new(vec![RAIL], 0)]).with_steps(1)]); + let root = Node::split(Axis::X, SplitSize::FixedFirst(120.0), dock, Node::tabs(vec![1], 0)); + let mut workspace = Arc::new(Workspace::new(Layout::new(Some(root), Vec::new()))); + let (mut panels, specs) = (RailPanels { seen: seen.clone() }, Tracked::new(RailSpecs)); + let mut fixture = Fixture::new(move |ui| { + let _ = DockArea::new("Rail dock", Bind::bound(&mut workspace), &specs, &mut panels, DockConfig::default()).show(ui); + }); + fixture.room(Vec2::new(800.0, 600.0)).settle(); + let grips = + |fixture: &Fixture| last_pass_runs(fixture.ctx()).into_iter().filter(|(ty, _)| ty.contains("GroupGrip<")).map(|(_, runs)| runs).sum::(); + for step in 1..=3 { + fixture.frame(vec![pointer::moved(egui::pos2(500.0 + step as f32, 300.0))]); + assert_eq!(grips(&fixture), 0, "pointer step {step}: the rail's grip replays its last run"); + } +} From bf37300a17fc89165cf5f8c5bd0dd07b30b77e8f Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 02:19:01 +0000 Subject: [PATCH 34/40] 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 82f8f81491..afe5733a21 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 35/40] 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 f26bb25280..d6b93a7683 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 41061fe14b..8314365ebc 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 36/40] 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 3d4244cb56..59bb088272 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 425a56ccfb..d7ab140157 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 1e4895efef..dea38e0381 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 48153ff5f3..688d7438a0 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 37/40] 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 1521d943b7..1fcd062826 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 8ef2bc258d..195bf3a1b0 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 38/40] 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 ed571bfa72..1189ba99fc 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 3a6d0c0f87..ad9cd40c55 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 d7ab140157..8a8f04cd68 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] From e49f8de1ea39d308b4b00cc25ab859988aa94031 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 05:48:54 +0000 Subject: [PATCH 39/40] text: show the editor's I-beam only over its text and during its own press The text editor requested the I-beam every pass of an open session, wherever the pointer was. At hover priority it beat the canvas tool's cursor and showed over panels, the options bar and the rest of the UI. It now asks only while its press is not idle: the pointer is over the editor or its own press is held. --- crates/text/src/ui/editor.rs | 6 +++++- crates/text/tests/it/editor.rs | 19 +++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index 8d8a85a0ed..d15863e950 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -620,7 +620,11 @@ impl Component for TextEditor<'_> { if let Some(text) = copied { cx.clipboard().put(&[ClipItem::Text(text.into())]); } - cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover); + // The I-beam is the editor's over its text and while its own press is held; elsewhere the canvas's tool or the + // rest of the UI sets the pointer. + if !matches!(press.phase, PressPhase::Idle) { + cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover); + } if done.changed { cx.propose(selection); } else if selection != before { diff --git a/crates/text/tests/it/editor.rs b/crates/text/tests/it/editor.rs index 7abc5e2139..ef7e1ee25f 100644 --- a/crates/text/tests/it/editor.rs +++ b/crates/text/tests/it/editor.rs @@ -210,6 +210,25 @@ fn a_secondary_click_on_the_text_reports_a_context_click_and_starts_no_drag() { assert_eq!(editor.commits.get() + editor.cancels.get(), 0, "the session stays open"); } +/// The I-beam is the editor's only over its text and while its own press is held: elsewhere the pointer is the +/// canvas's or the rest of the UI's. +#[trial] +fn the_i_beam_shows_over_the_text_and_during_its_drag_but_not_elsewhere() { + let mut editor = session("abc def", None); + editor.focus(); + let i_beam = Some(craft_behavior::Cursor::System(craft_behavior::CursorIcon::Text)); + let cursor = |editor: &Session| craft_ui::runtime::cursor::current(editor.fixture.ctx()); + let (on_text, away) = (pos2(40.0, 10.0), pos2(300.0, 300.0)); + editor.fixture.frame(vec![pointer::moved(on_text)]).settle(); + assert_eq!(cursor(&editor), i_beam, "over the text"); + editor.fixture.frame(vec![pointer::moved(away)]).settle(); + assert_ne!(cursor(&editor), i_beam, "away from the text, with the session open"); + editor.fixture.frame(vec![pointer::moved(on_text)]).frame(vec![pointer::press(on_text)]).frame(vec![pointer::moved(away)]); + assert_eq!(cursor(&editor), i_beam, "a drag that leaves the text keeps it"); + editor.fixture.frame(vec![pointer::release(away)]).settle(); + assert_ne!(cursor(&editor), i_beam, "after the release"); +} + fn preedit(text: &str) -> Event { Event::Ime(ImeEvent::Preedit { text: text.to_owned(), active_range_chars: None }) } From d40340cd42fa07255146388fb1ad05fd6e7759b8 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sun, 22 Nov 2026 05:55:54 +0000 Subject: [PATCH 40/40] text: the editor's I-beam request in its own function (cognitive complexity) --- crates/text/src/ui/editor.rs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index d15863e950..eeb07900d3 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -445,6 +445,14 @@ fn char_at(lines: &[HostLine], pos: TextPos) -> usize { line.chars.start + line.text[..byte].chars().count() } +/// The I-beam is the editor's over its text and while its own press is held; elsewhere the canvas's tool or the rest +/// of the UI sets the pointer. +fn show_i_beam(cx: &mut Cx<'_, TextEditor<'_>>, phase: &PressPhase, vertical: bool) { + if !matches!(phase, PressPhase::Idle) { + cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover); + } +} + /// The clipboard's text when the pass's input asks to paste and the clipboard has it ready. fn pasted_text(cx: &mut Cx<'_, TextEditor<'_>>, inputs: &[EditorInput]) -> Option> { if !inputs.iter().any(|input| matches!(input, EditorInput::Edit(EditCommand::Paste))) { @@ -620,11 +628,7 @@ impl Component for TextEditor<'_> { if let Some(text) = copied { cx.clipboard().put(&[ClipItem::Text(text.into())]); } - // The I-beam is the editor's over its text and while its own press is held; elsewhere the canvas's tool or the - // rest of the UI sets the pointer. - if !matches!(press.phase, PressPhase::Idle) { - cx.cursor(if vertical { CursorIcon::VerticalText } else { CursorIcon::Text }, CursorPriority::Hover); - } + show_i_beam(cx, &press.phase, vertical); if done.changed { cx.propose(selection); } else if selection != before {