From 3502761b8985ee0e964c84d7031973763bd473b6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 04:12:25 +0000 Subject: [PATCH 01/74] craft-draw, craft-ui-patterns: MemoProps and PlainData on the paint bar, brush picker, symmetry and preset view types PaintValues drops the size and the hardness: the bar shows neither (the preset picker before it does), so a view over it keys only on what it shows. The gradient tile, its style and its focus outline are memo props too: a gradient item carries its tile. --- crates/draw/src/ui/brush_presets/picker.rs | 4 ++-- crates/draw/src/ui/brush_presets/settings.rs | 4 ++-- crates/draw/src/ui/brush_settings/ellipse.rs | 2 +- crates/draw/src/ui/gradient/fill.rs | 2 +- crates/draw/src/ui/gradient/tile.rs | 4 ++-- crates/draw/src/ui/paint_bar.rs | 18 ++++++------------ crates/draw/src/ui/symmetry/menu.rs | 4 ++-- crates/draw/src/ui/symmetry/model.rs | 2 +- crates/ui-contract/src/contract/entry.rs | 6 +++--- .../ui-patterns/src/patterns/presets/state.rs | 4 ++-- 10 files changed, 22 insertions(+), 28 deletions(-) diff --git a/crates/draw/src/ui/brush_presets/picker.rs b/crates/draw/src/ui/brush_presets/picker.rs index fb51e253a..9709d04fe 100644 --- a/crates/draw/src/ui/brush_presets/picker.rs +++ b/crates/draw/src/ui/brush_presets/picker.rs @@ -30,7 +30,7 @@ use crate::ui::brush_settings::{BrushSizeField, TipAngle, TipEllipse}; const DEFAULT_MAX_DIAMETER: f64 = 5000.0; /// The brush values the picker's head edits, given by the app each pass. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct BrushPickerValues { /// The diameter in pixels: the Size field and its log slider. @@ -117,7 +117,7 @@ impl<'a> GearRows<'a> { /// The picker's state, kept by the host while the app runs: the browser's view (search, open groups, scale), the /// parts the presets show and whether the search field shows. [`settings`](Self::settings) is what persists. -#[derive(Clone, Debug)] +#[derive(Clone, Debug, craft_ui::contract::PlainData)] #[non_exhaustive] pub struct BrushPickerState { /// The browser's view settings; its zoom is the thumbnail scale. diff --git a/crates/draw/src/ui/brush_presets/settings.rs b/crates/draw/src/ui/brush_presets/settings.rs index 33569b7b5..6899a1732 100644 --- a/crates/draw/src/ui/brush_presets/settings.rs +++ b/crates/draw/src/ui/brush_presets/settings.rs @@ -23,7 +23,7 @@ pub enum BrushCardPart { /// /// - The tip alone is the browser's grid of thumbnails with the size as each caption. /// - The name or the stroke is the browser's list: the stroke as the row's picture while it is on, else the tip. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[serde(default)] #[non_exhaustive] pub struct BrushCardParts { @@ -80,7 +80,7 @@ impl BrushCardParts { /// scale. The app saves it in its settings (serde) when /// [`BrushPresetPickerOutput::settings`](super::BrushPresetPickerOutput::settings) is set and restores it with /// [`BrushPickerState::restore`]; the search text, open groups and an open rename are not saved. -#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, craft_ui::contract::MemoProps)] #[serde(default)] #[non_exhaustive] pub struct BrushPickerSettings { diff --git a/crates/draw/src/ui/brush_settings/ellipse.rs b/crates/draw/src/ui/brush_settings/ellipse.rs index 7c1513a1e..a2beed00d 100644 --- a/crates/draw/src/ui/brush_settings/ellipse.rs +++ b/crates/draw/src/ui/brush_settings/ellipse.rs @@ -34,7 +34,7 @@ const ROUND_STEP: f64 = 0.01; const ROUND_MIN: f64 = 0.01; /// A tip's angle and roundness. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct TipAngle { /// The major axis's angle in whole degrees, counter-clockwise from the right, −180 to 180. diff --git a/crates/draw/src/ui/gradient/fill.rs b/crates/draw/src/ui/gradient/fill.rs index 3ea3a91b8..de9d5179a 100644 --- a/crates/draw/src/ui/gradient/fill.rs +++ b/crates/draw/src/ui/gradient/fill.rs @@ -8,7 +8,7 @@ use serde::{Deserialize, Serialize}; use super::fill_editor::GradientFillWords; /// How a gradient runs from its line. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum GradientStyle { /// Along the line. diff --git a/crates/draw/src/ui/gradient/tile.rs b/crates/draw/src/ui/gradient/tile.rs index 97f459520..9f3fc7769 100644 --- a/crates/draw/src/ui/gradient/tile.rs +++ b/crates/draw/src/ui/gradient/tile.rs @@ -18,7 +18,7 @@ const TILE_STEPS: usize = 17; /// /// A tile other than [`Ramp`](GradientTile::Ramp) is one `craft_color_ui::ui::smooth_mesh` sampled through /// [`t_at`](GradientTile::t_at). `p` below is a point in the tile's unit square (0 to 1, y down) and `c` its centre. -#[derive(Clone, Copy, Debug, Default, PartialEq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum GradientTile { /// The ramp chip: the gradient along its length. @@ -56,7 +56,7 @@ impl GradientTile { } /// The outline a [`GradientTile::Focus`] gradient follows. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum FocusOutline { /// A circle. diff --git a/crates/draw/src/ui/paint_bar.rs b/crates/draw/src/ui/paint_bar.rs index fec07db9e..c589e2e61 100644 --- a/crates/draw/src/ui/paint_bar.rs +++ b/crates/draw/src/ui/paint_bar.rs @@ -30,7 +30,7 @@ pub use words::PaintBarWords; const PRESSURE: &str = "target"; /// The painting tools the bar serves. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum PaintTool { /// The Brush tool. @@ -43,14 +43,10 @@ pub enum PaintTool { MixerBrush, } -/// The bar's values. -#[derive(Clone, Debug, PartialEq)] +/// The bar's values. The size and the hardness are the preset picker's, which comes before the bar. +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct PaintValues { - /// The brush size. - pub size: f64, - /// The brush hardness. - pub hardness: f64, /// The opacity. pub opacity: f64, /// The flow. @@ -78,8 +74,6 @@ impl PaintValues { /// options overwrites every field. pub fn new(mode: M) -> Self { PaintValues { - size: 30.0, - hardness: 0.5, opacity: 1.0, flow: 1.0, smoothing: Smoothing::default(), @@ -95,7 +89,7 @@ impl PaintValues { } /// The stroke smoothing options. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct Smoothing { /// The amount, 0 to 1. @@ -118,7 +112,7 @@ impl Default for Smoothing { } /// The Mixer Brush's values. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct MixerValues { /// Load the brush after each stroke. @@ -162,7 +156,7 @@ impl Default for MixerValues { } /// What the Eraser tool erases with. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum EraserMode { /// A brush. diff --git a/crates/draw/src/ui/symmetry/menu.rs b/crates/draw/src/ui/symmetry/menu.rs index abd9f7f24..f34d0ebf6 100644 --- a/crates/draw/src/ui/symmetry/menu.rs +++ b/crates/draw/src/ui/symmetry/menu.rs @@ -28,7 +28,7 @@ craft_ui::words! { } /// The symmetry in force, as the menu marks it. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum SymmetryChoice { /// No symmetry. @@ -40,7 +40,7 @@ pub enum SymmetryChoice { } /// A path the symmetry can come from (the saved paths, the Work Path, the layer's path), in the app's order. -#[derive(Clone, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct SymmetryPathRow { /// The app's key ("work", "layer", or the saved path's name). diff --git a/crates/draw/src/ui/symmetry/model.rs b/crates/draw/src/ui/symmetry/model.rs index ad3c79080..6b623ec96 100644 --- a/crates/draw/src/ui/symmetry/model.rs +++ b/crates/draw/src/ui/symmetry/model.rs @@ -9,7 +9,7 @@ pub const TURN_STEP_DEGREES: f64 = 15.0; /// The straight symmetry modes PhotoCraft has (lead call 23). Photoshop's Wavy, Circle, Spiral, /// Parallel Lines, Radial and Mandala modes need engine work and are not built. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(rename_all = "lowercase")] #[non_exhaustive] pub enum SymmetryMode { diff --git a/crates/ui-contract/src/contract/entry.rs b/crates/ui-contract/src/contract/entry.rs index dfffeaf84..1fdf97eeb 100644 --- a/crates/ui-contract/src/contract/entry.rs +++ b/crates/ui-contract/src/contract/entry.rs @@ -10,19 +10,19 @@ const NO_LABEL: Label = Label::Empty; /// A row of entries: an item that reports its value when picked, a heading over a group of items, or a separator /// between groups of items. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] pub struct Entry { row: Row, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] enum Row { Item(Item), Heading(Label), Separator, } -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, crate::contract::MemoProps)] struct Item { value: T, label: Label, diff --git a/crates/ui-patterns/src/patterns/presets/state.rs b/crates/ui-patterns/src/patterns/presets/state.rs index 47a4a2f7f..405c5fd4d 100644 --- a/crates/ui-patterns/src/patterns/presets/state.rs +++ b/crates/ui-patterns/src/patterns/presets/state.rs @@ -8,7 +8,7 @@ use std::collections::HashSet; use std::hash::Hash; /// How the presets are shown. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, crate::contract::PlainData)] #[serde(rename_all = "lowercase")] #[non_exhaustive] pub enum PresetView { @@ -37,7 +37,7 @@ pub enum DefaultOpen { /// /// A group is open when its default (from [`DefaultOpen`]) differs from membership in `toggled`. While the search /// text is not empty, every group is open. -#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, crate::contract::PlainData)] #[serde(default, bound(serialize = "K: serde::Serialize", deserialize = "K: serde::Deserialize<'de> + Eq + std::hash::Hash"))] #[non_exhaustive] pub struct PresetState { From da74cd2c85f415ad74a07c07e02fa0ffa5381f3e Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 04:30:41 +0000 Subject: [PATCH 02/74] craft-color-ui: MemoProps on the Color panel's settings, mode and ramp --- crates/color-ui/src/ui/panel.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 76c85e775..22a624530 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -62,7 +62,7 @@ craft_ui::words! { /// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default; /// the theme never changes it. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelMode { @@ -129,7 +129,7 @@ impl ColorPanelMode { } /// The ramp under the sliders. Shift-click on the ramp cycles them in this order. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum ColorPanelRamp { @@ -179,7 +179,7 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { From a94a95107f7df65e059370ac9a3a36e0e751ef7a Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 06:51:34 +0000 Subject: [PATCH 03/74] Memoized views: a held press engages a view only where its layer is the top layer at the press origin A drag on a popover over a memoized view ran the view on every move: the press half of lazy::engaged asked only whether the press origin lay in the view's rect. It now asks whether the view's layer is the top layer there, as the pointer half does through rect_contains_pointer. Trial: a drag on a popover's slider over a view replays the view. --- crates/ui-contract/src/runtime/lazy.rs | 7 ++- crates/ui-widgets/tests/it/body/memo_view.rs | 65 +++++++++++++++++++- 2 files changed, 69 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 19b1b46e3..368d5c2c5 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -559,10 +559,13 @@ fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option bool { let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); - ctx.rect_contains_pointer(layer, rect) || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin)) + ctx.rect_contains_pointer(layer, rect) + || input_state::held_press_origin(ctx) + .is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 0c52bb966..4a5d7e01b 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -12,7 +12,8 @@ use craft_ui::runtime::memory::{SaveKey, set_saved_value}; use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::in_audit_run; use craft_ui::testing::input::key_press; -use craft_ui::testing::layout::{in_region, measured_block}; +use craft_ui::popover::Popover; +use craft_ui::testing::layout::{allocate, in_region, measured_block}; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{ Frames, MemoRun, last_frame_memo_runs, last_pass_measuring_runs, last_pass_memo_key_bytes, last_pass_memo_runs, last_pass_runs, @@ -1084,6 +1085,68 @@ fn a_view_replayed_for_frames_keeps_the_layout_memory_it_kept() { assert_eq!(after_replays, after_a_run, "the replays kept the stack's measurements alive"); } +/// A view as large as the region `COVERED` gives it, under the popover of the covered trial. +#[derive(MemoProps)] +struct Board { + title: String, +} + +fn board(props: &mut Board, ui: &mut Ui) { + Button::new(props.title.clone()).show(ui); + allocate(ui, Vec2::new(300.0, 200.0)); +} + +/// Where the board view is: the popover hangs over its middle. +const COVERED: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(410.0, 260.0) }; + +/// A board view with an open popover over it whose slider edits a value the board does not show. +struct Covered { + size: f32, + /// Where the slider in the popover was shown in the last frame. + slider: Option, +} + +impl Covered { + fn show(&mut self, ui: &mut Ui) { + in_region(ui, COVERED, |ui| MemoView::new("board", Board { title: "Board".to_owned() }, board).show(ui)); + let (size, slider) = (&mut self.size, &mut self.slider); + Popover::new("Size", Bind::given(true)).at_point(Pos2::new(80.0, 80.0)).show(ui, |ui, _| { + *slider = Some(Scrub::new(Bind::bound(size)).show(ui).response.rect); + }); + } + + /// One frame with `events`; returns the views that ran in any of its passes, by props type name. + fn frame(&mut self, frames: &mut Frames, events: Vec) -> Vec<&'static str> { + frames.frame(events, |ui| self.show(ui)); + let ran = last_frame_memo_runs(&frames.ctx).into_iter().filter(|(_, _, run)| *run == MemoRun::Ran); + ran.map(|(name, _, _)| short_name(name)).collect() + } +} + +/// A drag of a slider on a popover over a memoized view leaves the view replaying: the press is on the popover, the +/// top layer where it started, so it engages nothing beneath it. +#[trial] +fn a_drag_on_a_popover_over_a_view_replays_the_view() { + let mut scene = Covered { size: 10.0, slider: None }; + let mut frames = Frames::new(); + for _ in 0..SETTLE { + scene.frame(&mut frames, vec![]); + } + let slider = scene.slider.expect("the popover shows its slider"); + let from = Pos2::new(slider.left() + 10.0, slider.center().y); + assert!(COVERED.contains(from), "the slider lies over the board"); + scene.frame(&mut frames, vec![moved(from)]); + assert_eq!(scene.frame(&mut frames, vec![press(from)]), Vec::<&str>::new(), "the press runs no view"); + let start = scene.size; + let mut runs = Vec::new(); + for step in 1..=4 { + runs.push(scene.frame(&mut frames, vec![moved(from + Vec2::new(12.0 * step as f32, 0.0))])); + } + scene.frame(&mut frames, vec![release(from + Vec2::new(48.0, 0.0))]); + assert_ne!(scene.size, start, "the drag edited the size"); + assert!(runs.iter().all(Vec::is_empty), "the board replays in every drag frame: {runs:?}"); +} + #[derive(MemoProps)] struct Centred { label: String, From 5734238622eab026418e22e2a3bfa83b81f0c03c Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 06:51:34 +0000 Subject: [PATCH 04/74] Memoized views: the view's content keeps the axes the enclosing body sizes from its content A memoized member of a bar whose content held a vertical rule took the bar's whole open room as its height: the view's layout room started with no content-sized axes, so a child that fills took the room. The room keeps the enclosing body's content axes (they join the scope key), so the view takes what its content used, as without the view. Trial: a bar with a memoized member is as high as the bar with the same content shown plainly. --- Cargo.lock | 1 + crates/ui-contract/src/contract/memo_view.rs | 15 +++++-- crates/ui-contract/src/runtime/env.rs | 7 +-- crates/ui-widgets/tests/it/bars/memo.rs | 47 ++++++++++++++++++-- 4 files changed, 60 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index add7ab337..2fe6988ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4252,6 +4252,7 @@ name = "craft-tracked" version = "0.1.0" dependencies = [ "craft-ui-macros", + "serde", ] [[package]] diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index d866926f6..04fb2ce87 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -3,7 +3,7 @@ use super::lazy::{Lazy, Shown}; use super::memo::{MemoKey, MemoProps}; -use crate::runtime::env::{Env, Scoped}; +use crate::runtime::env::Env; use crate::runtime::shift::Shift; use egui::Ui; use std::fmt; @@ -103,8 +103,17 @@ impl MemoVie let env = Env::of(ui); let key = Self::key(&ctx, &env, &props, show); let shown = lazy.run_keyed(ui, std::any::type_name::

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { - // The content is a layout room of its own: the flow of the body around it does not reach in. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); + // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps the + // axes that body sizes from its content, so the view takes what its content used there, as the same + // content shown without the view would: a child that fills takes its measured size, never the open room. + let installed = Env::install_for( + ui, + env.derive_local(|scoped| { + let content = scoped.content; + scoped.start_room(); + scoped.content = content; + }), + ); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 38a7d029b..8963b05df 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -397,9 +397,10 @@ impl Scoped { /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line - /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. The - /// flow fields of the enclosing body are not in it: a memoized view's content starts a layout room of its own - /// (`start_room`). Computed once per scope, on the first view that asks; the bytes it fed are counted then. + /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. Of + /// the flow fields of the enclosing body only the axes it sizes from its content are in it: a memoized view's + /// content starts a layout room of its own (`start_room`) that keeps those axes. Computed once per scope, on the + /// first view that asks; the bytes it fed are counted then. pub(crate) fn scope_key(&self) -> u128 { *self.scope_key.get_or_init(|| { use crate::contract::{MemoKey, MemoProps as _}; diff --git a/crates/ui-widgets/tests/it/bars/memo.rs b/crates/ui-widgets/tests/it/bars/memo.rs index a19c16ca3..ec051fa1a 100644 --- a/crates/ui-widgets/tests/it/bars/memo.rs +++ b/crates/ui-widgets/tests/it/bars/memo.rs @@ -3,17 +3,17 @@ //! idle frames replay them, a change to what one holds runs only that one, and an event leaves through an `Outbox`. use craft_behavior::IconId; -use craft_ui::bars::{Bar, BarItem, BarItems, BarKind, StatusMessage, StatusProgress}; +use craft_ui::bars::{Bar, BarHome, BarItem, BarItems, BarKind, StatusMessage, StatusProgress}; use craft_ui::buttons::IconButton; -use craft_ui::contract::{CommandSet, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _}; +use craft_ui::contract::{Bind, CommandSet, MemoProps, MemoView, Outbox, Props as _, Show as _, ShowContainer as _}; use craft_ui::display::Text; use craft_ui::layout_components::Stack; use craft_ui::runtime::commands::CommandScope; use craft_ui::runtime::env::Label; use craft_ui::testing::layout::in_region; -use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; +use craft_ui::testing::{Fixture, Frames, MemoRun, last_frame_memo_runs, trial}; use egui::{Pos2, Rect, Ui, Vec2}; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::rc::Rc; /// The tool commands of the toolbar. @@ -213,3 +213,42 @@ fn a_click_on_the_cancel_button_delivers_its_event_once() { fixture.settle(); assert_eq!(state.borrow().cancelled, 1); } + +/// The lead of an options bar as a member: Home and the vertical rule after it, which fills the bar's line. +#[derive(MemoProps)] +struct LeadProps { + on: bool, +} + +fn lead(props: &mut LeadProps, ui: &mut Ui) -> Rect { + BarHome::new("Home", Bind::given(props.on)).show(ui); + ui.min_rect() +} + +/// A bar offered far more height than its members need. +const TALL_ROOM: Vec2 = Vec2::new(400.0, 300.0); + +/// A memoized member takes what its content used: its rule that fills the line is as long as without the view, so the +/// bar with the member as a memoized view is as high as the bar with the same content shown plainly, both far below +/// the room they are offered. +#[trial] +fn a_memoized_member_takes_the_height_its_content_used_not_the_bars_room() { + let (plain, memo, member) = (Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING)); + Frames::new().idle(4, |ui| { + let at = |x: f32| Rect::from_min_size(Pos2::new(x, 10.0), TALL_ROOM); + plain.set(in_region(ui, at(10.0), |ui| { + Bar::new("Plain", BarKind::Options).show(ui, |ui, _| BarHome::new("Home", Bind::given(false)).show(ui)).output.response.rect + })); + memo.set(in_region(ui, at(420.0), |ui| { + let shown = Bar::new("Memoized", BarKind::Options).show(ui, |ui, _| MemoView::new("lead", LeadProps { on: false }, lead).show(ui)); + if let Some(Some(rect)) = shown.inner { + member.set(rect); + } + shown.output.response.rect + })); + }); + let (plain, memo, member) = (plain.get(), memo.get(), member.get()); + assert!(plain.height() < TALL_ROOM.y / 2.0, "the plain bar sizes from its members: {plain:?}"); + assert!(member.height() < TALL_ROOM.y / 2.0, "the member takes what its content used, not the bar's room: {member:?}"); + assert!((memo.height() - plain.height()).abs() <= 0.5, "the bar is as high with the member memoized: {memo:?} against {plain:?}"); +} From d37c886c2ddd926be5d336e27b005f1d129e6fa2 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 07:02:41 +0000 Subject: [PATCH 05/74] Memoized views: rustfmt --- crates/ui-contract/src/runtime/lazy.rs | 3 +-- crates/ui-widgets/tests/it/body/memo_view.rs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 368d5c2c5..a2fba430f 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -564,8 +564,7 @@ fn moved(ctx: &Context, settled: &Settled, view: Option<(Option, Option bool { let screen = ctx.layer_transform_to_global(layer).map_or(rect, |transform| transform * rect); ctx.rect_contains_pointer(layer, rect) - || input_state::held_press_origin(ctx) - .is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) + || input_state::held_press_origin(ctx).is_some_and(|origin| screen.contains(origin) && ctx.layer_id_at(origin) == Some(layer)) } /// Adds the last real run of the memoized view `id` to the running pass, in place of running it, at the place `shift` diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 4a5d7e01b..48813d530 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -7,12 +7,12 @@ use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Tracked}; use craft_ui::display::Text; use craft_ui::layout_components::{Row, Stack}; +use craft_ui::popover::Popover; use craft_ui::runtime::env::{BodyMode, RevealEdge, ShellCx, WindowKey}; use craft_ui::runtime::memory::{SaveKey, set_saved_value}; use craft_ui::runtime::{frame, inspect}; use craft_ui::testing::in_audit_run; use craft_ui::testing::input::key_press; -use craft_ui::popover::Popover; use craft_ui::testing::layout::{allocate, in_region, measured_block}; use craft_ui::testing::pointer::{moved, press, release}; use craft_ui::testing::{ From 6eae28f167e667f23199a303d29a3e1856276acb Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 06:07:09 +0000 Subject: [PATCH 06/74] craft-tracked: From, value equality and an optional serde feature for Tracked A Tracked field inside a derived PartialEq or serde type (a brush's tip inside its settings) compares by value and saves as its value; a loaded one starts a new source. --- crates/tracked/Cargo.toml | 8 +++++++- crates/tracked/src/lib.rs | 29 +++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/crates/tracked/Cargo.toml b/crates/tracked/Cargo.toml index 24265919f..ba1d94fe9 100644 --- a/crates/tracked/Cargo.toml +++ b/crates/tracked/Cargo.toml @@ -10,7 +10,13 @@ description = "Tracked: app data whose every write moves a revision, so a rea [lints] workspace = true -# No dependencies, so engine crates can hold and move a revision without the UI. +# No dependencies but an optional serde, so engine crates can hold and move a revision without the UI. +[dependencies] +serde = { workspace = true, optional = true } + +[features] +# `Serialize` and `Deserialize` for `Tracked`: saved as its value, loaded as a new source. +serde = ["dep:serde"] [dev-dependencies] # `#[derive(PlainData)]` in the doc tests. diff --git a/crates/tracked/src/lib.rs b/crates/tracked/src/lib.rs index a56ddbe4f..5587f70e7 100644 --- a/crates/tracked/src/lib.rs +++ b/crates/tracked/src/lib.rs @@ -326,13 +326,38 @@ impl Clone for Tracked { } } -/// Two values are equal when what they hold is: the revision says which writes a value saw, not what it is. +/// `value`, as a new source at count 0 ([`Tracked::new`]). +impl From for Tracked { + fn from(value: T) -> Tracked { + Tracked::new(value) + } +} + +/// Equal values compare equal, whatever their revisions. impl PartialEq for Tracked { - fn eq(&self, other: &Self) -> bool { + fn eq(&self, other: &Tracked) -> bool { self.value == other.value } } +impl Eq for Tracked {} + +/// Saved as its value. +#[cfg(feature = "serde")] +impl serde::Serialize for Tracked { + fn serialize(&self, serializer: S) -> Result { + self.value.serialize(serializer) + } +} + +/// Loaded as a new source. +#[cfg(feature = "serde")] +impl<'de, T: PlainData + serde::Deserialize<'de>> serde::Deserialize<'de> for Tracked { + fn deserialize>(deserializer: D) -> Result, D::Error> { + T::deserialize(deserializer).map(Tracked::new) + } +} + impl Deref for Tracked { type Target = T; From 000a091d4bf0f949ee28f7528a53806116356eb4 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 05:09:03 +0000 Subject: [PATCH 07/74] craft-menu: English names on the menu model, the MenuBarUi::english hook goes --- crates/menu/README.md | 2 +- crates/menu/src/bar.rs | 71 ++++++++----------------------- crates/menu/src/context.rs | 24 +++-------- crates/menu/src/layout.rs | 34 +++++++++++---- crates/menu/src/lib.rs | 2 +- crates/menu/src/model.rs | 45 +++++++++++++++++++- crates/menu/src/palette.rs | 22 +++++----- crates/menu/tests/it/mnemonic.rs | 21 +++++---- migration/api-map/craft-menu.toml | 9 +++- 9 files changed, 125 insertions(+), 105 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index a654dbcaf..29167ca57 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -156,7 +156,7 @@ egui::Panel::top("menu-bar").show(ui, |ui| { they are off unless set. `.mnemonics(&[("View", 'W'), ("file.open", 'P')])` names preferred letters by title as shown or by command id. A label without an ASCII letter or digit shows its English label's letter after it, "文件(F)", before a trailing ellipsis ("開く(O)…"), when - `.english(&hook)` returns that English label for the `Labeled::Command` or `Labeled::Title`. + the item, submenu or menu carries that English label (`Item::english`, `Node::english`, `Menu::english`). - **Items:** a command the runtime's gate forbids, or whose state is disabled, is greyed and never fires. A submenu whose items are all disabled is greyed. The shortcut column shows the command's chord, else the item's own shortcut, in the shell's names (⌘ glyphs on a Mac). `.target(..)` diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 35e8fe9ae..00da81878 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -13,8 +13,8 @@ pub(crate) mod stories; use craft_host::target::Os; use craft_i18n::Words; -use craft_keymap::{CommandRef, Platform}; -use craft_ui::contract::{MemoProps, MemoView, Show as _, Stateless, Tracked}; +use craft_keymap::Platform; +use craft_ui::contract::{MemoProps, MemoView, Show as _, Tracked}; use craft_ui::menu::{MenuBar as Bar, MenuHelp, MenuTitle}; use craft_ui::runtime::env::{Env, Label}; use egui::{Rect, Ui}; @@ -27,19 +27,6 @@ use crate::palette::entries_of; /// Whether a menu of the bar is open; the app's single-key shortcuts wait while it is true. pub use craft_ui::menu::bar::{is_focused, is_open}; -/// A row or title, as the bar names it to the app's mnemonic hooks ([`MenuBarUi::english`]). -#[derive(Clone, Copy, Debug, PartialEq)] -#[non_exhaustive] -pub enum Labeled<'s> { - /// An item, by its command. - Command(&'s CommandRef), - /// A menu or submenu, by its title as shown. - Title(&'s str), -} - -/// The app's English labels ([`MenuBarUi::english`]). -pub type EnglishHook<'h> = dyn Fn(Labeled<'_>) -> Option + 'h; - craft_ui::words! { /// The words of the in-window bar that the menu family does not hold. struct BarWords { @@ -78,21 +65,16 @@ pub struct MenuBarOutput { pub titles: Rect, } -/// The English-label hook a bar takes by default: none is set, so this type only names the slot. -pub type EnglishFn = fn(Labeled<'_>) -> Option; - /// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel. /// The commands chosen come back through the command queue, not from `show`. /// /// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing /// reaches it (pointer, focus, keys, an open menu), it adds that run again in place of running. #[derive(craft_ui::contract::Pattern)] -#[pattern(probe(MenuBarUi<'static, EnglishFn>))] -pub struct MenuBarUi<'a, E = EnglishFn> { +pub struct MenuBarUi<'a> { bar: &'a Tracked, /// The platform set with [`target`](Self::target); the shell's when none is. target: Option, - english: Option>, preferred: &'a [(&'a str, char)], keyboard: Option, help_search: bool, @@ -100,10 +82,9 @@ pub struct MenuBarUi<'a, E = EnglishFn> { /// Every input of the bar's view. #[derive(MemoProps)] -struct BarProps<'a, #[memo_props(stateless)] E> { +struct BarProps<'a> { bar: &'a Tracked, target: Target, - english: Option>, preferred: &'a [(&'a str, char)], keyboard: bool, help: Option, @@ -113,47 +94,37 @@ struct BarProps<'a, #[memo_props(stateless)] E> { impl<'a> MenuBarUi<'a> { /// The bar for `bar`, already laid out ([`crate::layout`]), on the shell's platform ([`Target::of_shell`]). pub fn new(bar: &'a Tracked) -> MenuBarUi<'a> { - MenuBarUi { bar, target: None, english: None, preferred: &[], keyboard: None, help_search: false } + MenuBarUi { bar, target: None, preferred: &[], keyboard: None, help_search: false } } } -impl<'a, E: Fn(Labeled<'_>) -> Option + Copy + 'static> MenuBarUi<'a, E> { +impl<'a> MenuBarUi<'a> { /// The platform the bar is on, for the shortcut column ([`craft_keymap::Chord::display`]): ⌘ glyphs on /// [`Target::Mac`] and in a browser on a Mac, Ctrl names everywhere else. On [`Target::Mac`] the native bar /// has the keys, and this one takes none unless [`keyboard`](Self::keyboard) says so. - pub fn target(mut self, target: Target) -> MenuBarUi<'a, E> { + pub fn target(mut self, target: Target) -> MenuBarUi<'a> { self.target = Some(target); self } /// Whether the bar takes F10, Alt and Alt with a letter. By default it does, except on [`Target::Mac`]. The /// app turns it off while a modal dialog or the shortcut recorder has the keys. - pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a, E> { + pub fn keyboard(mut self, on: bool) -> MenuBarUi<'a> { self.keyboard = Some(on); self } - /// The English label of a row or title, for labels the keyboard can't type a letter of (Chinese, Japanese, - /// Korean…): such a label shows its English label's mnemonic after it, "文件(F)", before a trailing ellipsis - /// ("開く(O)…"), as Windows menus do. Without this hook (or when it returns `None`) such a label has no - /// mnemonic. The Help menu's search also matches the English labels, on every target. The hook is a fn item or a - /// closure that captures nothing ([`Stateless`]): the bar's key follows its type. - pub fn english) -> Option + Copy + 'static>(self, english: F) -> MenuBarUi<'a, F> { - let MenuBarUi { bar, target, english: _, preferred, keyboard, help_search } = self; - MenuBarUi { bar, target, english: Some(Stateless::new(english)), preferred, keyboard, help_search } - } - /// Preferred mnemonics, each for a menu or submenu by its title as shown or for an item by its command id: /// the row takes that letter when its label has it and no row before it in its menu took it. Every other row /// takes the first unused letter of its label, word starts first. - pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a, E> { + pub fn mnemonics(mut self, preferred: &'a [(&'a str, char)]) -> MenuBarUi<'a> { self.preferred = preferred; self } /// Start the [`MenuRole::Help`] menu with a search field over every command of the bar /// ([`MenuBar::help_entries`]). A bar with no Help menu has no field. - pub fn help_search(mut self, on: bool) -> MenuBarUi<'a, E> { + pub fn help_search(mut self, on: bool) -> MenuBarUi<'a> { self.help_search = on; self } @@ -168,24 +139,18 @@ impl<'a, E: Fn(Labeled<'_>) -> Option + Copy + 'static> MenuBarUi<'a, E> let props = BarProps { bar: self.bar, target, - english: self.english, preferred: self.preferred, keyboard: self.keyboard.unwrap_or(target != Target::Mac), help, label: env.words::().label.clone(), }; - MemoView::new("menu-bar", props, show_bar::).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) + MemoView::new("menu-bar", props, show_bar).show(ui).unwrap_or(MenuBarOutput { titles: Rect::NOTHING }) } } /// The bar's view: the titles through [`craft_ui::menu::MenuBar`], each menu's rows as command rows. -fn show_bar) -> Option + Copy + 'static>(props: &mut BarProps<'_, E>, ui: &mut Ui) -> MenuBarOutput { - let hook = props.english.map(|english| { - let english = english.get(); - move |labeled: Labeled<'_>| english(labeled) - }); - let english: Option<&EnglishHook<'_>> = hook.as_ref().map(|hook| hook as &EnglishHook<'_>); - let rows = Rows::new(props.target).english(english).preferred(props.preferred); +fn show_bar(props: &mut BarProps<'_>, ui: &mut Ui) -> MenuBarOutput { + let rows = Rows::new(props.target).preferred(props.preferred); let env = Env::of(ui); let os = env.view().shell().os; // The text of every menu is worked out once for these inputs and kept: a pass that shows an open menu again writes none of it. @@ -194,7 +159,6 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B target: props.target, os, preferred: props.preferred, - english: props.english, words: &env.words, keymap: craft_ui::runtime::commands::keymap_generation(ui.ctx()), }; @@ -212,7 +176,7 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B .collect(); // Collecting the search's commands walks every row of every menu: the bar does it only while Help is open. let bar_model: &MenuBar = props.bar; - let entries = move || entries_of(bar_model, english); + let entries = move || entries_of(bar_model); let mut bar = Bar::new(props.label.clone(), titles).keyboard(props.keyboard); if let Some(menu) = props.help { bar = bar.help(MenuHelp::new(menu, &entries)); @@ -220,15 +184,14 @@ fn show_bar) -> Option + Copy + 'static>(props: &mut B MenuBarOutput { titles: bar.show(ui).titles } } -/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the mnemonic and English -/// hooks, the language and the keymap. +/// What the kept text of a bar is made of: the model, the platform that names its shortcuts, the preferred mnemonics, +/// the language and the keymap. The English names are part of the model. #[derive(MemoProps)] -struct LabelKey<'a, #[memo_props(stateless)] E> { +struct LabelKey<'a> { bar: &'a Tracked, target: Target, os: Os, preferred: &'a [(&'a str, char)], - english: Option>, words: &'a Words, keymap: u64, } diff --git a/crates/menu/src/context.rs b/crates/menu/src/context.rs index 6f6f3ac28..f353a7fe6 100644 --- a/crates/menu/src/context.rs +++ b/crates/menu/src/context.rs @@ -15,7 +15,7 @@ use craft_ui::runtime::pointer; use craft_ui::runtime::windows::{WindowAction, WindowHost}; use egui::{Ui, ViewportId}; -use crate::bar::{EnglishHook, Labeled, keymap_platform}; +use crate::bar::keymap_platform; use crate::layout::Target; use crate::model::{Builtin, Item, ItemKind, Node}; @@ -54,22 +54,16 @@ pub(crate) struct BarLabels { pub(crate) menus: Vec, } -/// How the rows of a menu are written: the target that names the shortcuts, the app's English labels and its -/// preferred mnemonic letters. +/// How the rows of a menu are written: the target that names the shortcuts and the app's preferred mnemonic +/// letters. pub(crate) struct Rows<'a> { target: Target, - english: Option<&'a EnglishHook<'a>>, preferred: &'a [(&'a str, char)], } impl<'a> Rows<'a> { pub(crate) fn new(target: Target) -> Self { - Rows { target, english: None, preferred: &[] } - } - - pub(crate) fn english(mut self, english: Option<&'a EnglishHook<'a>>) -> Self { - self.english = english; - self + Rows { target, preferred: &[] } } pub(crate) fn preferred(mut self, preferred: &'a [(&'a str, char)]) -> Self { @@ -112,10 +106,6 @@ impl<'a> Rows<'a> { self.preferred.iter().find(|(k, _)| *k == key).map(|(_, c)| *c) } - pub(crate) fn english_of(&self, labeled: Labeled<'_>) -> Option { - self.english.and_then(|hook| hook(labeled)) - } - /// The label a node shows as the menu's sibling, for the preferred letters and the English labels. pub(crate) fn node_labels(&self, nodes: &[Node]) -> Vec { let shown: Vec<&Node> = nodes.iter().filter(|node| !matches!(node, Node::Separator | Node::Standard { .. })).collect(); @@ -133,8 +123,8 @@ impl<'a> Rows<'a> { _ => "", }, |node| match node { - Node::Item(item) => self.english_of(Labeled::Command(&item.command)), - Node::Submenu { label, .. } => self.english_of(Labeled::Title(label)), + Node::Item(item) => item.english.clone(), + Node::Submenu { english, .. } => english.clone(), _ => None, }, ) @@ -164,7 +154,7 @@ impl<'a> Rows<'a> { /// The text of a whole bar: the titles and each menu's rows. pub(crate) fn bar_labels(&self, menus: &[crate::model::Menu], platform: Platform) -> BarLabels { - let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| self.english_of(Labeled::Title(&menu.title))); + let titles = self.labels(menus, |menu| menu.title.as_str(), |menu| menu.title.as_str(), |menu| menu.english.clone()); BarLabels { titles, menus: menus.iter().map(|menu| self.level_labels(&menu.children, platform)).collect() } } diff --git a/crates/menu/src/layout.rs b/crates/menu/src/layout.rs index fd1627385..a12a7d002 100644 --- a/crates/menu/src/layout.rs +++ b/crates/menu/src/layout.rs @@ -103,6 +103,11 @@ impl<'a> LayoutOptions<'a> { (self.label)(english).replace("{app}", self.app_name) } + /// The English text of a label `text` writes, `{app}` filled in. + fn english_text(&self, english: &'static str) -> String { + english.replace("{app}", self.app_name) + } + fn standard(&self, kind: Standard) -> Node { Node::Standard { kind, label: self.text(kind.english()) } } @@ -181,6 +186,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout { let mut menu = Vec::new(); if let Some(Node::Item(mut it)) = about { it.label = options.text("About {app}"); + it.english = Some(options.english_text("About {app}")); menu.extend([Node::Item(it), Node::Separator]); } if let Some(s) = settings { @@ -188,8 +194,9 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout { menu.push(settings_node(s, comma, options, &mut clashes)); } if let Some(mut l) = language { - if let Node::Submenu { label, .. } = &mut l { + if let Node::Submenu { label, english, .. } = &mut l { *label = options.text("Language"); + *english = Some("Language".to_owned()); } menu.push(l); } @@ -228,6 +235,7 @@ pub fn mac_layout(bar: &MenuBar, options: &LayoutOptions) -> Layout { _ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit), }; quit.label = options.text("Quit {app}"); + quit.english = Some(options.english_text("Quit {app}")); match taken(CMD_Q, std::slice::from_ref(&quit.command)) { Some(command) => { clashes.push(Clash { shortcut: CMD_Q, system: "Quit", command, resolution: "Quit has no shortcut" }); @@ -349,15 +357,19 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option _ => Item::new(Builtin::Quit.command(), "").role(ItemRole::Quit), }; it.label = options.text(label); + it.english = Some(options.english_text(label)); ensure_menu(&mut bar, MenuRole::File, "File", options).children.extend([Node::Separator, Node::Item(it)]); } if let Some(s) = settings { let s = match s { Node::Item(mut it) => { it.label = options.text("Preferences…"); + it.english = Some("Preferences…".to_owned()); Node::Item(it) } - Node::Submenu { children, role, platforms, .. } => Node::Submenu { label: options.text("Preferences"), children, role, platforms }, + Node::Submenu { children, role, platforms, .. } => { + Node::Submenu { label: options.text("Preferences"), english: Some("Preferences".to_owned()), children, role, platforms } + } other => other, }; ensure_menu(&mut bar, MenuRole::Edit, "Edit", options).children.extend([Node::Separator, s]); @@ -370,6 +382,7 @@ fn desktop_bar(bar: &MenuBar, target: Target, quit: Option<&'static str>, option } if let Some(Node::Item(mut it)) = about { it.label = options.text("About {app}"); + it.english = Some(options.english_text("About {app}")); ensure_menu(&mut bar, MenuRole::Help, "Help", options).children.extend([Node::Separator, Node::Item(it)]); } finish(&mut bar, |_| false); @@ -383,9 +396,13 @@ fn shown_on(bar: &MenuBar, target: Target) -> MenuBar { let shown = nodes.iter().filter_map(|n| match n { Node::Item(it) if !it.platforms.contains(on) => None, Node::Submenu { platforms, .. } if !platforms.contains(on) => None, - Node::Submenu { label, children, role, platforms } => { - Some(Node::Submenu { label: label.clone(), children: keep(children, on, appkit), role: *role, platforms: *platforms }) - } + Node::Submenu { label, english, children, role, platforms } => Some(Node::Submenu { + label: label.clone(), + english: english.clone(), + children: keep(children, on, appkit), + role: *role, + platforms: *platforms, + }), Node::Standard { .. } if !appkit => None, other => Some(other.clone()), }); @@ -420,7 +437,7 @@ fn ensure_menu<'b>(bar: &'b mut MenuBar, role: MenuRole, english: &'static str, MenuRole::Help => bar.menus.len(), _ => bar.menus.iter().position(|m| m.role == MenuRole::Help).unwrap_or(bar.menus.len()), }; - bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).role(role)); + bar.menus.insert(at, Menu::new(options.text(english), Vec::new()).english(english).role(role)); at } }; @@ -450,6 +467,7 @@ fn settings_node(node: Node, comma_taken: Option, options: &LayoutOp match node { Node::Item(mut it) => { it.label = options.text("Settings…"); + it.english = Some("Settings…".to_owned()); give(&mut it); Node::Item(it) } @@ -457,7 +475,7 @@ fn settings_node(node: Node, comma_taken: Option, options: &LayoutOp if let Some(Node::Item(first)) = children.iter_mut().find(|n| matches!(n, Node::Item(i) if i.enabled)) { give(first); } - Node::Submenu { label: options.text("Settings"), children, role, platforms } + Node::Submenu { label: options.text("Settings"), english: Some("Settings".to_owned()), children, role, platforms } } other => other, } @@ -478,7 +496,7 @@ fn appearance_node(bar: &mut MenuBar, options: &LayoutOptions) -> Vec { children.push(Node::Separator); children.extend(items); } - vec![Node::Submenu { label: options.text("Appearance"), children, role, platforms }] + vec![Node::Submenu { label: options.text("Appearance"), english: Some("Appearance".to_owned()), children, role, platforms }] } _ => items, } diff --git a/crates/menu/src/lib.rs b/crates/menu/src/lib.rs index 17ffce8ee..aeed6522c 100644 --- a/crates/menu/src/lib.rs +++ b/crates/menu/src/lib.rs @@ -114,7 +114,7 @@ pub mod mac; pub mod ribbon; pub mod shortcuts; -pub use bar::{EnglishHook, Labeled, MenuBarOutput, MenuBarUi}; +pub use bar::{MenuBarOutput, MenuBarUi}; pub use craft_keymap::{Chord, CommandRef}; pub use customize::Customization; pub use documents::DOCUMENT_COMMAND_PREFIX; diff --git a/crates/menu/src/model.rs b/crates/menu/src/model.rs index 867b86bb7..4563bd3c5 100644 --- a/crates/menu/src/model.rs +++ b/crates/menu/src/model.rs @@ -57,6 +57,9 @@ impl Document { pub struct Menu { /// The title in the bar. pub title: String, + /// The title's English name, when `title` is a translation: the bar takes the mnemonic of a title the keyboard + /// can't type from it. + pub english: Option, /// What the menu is for. pub role: MenuRole, /// The menu's entries, top to bottom. @@ -145,6 +148,8 @@ pub enum Node { Submenu { /// The submenu's title. label: String, + /// The title's English name, when `label` is a translation ([`Menu::english`]). + english: Option, /// The submenu's entries. children: Vec, /// The place a layout gives it, if any. @@ -172,6 +177,9 @@ pub struct Item { pub command: CommandRef, /// The text shown. pub label: String, + /// The label's English name, when `label` is a translation. A label the keyboard can't type (Chinese, Japanese, + /// Korean…) takes its mnemonic from it in the in-window bar, and the Help search matches it on every target. + pub english: Option, /// `cmd` is ⌘ and `ctrl` the Control key: ⌃⌘M and ⌘M are different shortcuts. pub shortcut: Option, /// Whether the item can be chosen. @@ -354,6 +362,7 @@ impl Item { Item { command: command.into(), label: label.into(), + english: None, shortcut: None, enabled: true, kind: ItemKind::Plain, @@ -402,6 +411,12 @@ impl Item { self } + /// Set the label's English name ([`Item::english`] field). + pub fn english(mut self, english: impl Into) -> Item { + self.english = Some(english.into()); + self + } + /// Show the item only on `platforms`. pub fn platforms(mut self, platforms: Platforms) -> Item { self.platforms = platforms; @@ -435,7 +450,17 @@ impl Node { /// A submenu shown on every platform. pub fn submenu(label: impl Into, children: Vec) -> Node { - Node::Submenu { label: label.into(), children, role: None, platforms: Platforms::ALL } + Node::Submenu { label: label.into(), english: None, children, role: None, platforms: Platforms::ALL } + } + + /// Set the English name of an item's label or a submenu's title. + pub fn english(mut self, english: impl Into) -> Node { + match &mut self { + Node::Item(it) => it.english = Some(english.into()), + Node::Submenu { english: e, .. } => *e = Some(english.into()), + Node::Separator | Node::Standard { .. } => {} + } + self } /// Give an item or a submenu a role: `Node::submenu("Theme", pages).role(ItemRole::Appearance)`. @@ -462,7 +487,13 @@ impl Node { impl Menu { /// A menu with no special role. pub fn new(title: impl Into, children: Vec) -> Menu { - Menu { title: title.into(), role: MenuRole::Other, children } + Menu { title: title.into(), english: None, role: MenuRole::Other, children } + } + + /// Set the title's English name ([`Menu::english`] field). + pub fn english(mut self, english: impl Into) -> Menu { + self.english = Some(english.into()); + self } /// Set the menu's role. @@ -580,6 +611,8 @@ pub struct Row { pub command: CommandRef, /// The text shown. pub label: String, + /// The label's English name, when `label` is a translation ([`Item::english`]). + pub english: Option, /// The row's shortcut. pub shortcut: Option, /// Whether the row can be chosen. @@ -601,6 +634,7 @@ impl Row { path: path.iter().map(|s| (*s).to_owned()).collect(), command: command.into(), label: label.into(), + english: None, shortcut: None, enabled: true, kind: ItemKind::Plain, @@ -610,6 +644,12 @@ impl Row { } } + /// Set the label's English name. + pub fn english(mut self, english: impl Into) -> Row { + self.english = Some(english.into()); + self + } + /// Whether the row can be chosen. pub fn enabled(mut self, on: bool) -> Row { self.enabled = on; @@ -682,6 +722,7 @@ pub fn from_items(tops: &[&str], rows: &[Row]) -> MenuBar { match slot { Slot::Leaf(it) if it.label == "---" => out.push(Node::Separator), Slot::Leaf(it) => out.push(Node::Item(Item { + english: it.english.clone(), shortcut: it.shortcut, enabled: it.enabled, kind: it.kind, diff --git a/crates/menu/src/palette.rs b/crates/menu/src/palette.rs index 07e2ab657..99eab3ec2 100644 --- a/crates/menu/src/palette.rs +++ b/crates/menu/src/palette.rs @@ -2,7 +2,6 @@ use craft_ui::menu::HelpEntry; -use crate::bar::{EnglishHook, Labeled}; use crate::model::{Builtin, MenuBar, Node}; use crate::{LayoutOptions, Target, layout}; @@ -18,39 +17,38 @@ impl MenuBar { /// Building the list lays out the whole bar, so a host caches the result and rebuilds it when the bar /// changes, not every frame. /// - /// `english` gives a command's or menu title's English name (as [`crate::MenuBarUi::english`]), asked on - /// every target, so the search finds a translated command by its English name. - pub fn help_entries(&self, target: Target, options: &LayoutOptions, english: Option<&EnglishHook<'_>>) -> Vec { - entries_of(&layout(self, target, options).bar, english) + /// An item's [`english`](crate::Item::english) name is listed with it, on every target, so the search finds a + /// translated command by its English name. + pub fn help_entries(&self, target: Target, options: &LayoutOptions) -> Vec { + entries_of(&layout(self, target, options).bar) } } /// The entries of an already laid-out bar. -pub(crate) fn entries_of(bar: &MenuBar, english: Option<&EnglishHook<'_>>) -> Vec { - let english_of = |labeled: Labeled<'_>| english.and_then(|hook| hook(labeled)); +pub(crate) fn entries_of(bar: &MenuBar) -> Vec { let mut entries = Vec::new(); let mut path: Vec = Vec::new(); for menu in &bar.menus { path.push(menu.title.clone()); - collect(&menu.children, &mut path, &english_of, &mut entries); + collect(&menu.children, &mut path, &mut entries); path.pop(); } entries } -fn collect(nodes: &[Node], path: &mut Vec, english_of: &dyn Fn(Labeled<'_>) -> Option, entries: &mut Vec) { +fn collect(nodes: &[Node], path: &mut Vec, entries: &mut Vec) { for node in nodes { match node { Node::Item(item) if Builtin::of(&item.command).is_none() => { let mut entry = HelpEntry::new(item.command.clone(), item.label.clone()).with_path(path.iter().cloned()); - if let Some(english) = english_of(Labeled::Command(&item.command)) { - entry = entry.with_english(english); + if let Some(english) = &item.english { + entry = entry.with_english(english.clone()); } entries.push(entry); } Node::Submenu { label, children, .. } => { path.push(label.clone()); - collect(children, path, english_of, entries); + collect(children, path, entries); path.pop(); } Node::Item(_) | Node::Separator | Node::Standard { .. } => {} diff --git a/crates/menu/tests/it/mnemonic.rs b/crates/menu/tests/it/mnemonic.rs index 8a43bc0c7..63c1dc60b 100644 --- a/crates/menu/tests/it/mnemonic.rs +++ b/crates/menu/tests/it/mnemonic.rs @@ -5,21 +5,18 @@ use std::sync::Arc; use craft_host::target::Os; use craft_host::{AppInfo, Host}; -use craft_menu::{CommandRef, Labeled, MenuBarUi, Row, from_items}; +use craft_menu::{CommandRef, LayoutOptions, MenuBarUi, Row, Target, from_items}; use craft_ui::contract::Tracked; use craft_ui::testing::{Fixture, trial}; use egui::{Key, Modifiers}; #[trial] fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { - let bar = Tracked::new(from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建")])); - let english = |labeled: Labeled<'_>| match labeled { - Labeled::Title("文件") => Some("File".to_owned()), - Labeled::Command(command) if *command == CommandRef::new("file.new") => Some("New".to_owned()), - _ => None, - }; + let mut bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]); + bar.menus[0].english = Some("File".to_owned()); + let bar = Tracked::new(bar); let mut fixture = Fixture::new(move |ui| { - MenuBarUi::new(&bar).english(english).show(ui); + MenuBarUi::new(&bar).show(ui); }); // A Mac bar has no letters. fixture.os(Os::Linux); @@ -30,6 +27,14 @@ fn a_cjk_title_shows_its_english_letter_and_alt_with_the_letter_opens_it() { assert!(fixture.by_label("新建(N)").is_some(), "Alt+F opens the title's menu, whose row shows its own English letter"); } +#[trial] +fn help_search_lists_an_item_by_its_english_name_in_a_translated_model() { + let bar = from_items(&["文件"], &[Row::new(&["文件"], CommandRef::new("file.new"), "新建").english("New")]); + let entries = bar.help_entries(Target::Linux, &LayoutOptions::new("Sample")); + let entry = entries.iter().find(|entry| *entry.command() == CommandRef::new("file.new")).expect("the command is listed"); + assert_eq!(entry.english().map(|label| label.as_str()), Some("New")); +} + /// A host whose interface language is Turkish, with an empty catalog. pub(crate) fn turkish() -> Arc { let (i18n, _) = craft_i18n::I18n::from_owned([("tr".to_owned(), String::new(), String::new())], &["tr"]); diff --git a/migration/api-map/craft-menu.toml b/migration/api-map/craft-menu.toml index 3cb23d23a..72235b1c4 100644 --- a/migration/api-map/craft-menu.toml +++ b/migration/api-map/craft-menu.toml @@ -107,7 +107,12 @@ old = "id(Id)" new = "" note = "Use `Props::id_salt` on the bar's parent scope." +[[call]] +old = "MenuBarUi::english(hook)" +new = "Item::english, Node::english, Menu::english" +note = "The English name is a field of the model, set where the app translates a label." + [[call]] old = "MenuBar::palette_entries(&keymap, target, &options, english, os)" -new = "MenuBar::help_entries(target, &options, english)" -note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go." +new = "MenuBar::help_entries(target, &options)" +note = "Returns `craft_ui::menu::HelpEntry`; chords and enabled state come from the commands, so the keymap and operating system arguments go, and so does the English hook: set `Item::english` on the model." From bae11d791699c12f9ab51fd8797c03e85871033a Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 21:04:18 +0000 Subject: [PATCH 08/74] Preset lists as sources: PresetSource keys a browser's rows, the list runs as a memoized view PresetBrowser, PresetPicker, PresetManager and BrushPresetPicker take a PresetSource (the host's MemoProps inputs and capture-free fns that build the rows and answer can_rename, can_delete, can_move, accepts and thumb), so the browser's grid or list, its drop zone and row menu run in a memoized view keyed on the inputs. Rows are kept per inputs and scope units (runtime::derived). The Brush Preset picker's head and its search-row tools are memoized views of their own; the gear rows are a fn. Work in progress: the remaining callers (form dialogs, color-ui, draw gradients and patterns, text style panel, imaging layer styles) are not moved yet and do not build. --- crates/draw/src/ui/brush_presets/panel.rs | 26 +- crates/draw/src/ui/brush_presets/picker.rs | 297 +++--- crates/draw/src/ui/brush_presets/stories.rs | 33 +- crates/draw/tests/it/brush_presets.rs | 20 +- crates/ui-contract/src/contract/memo.rs | 14 + crates/ui-contract/src/runtime/drag.rs | 2 +- crates/ui-contract/src/runtime/env/units.rs | 11 + .../src/patterns/presets/browser.rs | 846 +++++++++--------- .../src/patterns/presets/browser/reorder.rs | 40 +- .../src/patterns/presets/browser/stories.rs | 9 +- .../src/patterns/presets/manager.rs | 68 +- .../src/patterns/presets/manager/stories.rs | 24 +- .../ui-patterns/src/patterns/presets/mod.rs | 4 +- .../ui-patterns/src/patterns/presets/model.rs | 4 +- .../ui-patterns/src/patterns/presets/named.rs | 7 +- .../src/patterns/presets/named/stories.rs | 28 +- .../src/patterns/presets/picker.rs | 73 +- .../src/patterns/presets/picker/stories.rs | 19 +- .../src/patterns/presets/source.rs | 214 +++++ .../ui-patterns/src/patterns/presets/state.rs | 6 +- .../ui-patterns/tests/it/presets/browser.rs | 19 +- crates/ui-patterns/tests/it/presets/named.rs | 6 +- crates/ui-patterns/tests/it/presets/picker.rs | 16 +- 23 files changed, 1065 insertions(+), 721 deletions(-) create mode 100644 crates/ui-patterns/src/patterns/presets/source.rs diff --git a/crates/draw/src/ui/brush_presets/panel.rs b/crates/draw/src/ui/brush_presets/panel.rs index 293b35c55..e81884ca9 100644 --- a/crates/draw/src/ui/brush_presets/panel.rs +++ b/crates/draw/src/ui/brush_presets/panel.rs @@ -3,9 +3,9 @@ use std::hash::Hash; use craft_behavior::{EditEvents, IconId}; -use craft_ui::contract::{Bind, EditResponse, Outcome, Props as _, ShowContainer as _}; +use craft_ui::contract::{Bind, EditResponse, MemoProps, Outcome, Props as _, ShowContainer as _}; use craft_ui::layout_components::Stack; -use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetState}; +use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFooterEvent, PresetFooterOptions, PresetReorder, PresetSource, PresetState}; use craft_ui::runtime::drag::DropZone; use craft_ui::runtime::env::{Env, Label}; use craft_ui::sections::FooterAction; @@ -29,9 +29,9 @@ pub(super) const BRUSH_THUMBS: TileZoom = #[must_use = "show the panel with `show`"] #[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)] #[pattern(probe(BrushesPanel<'static, u32>))] -pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { +pub struct BrushesPanel<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> { label: Label, - rows: &'a [PresetRow], + source: &'a PresetSource<'a, K>, state: Bind<'a, PresetState>, diameter: Bind<'a, f64>, max_size: f64, @@ -67,16 +67,22 @@ impl Outcome for BrushesPanelOutput { } } -impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> BrushesPanel<'a, K> { - /// A panel named `label` over the presets in `rows`, with its view in `state` and the brush +impl<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> BrushesPanel<'a, K> { + /// A panel named `label` over the presets of `source`, with its view in `state` and the brush /// size in `diameter` up to `max_size`. - pub fn new(label: impl Into

{ /// Where a drop target lies: a rect on an egui layer, in that layer's space. A component's own target lies over its /// visible rect on its layer; a component that takes drops over an area it does not draw (a preset browser's canvas) /// names the area with [`DropZone::new`] and registers with [`zone_target`]. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq, crate::contract::MemoProps)] pub struct DropZone { layer: Layer, rect: Rect, diff --git a/crates/ui-contract/src/runtime/env/units.rs b/crates/ui-contract/src/runtime/env/units.rs index 914423660..10b6f07bc 100644 --- a/crates/ui-contract/src/runtime/env/units.rs +++ b/crates/ui-contract/src/runtime/env/units.rs @@ -323,6 +323,17 @@ impl crate::contract::MemoProps for Units { } } +impl Units { + /// Feeds what the readers and writers are built from: the scope's words (the unit words come from them), the + /// number format and the point size. The readers built so far are a cache of these. + pub(crate) fn feed(&self, key: &mut crate::contract::MemoKey) { + use crate::contract::MemoProps as _; + self.scope_words.key(key); + self.format.key(key); + self.point_size.key(key); + } +} + impl Units { /// The codec of a zoom field in percent: the percent reader, up to two decimals (the zoom ladder has rungs such as /// 66.67 %), with zoom typing (`a/b` as a ratio, a second separator cutting the text), so every zoom field reads diff --git a/crates/ui-patterns/src/patterns/presets/browser.rs b/crates/ui-patterns/src/patterns/presets/browser.rs index c01396567..ab01c5d95 100644 --- a/crates/ui-patterns/src/patterns/presets/browser.rs +++ b/crates/ui-patterns/src/patterns/presets/browser.rs @@ -15,17 +15,18 @@ pub use reorder::PresetReorder; use super::event::{PresetEvent, PresetOutput}; use super::footer::{PresetFooter, PresetFooterEvent, PresetFooterOptions}; use super::model::{CellShape, PresetRow, PresetTiles, ThumbInfo, children_end, has_captions}; +use super::source::PresetSource; use super::state::{DefaultOpen, PresetState, PresetView}; use super::words::PresetWords; use crate::bars::{Bar, BarKind}; use crate::choice::Segmented; use crate::contract::{ - Bind, BodyCx, CollectionEvent, DropMark, DropTarget, DropZone, Entry, ListDrag, OpenChange, Pattern, Props, Rename, ReorderMove, ReorderRule, - RowHeight, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename, + Bind, BodyCx, CollectionEvent, DropMark, DropTarget, DropZone, Entry, ListDrag, MemoProps, MemoView, OpenChange, Outbox, Pattern, Props, Rename, + ReorderMove, ReorderRule, RowHeight, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, request_rename, }; use crate::display::Divider; use crate::layout_components::Stack; -use crate::list::{List, ListRow, RowInk, RowTest, ThumbSize}; +use crate::list::{List, ListRow, RowInk, ThumbSize}; use crate::menu::{Menu, MenuItem}; use crate::notices::{Notice, NoticeLayout}; use crate::primitives::{ContentPainterCx, IconSpec}; @@ -126,23 +127,6 @@ fn app_move(mv: ReorderMove>) -> Option> { }) } -type ThumbPainterFn<'a, K> = Box) + 'a>; - -/// Paints a preset's thumbnail: the content painter, the rect and what the browser knows of the preset. -pub struct ThumbPainter<'a, K>(ThumbPainterFn<'a, K>); - -impl<'a, K> ThumbPainter<'a, K> { - /// Runs the painter: how a picker hands its own to the browser it opens. - pub(super) fn paint(&self, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, K>) { - (self.0)(cx, rect, info); - } - - /// The painter that runs `paint`. - pub fn new(paint: impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, K>) + 'a) -> Self { - ThumbPainter(Box::new(paint)) - } -} - type BrowserToolsFn<'a> = Box; /// The host's controls at the reading end of the toolbar, after the search field: a picker's buttons and menus. @@ -183,14 +167,14 @@ impl<'a> BrowserTools<'a> { #[must_use = "show the browser with `show`"] #[derive(Pattern, Props)] #[pattern(probe(PresetBrowser<'static, u32>))] -pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { +pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 'static> { label: Label, /// The browser's own id, which `PresetBrowser::request_rename` names; the scope id of the `Ui` it is shown in /// when none is given. #[prop] browser_id: Option, state: Bind<'a, PresetState>, - rows: &'a [PresetRow], + source: &'a PresetSource<'a, K>, /// The selected preset, which the host keeps. #[prop] selected: Option, @@ -223,21 +207,9 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { /// Fixes the view, whatever the state says; the toolbar then has no view buttons. #[prop] view_lock: Option, - /// Which presets and groups may be renamed; F2 does nothing on another. - #[prop(func = "Fn(&K) -> bool")] - can_rename: Option>, - /// Which presets and groups the context menu may delete; its row is disabled for the others. - #[prop(func = "Fn(&K) -> bool")] - can_delete: Option>, - /// Which presets the row menu's Move to may move; the menu has no such row for the others. - #[prop(func = "Fn(&K) -> bool")] - can_move: Option>, - /// Paints a preset's thumbnail; without it the row's own `preview` paints. - #[prop(func = "Fn(&ContentPainterCx, Rect, ThumbInfo<'_, K>)")] - thumb: Option>, /// Presets (and groups) drag and move by these rules. #[prop] - reorder: Option>, + reorder: Option, /// An area outside the browser (a canvas, a timeline) where a dragged preset drops: a release there reports /// `PresetEvent::DropAt` with the pointer in the zone's layer space. Groups dropped there report nothing. Without /// `reorder` presets still drag, to the zone and to the host's own drop targets only. @@ -266,15 +238,15 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + 'static> { empty: Option

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { - // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps the - // axes that body sizes from its content, so the view takes what its content used there, as the same - // content shown without the view would: a child that fills takes its measured size, never the open room. - let installed = Env::install_for( - ui, - env.derive_local(|scoped| { - let content = scoped.content; - scoped.start_room(); - scoped.content = content; - }), - ); + // The content is a layout room of its own: the flow of the body around it does not reach in. It keeps how + // that body sizes from its content, so the view takes what its content used there, as the same content + // shown without the view would. + let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 8963b05df..00c95d128 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -394,12 +394,22 @@ impl Scoped { self.offered = None; } + /// Starts a memoized view's layout room (`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 content, never the + /// open room. + pub(crate) fn start_view_room(&mut self) { + let (content_column, given_column) = (self.content_column, self.given_column); + self.start_room(); + (self.content_column, self.given_column) = (content_column, given_column); + } + /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line /// length, scroll owner and axes), the command chain, motion, the host's formats and date, and every app value. Of - /// the flow fields of the enclosing body only the axes it sizes from its content are in it: a memoized view's - /// content starts a layout room of its own (`start_room`) that keeps those axes. Computed once per scope, on the + /// the flow fields of the enclosing body only how it sizes from its content is in it: a memoized view's content + /// starts a layout room of its own (`start_view_room`) that keeps those facts. Computed once per scope, on the /// first view that asks; the bytes it fed are counted then. pub(crate) fn scope_key(&self) -> u128 { *self.scope_key.get_or_init(|| { @@ -407,6 +417,7 @@ impl Scoped { let mut key = MemoKey::of_view(&self.ctx); key.feed_hash(&(self.enabled, self.read_only, self.size, self.glyphs, self.ink, self.surface, self.wheel)); key.feed_hash(&(self.direction, self.text_direction, self.ids_stable, self.cell_fills, self.least, self.unbounded, self.content)); + key.feed_hash(&(self.content_column, self.given_column)); key.feed_hash(&(self.arena, self.roving, self.item, self.row, self.scroll_owner.map(|owner| (owner.id, owner.view)))); self.transform.map(|transform| (transform.scale, transform.offset)).key(&mut key); self.footer_slot.map(|slot| (slot.owner, slot.size)).key(&mut key); diff --git a/crates/ui-contract/src/runtime/inputs.rs b/crates/ui-contract/src/runtime/inputs.rs index 4c3d8d51c..27f75e78a 100644 --- a/crates/ui-contract/src/runtime/inputs.rs +++ b/crates/ui-contract/src/runtime/inputs.rs @@ -1,5 +1,6 @@ //! Tracked inputs: the framework inputs a view can read outside its props (the modifiers, the pointer, the window's -//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held), each with a generation +//! facts, the keyboard layout, the keymap, a drag, the focus, the open layers, the keys held, the requests to +//! collections), each with a generation //! that moves when its value changes. The accessor that reads one notes it into the records open around the running //! code (`replay::note_input`); a memoized view's replay is refused when an input its run read has another generation //! now (`runtime::lazy::settled`), so a change runs only the views that read it, and a view absent while it changed @@ -34,12 +35,15 @@ pub(crate) enum Input { Focus, /// The layers shown last frame (`overlay::is_open`, `any_open`, `top`, `family`, `entry`). Overlays, + /// The requests to collections from outside them (`items::request_rename`), read by the item step that takes + /// them, so a pending request runs the view that takes it. + Requests, /// The view of the scroll area a nested `Lazy` child decides by. No generation: compared by value. Scroll, } impl Input { - pub(crate) const ALL: [Input; 10] = [ + pub(crate) const ALL: [Input; 11] = [ Input::Modifiers, Input::Pointer, Input::Keys, @@ -49,6 +53,7 @@ impl Input { Input::Drag, Input::Focus, Input::Overlays, + Input::Requests, Input::Scroll, ]; @@ -117,7 +122,7 @@ pub(crate) fn observe(ctx: &Context, input /// The generation `input` has now. The inputs a pass can change while views run (keys, drag, focus, open layers) are /// observed here; the pointer and the modifiers by the pointer's begin hook, the window facts and the layout where -/// the frame's root env is built, the keymap by the command board. +/// the frame's root env is built, the keymap by the command board, the requests by each request. pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { match input { Input::Keys => observe(ctx, input, crate::runtime::keys::keys_state(ctx)), @@ -125,7 +130,7 @@ pub(crate) fn generation(ctx: &Context, input: Input) -> u64 { Input::Focus => observe(ctx, input, crate::runtime::focus::focus_state(ctx)), Input::Overlays => observe(ctx, input, crate::runtime::overlay::open_state(ctx)), Input::Keymap => return crate::runtime::commands::keymap_built(ctx), - Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Scroll => {} + Input::Modifiers | Input::Pointer | Input::Shell | Input::Keyboard | Input::Requests | Input::Scroll => {} } with(ctx, |generations| generations.gens[input as usize]) } diff --git a/crates/ui-patterns/src/patterns/presets/browser.rs b/crates/ui-patterns/src/patterns/presets/browser.rs index 1ca9ff484..d343f32d3 100644 --- a/crates/ui-patterns/src/patterns/presets/browser.rs +++ b/crates/ui-patterns/src/patterns/presets/browser.rs @@ -217,6 +217,9 @@ pub struct PresetBrowser<'a, K: Clone + Eq + Hash + Send + Sync + MemoProps + 's drop_zone: Option, extra_items: Vec>, actions: Vec

{ /// restoring creates a new group, column, dock or window for the panel. #[serde(default)] pub group: Option, + /// The panels of its group that closed in the same batch of actions, itself included, in group order; empty + /// when it closed alone. Reopening any of them brings back the others that are still hidden and were closed with + /// it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub closed_with: Vec

, } /// Groups, columns and floating windows are named by a panel they contain. @@ -340,7 +345,7 @@ pub enum Action

{ impl

Location

{ /// A location relative to `anchor` by `placement`, with no recorded sizes or siblings. pub fn new(anchor: Option

, placement: DockPlacement

) -> Self { - Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None } + Self { floating: None, anchor, placement, size: None, stack: None, sibling: Vec::new(), group: None, closed_with: Vec::new() } } } diff --git a/crates/behavior/src/dock/inner.rs b/crates/behavior/src/dock/inner.rs index bb620b8f5..93510d78a 100644 --- a/crates/behavior/src/dock/inner.rs +++ b/crates/behavior/src/dock/inner.rs @@ -554,7 +554,7 @@ pub(super) fn group_location(panels: &[P], panel: &P) -> Option(node: &Node

) -> Option<&P> { diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 5aba1f0b5..6f18bf113 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -12,7 +12,7 @@ use super::{ DockSide, action::{Action, DockPlacement, Location}, edit::tree_panels, - groups::{Column, DockEdge, PanelPlace, Target}, + groups::{Column, DockEdge, PanelPlace, Target, Unit}, layout::Layout, limits::MAX_PANELS, node::Node, @@ -163,7 +163,7 @@ impl

Workspace

{ impl Workspace

{ /// Check the version, the layout, that every hidden panel is hidden once and absent - /// from the layout, and that the floated records are bounded and one per panel. + /// from the layout and its record is bounded, and that the floated records are bounded and one per panel. pub fn validate(&self) -> Result<(), DockError> { if self.version > Self::VERSION { return Err(DockError::UnsupportedVersion); @@ -174,10 +174,13 @@ impl Workspace

{ } let visible: HashSet<&P> = self.layout.panels().into_iter().collect(); let mut seen = HashSet::new(); - for (panel, _) in &self.hidden { + for (panel, location) in &self.hidden { if visible.contains(panel) || !seen.insert(panel) { return Err(DockError::DuplicatePanel); } + if location.closed_with.len() > MAX_PANELS { + return Err(DockError::LimitExceeded); + } } if self.floated.len() > MAX_PANELS { return Err(DockError::LimitExceeded); @@ -211,8 +214,11 @@ impl Workspace

{ let policy = |panel: &P| if locked { permissions(panel).locked() } else { permissions(panel) }; let mut proposed = self.clone(); let mut all_closed = Vec::new(); + // The group of each panel as it closes, in closing order. + let mut closing_groups = Vec::new(); for action in actions { let closed = proposed.layout.closed_by(&action)?; + closing_groups.extend(closed.iter().map(|panel| proposed.layout.members(panel, Unit::Group).unwrap_or_else(|_| vec![panel.clone()]))); let locations = close_locations(&proposed.layout, &closed); let before = proposed.layout.clone(); // Opening a hidden panel puts it back where it was. @@ -240,6 +246,7 @@ impl Workspace

{ proposed.hidden.retain(|(p, _)| !visible.contains(p)); let mut seen = HashSet::new(); all_closed.retain(|p| !visible.contains(p) && seen.insert(p.clone())); + proposed.record_closed_together(&all_closed, &closing_groups); proposed.validate()?; let Workspace { layout, hidden, floated, .. } = proposed; (self.layout, self.hidden, self.floated) = (layout, hidden, floated); @@ -248,10 +255,11 @@ impl Workspace

{ } /// Show or hide one panel. Showing restores its recorded location, following the chain of - /// hidden anchors when its own anchor is hidden too; otherwise it opens as - /// [`Action::Open`] with `fallback` as the anchor, following `permissions`. The hidden - /// panels on that chain reopen beside it later, so a group or window closed one panel at a - /// time comes back as one. + /// hidden anchors when its own anchor is hidden too, and brings back the hidden panels of its + /// group that closed with it in one batch (Close Tab Group, a preset) as tabs of its group; + /// otherwise it opens as [`Action::Open`] with `fallback` as the anchor, following + /// `permissions`. The other hidden panels on that chain reopen beside it later, so a group or + /// window closed one panel at a time comes back as one. /// A shown panel becomes the active tab of its group. Hiding follows `permissions` and /// `locked`, as [`Self::apply`] does, so a protected canvas stays shown. pub fn set_visible( @@ -276,29 +284,91 @@ impl Workspace

{ self.apply_all([open, Action::Activate { panel }], locked, permissions).map(drop) } - /// Restore a hidden `panel` to its recorded place and make it the active tab. `Ok(false)` when the record - /// cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace stays - /// as it was and the caller opens the panel by the ordinary, checked path. + /// Restore a hidden `panel` to its recorded place, with the hidden panels closed with it, and make it the + /// active tab. The set is restored in group order, each panel by its own record, so the group comes back in + /// the order it had; a panel closed with it whose place refuses it stays hidden. `Ok(false)` when `panel`'s + /// record cannot be restored, or the place it restores to refuses the panel under `permissions`; the workspace + /// stays as it was and the caller opens the panel by the ordinary, checked path. fn reopen(&mut self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Result { - // The restore also rewrites the records of the hidden panels it passed, so it runs on a copy. + let mut restored = self.clone(); + for member in self.closed_together(panel) { + match restored.restored(&member, permissions) { + Some(next) => restored = next, + None if &member == panel => return Ok(false), + None => {} + } + } + restored.layout.apply(Action::Activate { panel: panel.clone() })?; + self.layout = restored.layout; + self.hidden = restored.hidden; + Ok(true) + } + + /// The workspace with the hidden `panel` restored to its recorded place, `None` when the record cannot be + /// restored or the place refuses the panel under `permissions`. The restore also rewrites the records of the + /// hidden panels it passed, so it runs on a copy. + fn restored(&self, panel: &P, permissions: &impl Fn(&P) -> Permissions) -> Option { let mut trial = self.clone(); let mut layout = self.layout.clone(); - if trial.restore_from_hidden(&mut layout, panel).is_err() { - return Ok(false); - } + trial.restore_from_hidden(&mut layout, panel).ok()?; let allowed = layout .location(panel) .ok() .and_then(|location| location.anchor.map(|anchor| location.placement.allowed_by(permissions(&anchor)))) .unwrap_or(true); if !allowed || layout.breaks_columns_beyond(&self.layout, permissions) { - return Ok(false); + return None; + } + trial.layout = layout; + trial.hidden.retain(|(p, _)| p != panel); + Some(trial) + } + + /// The hidden `panel` and the hidden panels closed with it, in group order: those its record's + /// [`closed_with`](Location::closed_with) names whose own records name it back. A panel that closed again on + /// its own since names it no more. `[panel]` when it closed alone. + fn closed_together(&self, panel: &P) -> Vec

{ + let record = |p: &P| self.hidden.iter().find(|(q, _)| q == p).map(|(_, location)| location); + let mut seen = HashSet::new(); + let together: Vec

= record(panel) + .map(|location| &location.closed_with[..]) + .unwrap_or_default() + .iter() + .filter(|&p| p == panel || record(p).is_some_and(|location| location.closed_with.contains(panel))) + .filter(|&p| seen.insert(p)) + .cloned() + .collect(); + if together.len() > 1 && together.contains(panel) { together } else { vec![panel.clone()] } + } + + /// Records on the hidden panels `closed`, which this batch closed, the panels of their group that closed with + /// them. `groups` holds each closing panel's group as it closed, in closing order. The closed panels of one + /// group, or of groups that share one, form one set in the order the groups name them. + fn record_closed_together(&mut self, closed: &[P], groups: &[Vec

]) { + let closed: HashSet<&P> = closed.iter().collect(); + let mut sets: Vec> = Vec::new(); + for group in groups { + let members: Vec<&P> = group.iter().filter(|p| closed.contains(p)).collect(); + let (joined, rest): (Vec>, Vec>) = + std::mem::take(&mut sets).into_iter().partition(|set| set.iter().any(|p| members.contains(&p))); + let mut set: Vec

= joined.into_iter().flatten().collect(); + for panel in members { + if !set.contains(panel) { + set.push(panel.clone()); + } + } + sets = rest; + if !set.is_empty() { + sets.push(set); + } + } + for set in sets.into_iter().filter(|set| set.len() > 1) { + for (panel, location) in &mut self.hidden { + if set.contains(panel) { + location.closed_with.clone_from(&set); + } + } } - layout.apply(Action::Activate { panel: panel.clone() })?; - self.layout = layout; - self.hidden = trial.hidden; - self.hidden.retain(|(p, _)| p != panel); - Ok(true) } /// Update the floated records after an action that turned `before` into the current layout: drop the records of diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index c4461067d..b3bad10d0 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -188,6 +188,42 @@ fn opening_a_closed_floating_panel_restores_its_window_place() { assert_eq!(group_members(workspace.layout(), 11), [11, 12, 50]); } +/// The active tab of the dock or floating group holding `panel`. +fn front(layout: &Layout, panel: u32) -> u32 { + *layout.group(&layout.place(&panel).unwrap()).unwrap().active_panel().unwrap() +} + +/// Tabs closed in one batch (one at a time, as a preset does, or by Close Tab Group) come back together with whichever +/// of them reopens, in their order and with that one in front, after a save and a load; a tab closed in a batch of its +/// own stays closed. +#[test] +fn tabs_closed_together_reopen_together_and_a_tab_closed_alone_stays_closed() { + let batches = [vec![Action::close(2), Action::close(3)], vec![Action::close(3), Action::close(2)], vec![Action::close_group(2)]]; + for batch in batches { + for open in [2, 3] { + let mut workspace = Workspace::new(docked()); + workspace.apply_all(batch.clone(), false, allow).unwrap(); + let saved = serde_json::to_string(&workspace).unwrap(); + let mut workspace: Workspace = serde_json::from_str(&saved).unwrap(); + workspace.apply(Action::open(open, None), false, allow).unwrap(); + let layout = workspace.layout(); + assert_eq!(group_members(layout, open), [2, 3], "{batch:?}, then {open} opens"); + assert_eq!(front(layout, open), open, "{batch:?}: the reopened tab is in front"); + assert_eq!(end_dock(layout)[0].groups[0].panels, [2, 3], "{batch:?}: back above 4 in its column"); + assert!(workspace.hidden().is_empty()); + } + } + + let mut workspace = Workspace::new(docked()); + workspace.apply(Action::close(3), false, allow).unwrap(); + workspace.apply(Action::close(2), false, allow).unwrap(); + workspace.apply(Action::open(2, None), false, allow).unwrap(); + assert_eq!(group_members(workspace.layout(), 2), [2]); + assert!(workspace.layout().place(&3).is_none(), "3 closed on its own stays closed"); + workspace.apply(Action::open(3, None), false, allow).unwrap(); + assert_eq!(group_members(workspace.layout(), 2), [2, 3], "it reopens beside 2"); +} + /// A panel that floats keeps its docked place until it docks or closes; floating again from the float keeps the first. #[test] fn a_floated_panel_keeps_where_it_was_docked_until_it_docks_or_closes() { From 212617056557eff5463c0d6ca0ca3d5c20f3aa65 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 07:48:59 +0000 Subject: [PATCH 33/74] Overlay placement: a context menu that fits neither side covers its anchor (photocraft#15552) PlaceRequest gains covers_anchor. Below or above the anchor, an overlay with it that fits on neither side but fits the bounds keeps the preferred side and its height and slides over the anchor; only one taller than the bounds is capped. The overlay host sets it for a layer hanging from the pointer or from the rect a context request named, so placement's room and the first pass's content room are the cap within the bounds, and the menu shows every row without scroll strips. Dropdowns, menu-bar menus and submenus keep their rule. --- crates/behavior/src/overlay.rs | 40 ++++++++++++++-- .../ui-contract/src/contract/overlay/host.rs | 10 ++-- .../src/contract/overlay/opener.rs | 10 ++++ .../src/contract/overlay/placement.rs | 47 +++++++++++++------ crates/ui-widgets/tests/it/menu/overflow.rs | 41 +++++++++++++++- 5 files changed, 123 insertions(+), 25 deletions(-) diff --git a/crates/behavior/src/overlay.rs b/crates/behavior/src/overlay.rs index 84b75ee02..365078a3b 100644 --- a/crates/behavior/src/overlay.rs +++ b/crates/behavior/src/overlay.rs @@ -97,6 +97,10 @@ pub struct PlaceRequest { /// Beside the anchor, the overlay lines up with the anchor's other end when it runs past the bounds from the /// aligned end and fits from the other, instead of sliding: a submenu of a low row opens upward. pub flips_across: bool, + /// Below or above the anchor, an overlay that fits on neither side but fits the bounds keeps its height and slides + /// over the anchor from the preferred side; only one taller than the bounds is capped. For a context menu, whose + /// anchor is a point or a row. + pub covers_anchor: bool, } impl PlaceRequest { @@ -113,6 +117,7 @@ impl PlaceRequest { bounds, kept: None, flips_across: false, + covers_anchor: false, } } @@ -163,6 +168,12 @@ impl PlaceRequest { self.flips_across = on; self } + + /// Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds. + pub const fn covers_anchor(mut self, on: bool) -> Self { + self.covers_anchor = on; + self + } } /// Where `place` put the overlay. @@ -200,9 +211,10 @@ fn room(anchor: Rect, bounds: Rect, side: Side, rtl: bool, gap: f32) -> f32 { } /// Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to -/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Beside the anchor, a request that -/// flips across lines up with the anchor's other end when it runs past the bounds from the aligned end and fits from the -/// other. The rect is always finite and inside the bounds. +/// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Below or above the anchor, a +/// request that covers its anchor and fits neither side keeps the preferred side and its height up to the bounds' and +/// slides over the anchor. Beside the anchor, a request that flips across lines up with the anchor's other end when it +/// runs past the bounds from the aligned end and fits from the other. The rect is always finite and inside the bounds. pub fn place(request: &PlaceRequest) -> Placement { let anchor = clean(request.anchor); let bounds = clean(request.bounds); @@ -213,12 +225,15 @@ pub fn place(request: &PlaceRequest) -> Placement { let need = if request.side.vertical() { wanted.y } else { wanted.x }; let preferred = room(anchor, bounds, request.side, rtl, gap); let other = room(anchor, bounds, request.side.flipped(), rtl, gap); + let covers = request.covers_anchor && request.side.vertical(); let side = match request.kept { Some(kept) => kept, None if preferred >= need || preferred >= other => request.side, + None if covers && other < need => request.side, None => request.side.flipped(), }; - let available = room(anchor, bounds, side, rtl, gap).max(0.0); + // Covering the anchor, the overlay may take the bounds' height: the shift inside them moves it over the anchor. + let available = if covers { bounds.height() } else { room(anchor, bounds, side, rtl, gap).max(0.0) }; let size = if side.vertical() { Vec2::new(wanted.x.min(bounds.width()), wanted.y.min(available).min(bounds.height())) } else { @@ -275,6 +290,20 @@ mod tests { assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside"); } + #[test] + fn a_menu_that_covers_its_anchor_and_fits_neither_side_keeps_its_height_and_slides_over_the_anchor() { + let point = rect(300.0, 400.0, 0.0, 0.0); + let request = PlaceRequest::new(point, Vec2::new(200.0, 450.0), BOUNDS).covers_anchor(true); + let placed = place(&request).rect; + assert_eq!(placed.height(), 450.0, "fits the bounds: its whole height"); + assert!(BOUNDS.contains_rect(placed) && placed.top() < point.top(), "slides up over the point: {placed:?}"); + assert_eq!(place(&request.size(Vec2::new(200.0, 700.0))).rect.height(), BOUNDS.height(), "taller than the bounds: capped"); + let above = place(&request.size(Vec2::new(200.0, 350.0))); + assert!(above.side == Side::Above && above.rect.bottom() == point.top(), "fits above: opens above the point: {above:?}"); + let without = place(&request.covers_anchor(false)); + assert!(without.side == Side::Above && without.rect.height() < 450.0, "without it: capped to the larger side: {without:?}"); + } + #[test] fn an_overlay_at_least_as_wide_as_its_anchor_takes_that_width_below_it_but_not_beside_it() { let field = rect(100.0, 100.0, 300.0, 24.0); @@ -298,7 +327,8 @@ mod tests { .side(side) .align(align) .rtl(i % 2 == 0) - .gap(if i == 1 { 4.0 } else { 0.0 }); + .gap(if i == 1 { 4.0 } else { 0.0 }) + .covers_anchor(align != Align::Start); let placed = place(&request).rect; assert!(placed.min.is_finite() && placed.max.is_finite(), "{request:?}"); assert!(BOUNDS.contains_rect(placed), "{request:?} gave {placed:?}"); diff --git a/crates/ui-contract/src/contract/overlay/host.rs b/crates/ui-contract/src/contract/overlay/host.rs index a37aa15b5..5d540cd9e 100644 --- a/crates/ui-contract/src/contract/overlay/host.rs +++ b/crates/ui-contract/src/contract/overlay/host.rs @@ -3,7 +3,7 @@ use super::dismissal::{dismissal, popup_dismissal}; use super::opener::{Opening, Trigger}; use super::place::{OverlayFit, Place}; -use super::placement::{anchor_rect, opened_overlay, placement}; +use super::placement::{anchor_rect, layer_covers_anchor, opened_overlay, placement}; use super::props::{Outside, Overlay}; use crate::runtime::access::{self}; use crate::runtime::egui::areas::{self, LayerSpec}; @@ -134,6 +134,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U if let Some((_, opening)) = &opened { memory.opening.get_or_insert(*opening); } + let covers = layer_covers_anchor(ctx, layer.overlay, memory.opening); let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), ..*layer }; let overlay = layer.overlay; let bounds = layer.region.map_or_else(|| areas::safe_rect(ctx), |region| region.intersect(areas::safe_rect(ctx))); @@ -155,7 +156,7 @@ pub(crate) fn host(ctx: &Context, layer: &Layer<'_>, body: &mut dyn FnMut(&mut U Some(size) => Some(egui::vec2(size.x.max(min_width), size.y)), None => areas::layer_rect(ctx, area).map(|rect| rect.size()), }; - let mut placed = placement(ctx, layer, size, bounds, anchor); + let mut placed = placement(ctx, layer, covers, size, bounds, anchor); let nudge = Nudge::of(ctx, layer, appears); if let Some(nudge) = &nudge { placed.at += nudge.offset(); @@ -275,6 +276,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut if let Some((_, opening)) = &opened { memory.opening.get_or_insert(*opening); } + let covers = layer_covers_anchor(ctx, layer.overlay, memory.opening); // The popup window lies outside any region of the opener: the work area is its room. let layer = &Layer { overlay: opened.as_ref().map_or(layer.overlay, |(overlay, _)| overlay), region: None, ..*layer }; let overlay = layer.overlay; @@ -282,7 +284,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut let anchor = anchor_rect(ctx, layer, bounds, &mut memory); let min_width = overlay.least_width(anchor.width()); let measured = layer.size.map(|size| egui::vec2(size.x.max(min_width), size.y)); - let unplaced = placement(ctx, layer, measured, bounds, anchor); + let unplaced = placement(ctx, layer, covers, measured, bounds, anchor); let parent = overlay::drawing_parent(ctx); let tier = overlay::layer_tier(ctx, overlay.rank); let scope = (overlay.focus != FocusPolicy::NONE).then_some(overlay.focus); @@ -302,7 +304,7 @@ fn host_in_popup(ctx: &Context, layer: &Layer<'_>, popup: PopupRoom, body: &mut shown = Some(show_in_popup(ui, layer, &unplaced, min_width, scope, &mut memory, &mut *body)); }); let (size, dismissed) = shown.unwrap_or((measured.unwrap_or_default(), None)); - let placed = if known.is_some() { unplaced } else { placement(ctx, layer, Some(size), bounds, anchor) }; + let placed = if known.is_some() { unplaced } else { placement(ctx, layer, covers, Some(size), bounds, anchor) }; let rect = Rect::from_min_size(placed.at, size); if known.is_none() { windows::place_popup(ctx, layer.id, rect.translate(popup.origin.to_vec2())); diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index d00d8c6fd..fbd2677a5 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -178,6 +178,16 @@ impl crate::runtime::env::EnvValue for LayerFloor { } } +/// Whether a layer opened by `opener` may cover the anchor [`opener_anchor`] gives it: the pointer, or the rect a context +/// request named. Both are a context menu's anchor, a point or a row. +pub(super) fn covers_anchor(opener: &Opener, opening: Opening, place: &Place) -> bool { + match opener_anchor(opener, opening, place) { + Anchor::Pointer => true, + Anchor::Rect(_) => opener.anchor.is_none() && matches!(opening, Opening::At(_)), + _ => false, + } +} + /// The anchor a layer opened by `opener` hangs from: the opener's own, else the layer's `Pointer` or `Corner` /// place, else the pointer for a context request a secondary release made, else the rect a key's context request /// named, else the opener's rect. diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 526a2fdda..d8be6a235 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -1,7 +1,7 @@ //! Where a shown layer goes: its anchor, the region and screen it stays in, and the room its body has. use super::host::{Layer, LayerMemory, memory_slot}; -use super::opener::{Opening, opener_anchor}; +use super::opener::{Opening, covers_anchor, opener_anchor}; use super::place::{Anchor, OverlayFit, Place, ViewportShare}; use super::props::Overlay; use crate::runtime::egui::areas::{self}; @@ -51,6 +51,18 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option) -> bool { + match &overlay.opener { + Some(first) => { + let (opener, opening) = first.active(ctx, stored); + covers_anchor(opener, opening, &overlay.place) + } + None => matches!(overlay.place, Place::Anchored { anchor: Anchor::Pointer, .. }), + } +} + /// The opening the layer `id` decided when it appeared, `None` before the host has run for it. fn stored_opening(ctx: &Context, id: Id) -> Option { MemoryStage::peek::(ctx, memory_slot(id)).opening @@ -172,7 +184,9 @@ pub(crate) fn measuring_room( inset: f32, rtl: bool, ) -> Option { - let opened = opened_overlay(ctx, overlay, stored_opening(ctx, id)); + let stored = stored_opening(ctx, id); + let covers = layer_covers_anchor(ctx, overlay, stored); + let opened = opened_overlay(ctx, overlay, stored); let overlay = opened.as_ref().map_or(overlay, |(overlay, _)| overlay); if !matches!(overlay.place, Place::Anchored { .. }) { return None; @@ -183,7 +197,7 @@ pub(crate) fn measuring_room( let bounds = screen_for(ctx, env, overlay); let resolved = resolve_anchor(ctx, id, overlay, own, own_to_screen); let anchor = resolved_anchor(ctx, overlay, resolved, bounds, inset, &mut MemoryStage::peek::(ctx, memory_slot(id)).pointer_at); - Some(content_room(overlay, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl)) + Some(content_room(overlay, covers, bounds, kept_in(overlay, resolved, bounds, inset), anchor, rtl)) } /// The most a layer's body may take: the fit's share of the safe rect `bounds`, at least as wide as the layer's @@ -198,13 +212,13 @@ fn cap(overlay: &Overlay, bounds: Rect, anchor: Rect) -> egui::Vec2 { } /// The room a layer offers its content before it is placed: the cap (a share of the safe rect `bounds`), and for an -/// anchored layer the cap within the larger side of its anchor along the side's axis, inside `kept` (`kept_in`). -/// Content measured in it fits wherever `placement` puts it: on its preferred side when it fits there, else on the -/// larger side. -pub(crate) fn content_room(overlay: &Overlay, bounds: Rect, kept: Rect, anchor: Rect, rtl: bool) -> egui::Vec2 { +/// anchored layer the cap within the larger side of its anchor along the side's axis, inside `kept` (`kept_in`), or +/// within `kept` for a layer that `covers` its anchor. Content measured in it fits wherever `placement` puts it: on its +/// preferred side when it fits there, else on the larger side, or over the anchor. +pub(crate) fn content_room(overlay: &Overlay, covers: bool, bounds: Rect, kept: Rect, anchor: Rect, rtl: bool) -> egui::Vec2 { let cap = cap(overlay, bounds, anchor); let Place::Anchored { side, .. } = &overlay.place else { return cap.min(bounds.size()) }; - let request = PlaceRequest::new(anchor, cap, kept).side(*side).rtl(rtl).min_width(overlay.min_width); + let request = PlaceRequest::new(anchor, cap, kept).side(*side).rtl(rtl).min_width(overlay.min_width).covers_anchor(covers); let on = |side: Side| craft_behavior::overlay::place(&request.kept(Some(side))).rect.size(); let (vertical, other) = match side { Side::Below => (true, Side::Above), @@ -228,17 +242,18 @@ pub(super) struct Placed { /// The pure placement of the anchored forms; the centre or the given position for floats, kept inside the safe rect /// within the overlay's bounds (`within_bounds`) by the keep rule moves follow. An anchored layer takes its side by its /// size: below its anchor, above when the room below is too short and the room above is larger, and keeps that side -/// while it stays open and the content fits there or that side is the larger. Before its size is known (a popup's -/// first, hidden pass) it takes no side and its body is offered `content_room`, so the size it measures decides the -/// side. -pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option, bounds: Rect, anchor: Rect) -> Placed { +/// while it stays open and the content fits there or that side is the larger. A layer that `covers` its anchor +/// ([`layer_covers_anchor`]) and fits neither side keeps its height within the bounds and slides over the anchor. +/// Before its size is known (a popup's first, hidden pass) it takes no side and its body is offered `content_room`, so +/// the size it measures decides the side. +pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, covers: bool, size: Option, bounds: Rect, anchor: Rect) -> Placed { let rtl = layer.env.direction.is_rtl(); let cap = cap(layer.overlay, bounds, anchor); match &layer.overlay.place { Place::Anchored { side, align, flips_across, .. } => { let kept = layer_bounds(layer, bounds); let Some(size) = size else { - let room = content_room(layer.overlay, bounds, kept, anchor, rtl); + let room = content_room(layer.overlay, covers, bounds, kept, anchor, rtl); return Placed { at: anchor.left_bottom().clamp(kept.min, kept.max), side: None, room }; }; // The side taken in an earlier pass is the preferred one while the layer stays open: it stays while the @@ -249,9 +264,11 @@ pub(super) fn placement(ctx: &Context, layer: &Layer<'_>, size: Option (Fixture, Id, egui::Pos2) { + let menu = Rc::new(Cell::new(None)); + let seen = Rc::clone(&menu); + let mut fixture = Fixture::new(move |ui| { + ui.add_space(top); + let target = Button::new("Target").show(ui); + let shown = Menu::context("Target menu", &target).show(ui, |ui, _| { + for at in 0..rows { + MenuItem::new(row(at)).show(ui); + } + }); + seen.set(Some(shown.output.response.id)); + }); + fixture.settle(); + let at = fixture.by_label("Target").expect("the target").center(); + fixture.frame(vec![pointer::moved(at)]); + fixture.frame(vec![pointer::secondary(at, true)]); + fixture.frame(vec![pointer::secondary(at, false)]); + fixture.settle(); + (fixture, menu.get().expect("the menu's id"), at) +} + +#[trial] +fn a_context_menu_too_tall_for_either_side_of_the_pointer_covers_it_and_shows_every_row_without_strips() { + let rows = 18; + let (fixture, menu, at) = context_menu(290.0, rows); + let room = fixture.ctx().content_rect(); + let rect = menu_rect(&fixture); + assert!(strips(&fixture, menu).is_none(), "the menu {rect:?} fits the window {room:?}: no strips"); + let (first, last) = (fixture.by_label(&row(0)).expect("the first row").rect, fixture.by_label(&row(rows - 1)).expect("the last row").rect); + let tall = last.bottom() - first.top(); + assert!(tall > at.y - room.top() && tall > room.bottom() - at.y, "the rows ({tall}) fit on neither side of the pointer at {at:?}"); + assert!(room.contains_rect(rect), "the menu {rect:?} stays inside the window {room:?}"); + assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}"); +} + /// A menu of `above` rows over a submenu row whose submenu has `rows` rows, in the fixture's 800 x 600 window. fn low_submenu(above: usize, rows: usize) -> Fixture { let mut fixture = Fixture::new(move |ui| { From 3a8c030cc4f5597ae41927d2727bdeb99894b5ce Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 07:49:27 +0000 Subject: [PATCH 34/74] Pictures sized from their least are held children of a content column A picture (`MeasureCx::picture_width`) in a content-sized Stack column takes its least in the column's measuring run, which offers no room, and shows across the width the column settles on. A square picture was then taller in the real run than its column had measured it, and everything under it was pushed past the column's end: the Curves dialog lost its tone bar, the Input/Output fields and the hint (photocraft#15543). Such a picture now reports itself held in the column's first sweep, in the same held record fill-width children use, with its kind (`HeldKind::Picture`). The column sweeps again at its settled width, where the picture is offered that width as room, so it measures at the width it shows. This covers the colour wheel and disc too. Trials: the hosted Curves dialog shows the graph with its tone bar, Input, Output and the hint inside the dialog; a square picture in a content column pushes what follows below its shown size; a column sweeps again only for a picture narrower than it. --- crates/imaging/tests/it/hosted_dialogs.rs | 52 ++++++++- crates/ui-contract/src/contract/body/hooks.rs | 6 +- crates/ui-contract/src/contract/cx/measure.rs | 17 ++- crates/ui-contract/src/contract/run.rs | 11 +- crates/ui-contract/src/layout/body.rs | 70 ++++++++---- crates/ui-contract/src/layout/mod.rs | 8 +- crates/ui-contract/src/runtime/env.rs | 6 +- crates/ui-contract/src/runtime/env/view.rs | 8 ++ .../ui-contract/src/runtime/layout_memory.rs | 2 +- crates/ui-contract/tests/it/layout/body.rs | 102 ++++++++++++++++++ 10 files changed, 240 insertions(+), 42 deletions(-) diff --git a/crates/imaging/tests/it/hosted_dialogs.rs b/crates/imaging/tests/it/hosted_dialogs.rs index e4d53e6c7..e4aa06ae2 100644 --- a/crates/imaging/tests/it/hosted_dialogs.rs +++ b/crates/imaging/tests/it/hosted_dialogs.rs @@ -5,8 +5,10 @@ use std::cell::RefCell; use std::rc::Rc; use craft_imaging::layer_style::{EffectId, EffectInstance, EffectKind, LayerStyle, LayerStyleDraft, LayerStylePage, StyleParams}; -use craft_imaging::ui::adjust::{BrightnessContrast, BrightnessContrastEditor, HostedAdjustDialog}; +use craft_imaging::ui::adjust::{BrightnessContrast, BrightnessContrastEditor, CurvesPanel, HostedAdjustDialog, ToneChannels, ToneCurves, ToneSpace}; +use craft_imaging::ui::curve::Curve; use craft_imaging::ui::layer_style::{HostedLayerStyle, LayerStyleAsk}; +use craft_ui::contract::Role; use craft_ui::dialog::{DialogHost, DialogResult, HeldOk, StackDialog, dialog_id}; use craft_ui::runtime::env::Label; use craft_ui::testing::{Fixture, trial}; @@ -226,3 +228,51 @@ fn a_held_adjustment_ok_refused_stays_open_and_an_accepted_one_closes() { let answered = host.borrow_mut().take_keyed::().and_then(|(result, _)| result.ok()).map(|value| value.brightness); assert_eq!(answered, Some(5.0), "the accepted OK closes the dialog with the held value"); } + +/// The Curves value of the dialog trial: three points on the composite curve. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +struct Curves(ToneCurves); + +impl Default for Curves { + fn default() -> Self { + let mut curves = ToneCurves::identity(&ToneChannels::of(ToneSpace::Rgb, false)); + curves.curves[0] = Curve::smooth(vec![[0.0, 0.0], [128.0, 160.0], [255.0, 255.0]]); + Curves(curves) + } +} + +type CurvesDialog = HostedAdjustDialog; + +// The dialog sizes its content column from what the editor takes, and the graph is a square picture that shows across +// that column: everything under it (its tone bar, the selected point's Input and Output, the hint) lies inside the +// dialog, not pushed past its edge. +#[trial] +fn the_curves_dialog_shows_the_tone_bar_the_point_fields_and_the_hint() { + let host = Rc::new(RefCell::new(DialogHost::new())); + let mut fixture = fixture(&host); + host.borrow_mut().open(CurvesDialog::new("image.adjustments.curves", "Curves", Curves::default(), |ui, value, cx| { + let mut panel = + CurvesPanel::new("Curves", craft_ui::contract::Bind::bound(&mut value.0), ToneChannels::of(ToneSpace::Rgb, false)).context(cx.context); + if let Some(point) = cx.select_point { + panel = panel.select(point); + } + let _ = panel.show(ui); + None + })); + fixture.idle(10); + if let Some(dialog) = host.borrow_mut().get_mut::() { + dialog.select_point(1); + } + fixture.settle(); + let dialog = fixture.by_role(Role::DIALOG).first().map(|dialog| dialog.rect).expect("the Curves dialog shows"); + let point = fixture.by_label("Point 2 of 3").expect("the middle point"); + let tree = fixture.tree(); + let graph = tree.parent_of_key(point.node).and_then(|graph| tree.bounds_of(graph)).expect("the graph holds its points"); + let input = fixture.by_label("Input").expect("the Input field").rect; + let output = fixture.by_label("Output").expect("the Output field").rect; + let hint = fixture.texts().iter().find(|text| text.text.starts_with("Click to add a point")).expect("the hint is painted").rect; + for (part, rect) in [("the graph and its tone bar", graph), ("Input", input), ("Output", output), ("the hint", hint)] { + assert!(dialog.contains_rect(rect), "{part} {rect:?} lies inside the dialog {dialog:?}"); + } + assert!(input.top() >= graph.bottom() && hint.top() >= input.bottom(), "graph, fields, hint top to bottom: {graph:?} {input:?} {hint:?}"); +} diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 70f69657c..26a4ac93f 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -295,7 +295,7 @@ impl ShapeHooks for BodyHooks<'_> { 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.across = self.held && matches!(env.column, Some(ColumnSweep::Column(..))); self.in_column = label::in_column(ui); self.given.1 |= self.over_room(props, &env, at, ui.ctx(), id); let measured = self.measured_body.unwrap_or(Vec2::ZERO); @@ -1827,9 +1827,9 @@ impl BodyHooks<'_> { self.fixed_height = self.fixed_height(&props, at.at); self.passes = self.passes_width(&props, at.env, at.at); self.held = self.held(&props, at.env); - self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(_))); + self.across = self.held && matches!(at.env.column, Some(ColumnSweep::Column(..))); // A held container across its column measures at the column's width. - if let Some(ColumnSweep::Column(width)) = at.env.column.filter(|_| self.across && at.width.is_none()) { + if let Some(ColumnSweep::Column(_, width)) = at.env.column.filter(|_| self.across && at.width.is_none()) { self.room.x = width; } self.in_column = label::in_column(at.ui); diff --git a/crates/ui-contract/src/contract/cx/measure.rs b/crates/ui-contract/src/contract/cx/measure.rs index de1112200..f5a3d939e 100644 --- a/crates/ui-contract/src/contract/cx/measure.rs +++ b/crates/ui-contract/src/contract/cx/measure.rs @@ -81,12 +81,21 @@ impl MeasureCx<'_, C> { /// The width a picture sizes at (a plot, a wheel, a well): it takes the room it is offered, down to `least` and up /// to `most`. At its least, where the width is unbounded, and in a measuring run of a column that sizes its width /// from its content (which offers no room), it is `least`: a picture needs no width of its own, so it never sets - /// that column's width, and the real run shows it across the width the column settles on. A band picture keeps a - /// height of its own; a square one is as tall as this. + /// that column's width. There it is a held child of the column (`layout::HeldKind::Picture`): when the column + /// settles wider, its second sweep offers the picture that width, so the picture measures at the width it shows. + /// A band picture keeps a height of its own; a square one is as tall as this. pub fn picture_width(&self, least: f32, most: f32) -> f32 { - match self.room.filter(|_| self.proposal != Proposal::Min) { + if self.proposal == Proposal::Min { + return least; + } + match self.room { Some(room) => room.clamp(least, most.max(least)), - None => least, + None => { + if let Some(column) = self.env.column_first_sweep() { + crate::layout::report_held(self.ui.ctx(), column, self.id, crate::layout::HeldKind::Picture, least); + } + least + } } } diff --git a/crates/ui-contract/src/contract/run.rs b/crates/ui-contract/src/contract/run.rs index f495e805f..a2ef6b755 100644 --- a/crates/ui-contract/src/contract/run.rs +++ b/crates/ui-contract/src/contract/run.rs @@ -820,7 +820,7 @@ fn place_root(p: &Pass<'_, '_, '_>, ui: &mut Ui, at: ShowAt, env: &Env, size: Ve let flowed = steps::place(ui, at, Vec2::new(p.measured.x.min(size.x), size.y), InFlow { fill: false, first: first(size.y), line }); // The column's first sweep learns which of its held children measured narrower than it settles on. if let Some(ColumnSweep::Count(column)) = env.column { - crate::layout::report_held(&ctx, column, flowed.width()); + crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Fill, flowed.width()); } let across = Vec2::new(size.x.max(flowed.width()).max(column), flowed.height()); if rtl { Rect::from_min_size(Pos2::new(flowed.max.x - across.x, flowed.min.y), across) } else { Rect::from_min_size(flowed.min, across) } @@ -1570,9 +1570,14 @@ fn room_step(t: &mut dyn Erased, ui: &Ui, at: ShowAt, begun: &Begun) -> Room { let room = match at { ShowAt::Rect(rect) => Some(rect.width()), // A measuring run in a content column asks for what the content needs: nothing there fills the room. Once the - // column settled its width, a child that fills its width measures at that width. + // column settled its width, a child that fills its width, or a picture its first sweep held, measures at + // that width. ShowAt::Flow => match env.column { - Some(ColumnSweep::Column(width)) if env.content_column && t.fills_width() => Some(width), + Some(ColumnSweep::Column(column, width)) + if env.content_column && (t.fills_width() || crate::layout::held_kind(ctx, column, id) == Some(crate::layout::HeldKind::Picture)) => + { + Some(width) + } _ => Some(crate::layout::flow_room(ui).x) .filter(|width| width.is_finite() && !(env.content_column && crate::runtime::measure::active(ctx))), }, diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 39aef7f2b..351d77574 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -137,21 +137,39 @@ pub(crate) struct Cursors(IdMap); #[derive(Default)] pub(crate) struct FillCounts(IdMap); -/// The narrowest width a held fill-width child of each content-sized `Stack` column measured at in the first sweep of -/// the column's measuring run (`report_held`), by column id. -#[derive(Default)] -pub(crate) struct HeldWidths(IdMap); +/// What makes a child of a content-sized `Stack` column a held child: it measures at its own width while the column +/// settles its width from the others, and the column's second sweep gives it the settled width. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum HeldKind { + /// A fill-width child: it shows across the width the column settles on. + Fill, + /// A picture that took its least for want of room (`MeasureCx::picture_width`): it shows at the width it sizes + /// at in the column's width, which may be narrower than the column. + Picture, +} -/// Reports a held fill-width child of the content-sized column `column` in its first sweep: the `width` it measured -/// at. A column with no first sweep open takes no report. -pub(crate) fn report_held(ctx: &egui::Context, column: Id, width: f32) { +/// The held children of each content-sized `Stack` column in its measuring run, by column id: each child's kind and +/// the narrowest width it measured at in the column's first sweep, by child id. +#[derive(Default)] +pub(crate) struct HeldWidths(IdMap>); + +/// Reports a held child `child` of the content-sized column `column` in its first sweep: its kind and the `width` it +/// measured at. A column with no first sweep open takes no report. +pub(crate) fn report_held(ctx: &egui::Context, column: Id, child: Id, kind: HeldKind, width: f32) { pass_state::with::(ctx, |held| { - if let Some(narrowest) = held.0.get_mut(&column) { - *narrowest = narrowest.min(width); + if let Some(children) = held.0.get_mut(&column) { + let entry = children.entry(child).or_insert((kind, width)); + entry.1 = entry.1.min(width); } }); } +/// The kind of the held child `child` of the column `column`, as its first sweep reported it, while the column's +/// second sweep runs. +pub(crate) fn held_kind(ctx: &egui::Context, column: Id, child: Id) -> Option { + pass_state::with::(ctx, |held| held.0.get(&column).and_then(|children| children.get(&child)).map(|(kind, _)| *kind)) +} + /// What the first child a measuring sweep placed in flow in each open target reported (`Scoped::first_line`): the y /// of its first line's centre, or `None` for a child with no line of its own. A container's measuring sweep opens and /// closes its header's and body's targets; a body's sweep starts its own target afresh. @@ -908,13 +926,14 @@ fn measure_sharing(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui:: /// is bounded: each sweep is `run_sharing`'s, with the column's sweep (`ColumnSweep`) in its children's env. It adds no /// `Ui` of its own, so the children have the ids `run_sharing` gives them when the column's width is not bounded. /// -/// A held fill-width child measures at its own width while the column settles its width from the others, so it may -/// measure narrower than it shows. A measuring run sweeps the children once, each held child reporting the width it -/// measured at (`report_held`). When one of them measured narrower than the column settled on, it sweeps them again -/// with that width, at which the held children measure across the column and the others reuse their records; else the -/// first sweep stands, and each held child keeps the record it made at its own width, which is the column's. It -/// records which (`sub(id, "column")`): the real run gives the held children the width the column shows at only after -/// a second sweep, so each shows as its records were made. +/// A held child (`HeldKind`: a fill-width child, or a picture that took its least for want of room) measures at its +/// own width while the column settles its width from the others, so it may measure narrower than it shows. A +/// measuring run sweeps the children once, each held child reporting the width it measured at (`report_held`). When +/// one of them measured narrower than the column settled on, it sweeps them again with that width, at which the held +/// children measure in the column's width and the others reuse their records; else the first sweep stands, and each +/// held child keeps the record it made at its own width, which is the column's. It records which +/// (`sub(id, "column")`): the real run gives the held children the width the column shows at only after a second +/// sweep, so each shows as its records were made. // PLAN: the second sweep's need is decided once for the column, not per held container at body/hooks.rs's reuse // rule: a container that reused its content-sized record there would be laid out across in the real run under records // not made across. @@ -931,29 +950,34 @@ fn run_column(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body: }; if !measure::active(&ctx) { let across = this_pass(&ctx, false, key).is_some_and(|took| took.x > 0.0); - let column = across.then(|| ColumnSweep::Column(flow_room(ui).x)); + let column = across.then(|| ColumnSweep::Column(id, flow_room(ui).x)); return sweep(ui, column, &mut body); } let (inner, rect, again) = crate::contract::keeping_ids(&ctx, || { - pass_state::with::(&ctx, |held| held.0.insert(id, f32::INFINITY)); + pass_state::with::(&ctx, |held| held.0.insert(id, IdMap::default())); let env = column_env(Some(ColumnSweep::Count(id))); let installed = Env::install_for(ui, env.clone()); let (inner, rect) = measure_sharing(ui, &env, id, Axis::Y, layout, &mut body); Env::restore(&ctx, installed); - let narrowest = pass_state::with::(&ctx, |held| held.0.remove(&id)); + let narrowest = pass_state::with::(&ctx, |held| { + held.0.get(&id).map_or(f32::INFINITY, |children| children.values().fold(f32::INFINITY, |least, (_, width)| least.min(*width))) + }); // Half a point: less than a pixel shows at any scale the box runs. - let again = narrowest.is_some_and(|narrowest| narrowest < rect.width() - 0.5); + let again = narrowest < rect.width() - 0.5; ((inner, rect, again), again) }); let column = rect.width(); // 0 when the first sweep stands, so nothing an earlier run of the pass left is read. found(&ctx, true, key, Vec2::ZERO, Vec2::new(if again { column } else { 0.0 }, 0.0)); - if again { - sweep(ui, Some(ColumnSweep::Column(column)), &mut body) + // The second sweep reads the held children's kinds (`held_kind`); the column's record closes after it. + let inner = if again { + sweep(ui, Some(ColumnSweep::Column(id, column)), &mut body) } else { ui.advance_cursor_after_rect(rect); inner - } + }; + pass_state::with::(&ctx, |held| held.0.remove(&id)); + inner } /// What places the children in flow of a body that places them itself. diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index b5fbb0c2e..1301468c2 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -24,8 +24,8 @@ pub use body::place_in_flow; #[cfg(feature = "testing")] pub(crate) use body::run_body; pub(crate) use body::{ - BracketTook, 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, 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, + 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, }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index fd3733682..46b85f384 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -284,9 +284,9 @@ pub(crate) enum ColumnSweep { /// The first sweep of the measuring run of the column `Id`: each held fill-width child reports the width it /// measured at (`layout::report_held`). Count(Id), - /// The width the column settled on, in its second sweep and in the real run after one: a held fill-width child - /// measures and shows across it. - Column(f32), + /// The width the content-sized `Stack` column `Id` settled on, in its second sweep and in the real run after one: + /// a held fill-width child measures and shows across it, and a held picture measures in it. + Column(Id, f32), } /// The line of an unwrapped `Row` body, as its direct children placed in flow see it: a child of one line sits with diff --git a/crates/ui-contract/src/runtime/env/view.rs b/crates/ui-contract/src/runtime/env/view.rs index 42d7cb568..b418809b6 100644 --- a/crates/ui-contract/src/runtime/env/view.rs +++ b/crates/ui-contract/src/runtime/env/view.rs @@ -58,6 +58,14 @@ impl<'a> EnvView<'a> { self.scoped.measure } + /// The content-sized `Stack` column whose first sweep runs now, if the scope is a direct child of it in flow. + pub(crate) fn column_first_sweep(&self) -> Option { + match self.scoped.column { + Some(super::ColumnSweep::Count(column)) => Some(column), + _ => None, + } + } + /// The inside label the scope carries ([`inside_label`](EnvView::inside_label) reads it back). pub(crate) fn inside_held(&self) -> Option<&'a Held> { self.scoped.inside_label.as_ref() diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 3894fd46b..e3bd41318 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -1236,7 +1236,7 @@ pub(crate) mod guard { ("layout::column_group::Open", "column groups: frames the run opens and closes; reports go through contribute"), ("access::scope::Stack", "label and merge scopes: opened and closed by the run; control minimums go through contribute"), ("layout::body::FillCounts", "fill counts: opened and closed by the body's own measuring sweep"), - ("layout::body::HeldWidths", "held widths: opened and closed by the column's own first sweep"), + ("layout::body::HeldWidths", "held children: opened by the column's own first sweep and closed after its last"), ("layout::body::FirstLines", "first lines: opened and closed by the container's own measuring sweep; the line goes through emit_record"), ("layout::body::RowLines", "row lines: opened by each sweep of the row and closed after it; the line goes through emit_record"), ( diff --git a/crates/ui-contract/tests/it/layout/body.rs b/crates/ui-contract/tests/it/layout/body.rs index c5844b134..fcb59a565 100644 --- a/crates/ui-contract/tests/it/layout/body.rs +++ b/crates/ui-contract/tests/it/layout/body.rs @@ -237,6 +237,108 @@ fn a_held_fill_width_child_measures_again_only_when_a_sibling_widens_the_column( assert!(unbounded >= 1 && bounded == 0, "the narrower sibling: the held child measured again: {unbounded} and {bounded}"); } +/// A square picture: as wide as `picture_width` gives it from `least` up to `MOST_PICTURE`, as tall as wide. +#[derive(Component)] +struct Square<'a> { + #[common] + common: Common, + least: f32, + seen: &'a RefCell, + measures: &'a Measures, +} + +/// The widest a `Square` takes. +const MOST_PICTURE: f32 = 1000.0; + +impl Component for Square<'_> { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: SquareStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + if cx.proposal == Proposal::Ideal && is_measuring(cx.ui.ctx()) { + let count = if cx.room.is_some() { &self.measures.bounded } else { &self.measures.unbounded }; + count.set(count.get() + 1); + } + Vec2::splat(cx.picture_width(self.least, MOST_PICTURE)) + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn update(&mut self, cx: &mut Cx<'_, Self>) { + self.seen.borrow_mut().rect = cx.rect; + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +/// What a content-sized column shows with a square picture of least width `least` (none when `None`), a `Wrap` and a +/// probe under them `sibling` wide: the column's rect, the picture's and the probe's, the picture's ideal measures in +/// measuring runs without a room and in one, and the wrap's. +struct PictureColumn { + rects: [Rect; 3], + picture: (usize, usize), + wrap: (usize, usize), +} + +fn picture_in_column(least: Option, sibling: f32) -> PictureColumn { + let (square, under, wrap) = + (Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default()))); + let (pictures, wraps, column) = (Rc::new(Measures::default()), Rc::new(Measures::default()), Rc::new(Cell::new(Rect::NOTHING))); + let (shown_square, shown_under, shown_wrap) = (Rc::clone(&square), Rc::clone(&under), Rc::clone(&wrap)); + let (counted_pictures, counted_wraps, shown_column) = (Rc::clone(&pictures), Rc::clone(&wraps), Rc::clone(&column)); + let mut fixture = Fixture::new(move |ui| { + let shown = Panel::new().id_salt("column").show(ui, |ui, _| { + if let Some(least) = least { + Square { common: Common::new(), least, seen: &shown_square, measures: &counted_pictures }.id_salt("picture").show(ui); + } + Wrap::new(&shown_wrap, &counted_wraps).id_salt("wrap").show(ui); + Probe::new(&shown_under).size(Vec2::new(sibling, LINE)).id_salt("under").show(ui); + }); + shown_column.set(shown.output.rect); + }); + fixture.room(Vec2::splat(800.0)).settle(); + let rects = [column.get(), square.borrow().rect, under.borrow().rect]; + PictureColumn { rects, picture: (pictures.unbounded.get(), pictures.bounded.get()), wrap: (wraps.unbounded.get(), wraps.bounded.get()) } +} + +// A square picture in a content-sized column takes no width of its own there; the column settles on its siblings' +// width and the picture shows across it, as tall as wide, with what follows it laid out below the shown square. +#[trial] +fn a_square_picture_in_a_content_column_pushes_what_follows_below_its_shown_size() { + let PictureColumn { rects: [column, picture, under], .. } = picture_in_column(Some(60.0), 300.0); + let dump = format!("column {column:?}, picture {picture:?}, under {under:?}"); + assert!(picture.width() > 60.0 + SLACK, "the picture shows wider than its least, across the column: {dump}"); + assert!((picture.width() - picture.height()).abs() < SLACK, "a square picture is as tall as it shows wide: {dump}"); + assert!(under.top() >= picture.bottom() - SLACK, "what follows lies below the shown picture: {dump}"); + assert!(column.bottom() >= under.bottom() - SLACK, "the column holds everything it shows: {dump}"); +} + +// Count trial: a column whose picture took its least sweeps again once at its settled width; a column without a +// picture, or whose picture is its widest child, sweeps once. +#[trial] +fn a_content_column_sweeps_again_only_for_a_picture_narrower_than_it() { + let none = picture_in_column(None, 300.0); + let wide = picture_in_column(Some(400.0), 300.0); + let narrow = picture_in_column(Some(60.0), 300.0); + assert!(none.wrap.0 >= 1 && none.wrap.1 == 0, "no picture: the column sweeps its children: {:?}", none.wrap); + assert_eq!(wide.wrap, none.wrap, "a picture as wide as the column adds no sweep"); + assert!(wide.picture.0 >= 1 && wide.picture.1 == 0, "the widest picture keeps its first measure: {:?}", wide.picture); + let (unbounded, bounded) = narrow.picture; + assert!( + bounded >= 1 && bounded == unbounded, + "a narrower picture measures once more per measuring run, at the column: {unbounded} and {bounded}" + ); +} + #[trial] fn a_space_between_child_leaves_room_for_the_siblings_after_it() { let (first, last) = (Rc::new(RefCell::new(Seen::default())), Rc::new(RefCell::new(Seen::default()))); From 7a6827f5bfde0f97f19e8efede889bb500c50035 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 07:57:24 +0000 Subject: [PATCH 35/74] Overlay placement: a menu hung at a point also covers its anchor (photocraft#15552) Most context menus hang from Anchor::Point (table header, rulers, ribbon, places, versions, dock group menu). layer_covers_anchor decides every case in one place: the pointer, the rect a context request named, and a point for a layer whose key class is OwnerClass::Menu. Point-anchored layers that are not menus (the iconic flyout, a popover at a point) keep their rule. docs/contract-api.md regenerated. --- .../src/contract/overlay/opener.rs | 10 --- .../src/contract/overlay/placement.rs | 24 +++++-- crates/ui-widgets/tests/it/table.rs | 35 +++++++++- docs/contract-api.md | 64 ++++++++++++++----- 4 files changed, 100 insertions(+), 33 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/opener.rs b/crates/ui-contract/src/contract/overlay/opener.rs index fbd2677a5..d00d8c6fd 100644 --- a/crates/ui-contract/src/contract/overlay/opener.rs +++ b/crates/ui-contract/src/contract/overlay/opener.rs @@ -178,16 +178,6 @@ impl crate::runtime::env::EnvValue for LayerFloor { } } -/// Whether a layer opened by `opener` may cover the anchor [`opener_anchor`] gives it: the pointer, or the rect a context -/// request named. Both are a context menu's anchor, a point or a row. -pub(super) fn covers_anchor(opener: &Opener, opening: Opening, place: &Place) -> bool { - match opener_anchor(opener, opening, place) { - Anchor::Pointer => true, - Anchor::Rect(_) => opener.anchor.is_none() && matches!(opening, Opening::At(_)), - _ => false, - } -} - /// The anchor a layer opened by `opener` hangs from: the opener's own, else the layer's `Pointer` or `Corner` /// place, else the pointer for a context request a secondary release made, else the rect a key's context request /// named, else the opener's rect. diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index d8be6a235..59602d1bc 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -1,13 +1,14 @@ //! Where a shown layer goes: its anchor, the region and screen it stays in, and the room its body has. use super::host::{Layer, LayerMemory, memory_slot}; -use super::opener::{Opening, covers_anchor, opener_anchor}; +use super::opener::{Opening, opener_anchor}; use super::place::{Anchor, OverlayFit, Place, ViewportShare}; use super::props::Overlay; use crate::runtime::egui::areas::{self}; use crate::runtime::env::Env; use crate::runtime::memory::MemoryStage; use crate::runtime::overlay::{self}; +use craft_behavior::OwnerClass; use craft_behavior::overlay::{PlaceRequest, Side}; use egui::{Context, Id, Pos2, Rect}; @@ -51,15 +52,26 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option) -> bool { - match &overlay.opener { + let (anchor, requested) = match &overlay.opener { Some(first) => { let (opener, opening) = first.active(ctx, stored); - covers_anchor(opener, opening, &overlay.place) + (opener_anchor(opener, opening, &overlay.place), opener.anchor.is_none() && matches!(opening, Opening::At(_))) } - None => matches!(overlay.place, Place::Anchored { anchor: Anchor::Pointer, .. }), + None => match &overlay.place { + Place::Anchored { anchor, .. } => (anchor.clone(), false), + Place::Float(_) => return false, + }, + }; + match anchor { + Anchor::Pointer => true, + Anchor::Point(_) => overlay.keys == OwnerClass::Menu, + // `opener_anchor` gives a requested rect only for a context request's opening. + Anchor::Rect(_) => requested, + _ => false, } } diff --git a/crates/ui-widgets/tests/it/table.rs b/crates/ui-widgets/tests/it/table.rs index 8bb3a2d4d..7db9b8ffd 100644 --- a/crates/ui-widgets/tests/it/table.rs +++ b/crates/ui-widgets/tests/it/table.rs @@ -1,6 +1,7 @@ //! The table's header row and column widths: a double click on a column's edge fits the column to its widest cell in //! view, the header menu hides, shows and resets columns, Ctrl or Cmd with an arrow moves the focused column, and the -//! metadata table's name column follows its widest name up to a third of the table. +//! metadata table's name column follows its widest name up to a third of the table. A header menu too tall for either +//! side of its point covers the point instead of scrolling. use craft_behavior::{ColumnKey, ColumnWidth, keyed}; use craft_host::target::Os; @@ -217,6 +218,38 @@ fn the_header_menu_hides_shows_and_resets_columns() { assert!(menu_row(&fixture, Role::MENU_ITEM, "Move Column Right").is_none(), "with no column there are no column commands"); } +/// The hideable columns of a table whose header menu is taller than the room on either side of the point it opens at. +const EXTRA: [&str; 14] = + ["Kind", "Owner", "Group", "Created", "Modified", "Opened", "Tags", "Rating", "Label", "Path", "Format", "Pixels", "Profile", "Author"]; + +/// A header menu opened at a point mid-window, too tall for the room above or below the point but not for the window, +/// covers the point and shows every row. +#[trial] +fn a_header_menu_too_tall_for_either_side_of_its_point_covers_it_and_shows_every_row() { + let mut fixture = Fixture::new(|ui| { + ui.add_space(270.0); + let mut columns = vec![ColumnSpec::new(NAME, "Name", ColumnWidth::Controls(4.0)).movable()]; + columns.extend(EXTRA.iter().map(|name| ColumnSpec::new(ColumnKey::new(name), *name, ColumnWidth::Controls(2.0)).hideable())); + let keys = [0_usize]; + let source = keyed(&keys, |key: &usize| *key); + Table::new("Files", columns).show_items(ui, &source, &mut |key, icx| ListRow::new(format!("File {key}")).cells(icx.cells())); + }); + fixture.settle(); + let at = fixture.by_label("Name").expect("the header cell").center(); + secondary_click(&mut fixture, at); + let room = fixture.ctx().content_rect(); + let first = menu_row(&fixture, Role::MENU_ITEM_CHECK_BOX, EXTRA[0]).expect("the first column's row").rect; + let last = menu_row(&fixture, Role::MENU_ITEM, "Reset Columns").expect("the last row").rect; + let tall = last.bottom() - first.top(); + assert!(tall > at.y - room.top() && tall > room.bottom() - at.y, "the rows ({tall}) fit on neither side of the point {at:?}"); + let menus = fixture.by_role(Role::MENU); + assert!(!menus.is_empty(), "the header menu is open"); + for menu in menus { + assert!(room.contains_rect(menu.rect), "the menu {:?} stays inside the window {room:?}", menu.rect); + assert!(menu.rect.contains_rect(first) && menu.rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {:?}", menu.rect); + } +} + /// Ctrl or Cmd with Right on a focused movable header moves its column one place on; Right alone moves the focus. /// macOS makes Cmd+Right a move to the line's end, which the header reads the same. #[trial] diff --git a/docs/contract-api.md b/docs/contract-api.md index f5b3b99ef..fd4349515 100644 --- a/docs/contract-api.md +++ b/docs/contract-api.md @@ -538,11 +538,11 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn add_document(&mut self, document: &D)`. Adds `document` to the first docked group, or to a new docked group when there is none. A document a group - `pub fn to_actions(&self, layout: &Layout

, panel_of: impl Fn(u64) -> P) -> Vec>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. The - `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub column: Column

, pub rect: Rect, pub native: Option, pub edge: Option }`. A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column - - `pub fn new(column: Column

, rect: Rect) -> Self`. A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build - - `pub fn single(panels: Vec

, active: usize, rect: Rect) -> Self`. A window with one group. Each call makes a new window, as [`Self::new`] does. - - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id`, for a layout the app builds in code, such as a default layout: + - `pub fn new(id: u64, column: Column

, rect: Rect) -> Self`. The window `id` holding `column`. Ids are unique within a layout; a window added to a live layout takes its id + - `pub fn single(id: u64, panels: Vec

, active: usize, rect: Rect) -> Self`. The window `id` with one group. + - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id` in place of its own. Ids must be unique within a layout. - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, top group first. - - `pub fn stack(groups: Vec>, rect: Rect) -> Option`. A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window, + - `pub fn stack(id: u64, groups: Vec>, rect: Rect) -> Option`. The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups. - `pub fn groups(&self) -> &[Group

]`. The window's groups, top to bottom. - `pub fn contains(&self, panel: &Q) -> bool where P: std::borrow::Borrow,`. True when a group of this window holds `panel`. Takes any borrowed form of `P`, such - `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a column, docked or floating. @@ -553,7 +553,9 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub const fn with_flyout_width(mut self, width: Option) -> Self`. The location with the group's flyout `width` points wide. - `pub const fn with_flyout_offset(mut self, offset: Option) -> Self`. The location with the group's flyout top `offset` points from its icons' top. - `craft_behavior::dock::Layout`: `pub struct Layout

{ pub root: Option>, pub floating: Vec> }`. The panels of a workspace: a docked tree plus floating windows. Every panel occurs once. - - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. + - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. New windows take ids above every id + - `pub fn fresh_window_id(&mut self) -> u64`. An id for a new floating window: above every window id the layout held when it was built or loaded and every + - `pub fn window_floor(&self) -> u64`. The least id above every id the layout holds or has held. - `pub fn validate(&self) -> Result<(), DockError>`. Check depth, allocation bounds, geometry, selection, globally unique panel ownership and - `pub fn panels(&self) -> Vec<&P>`. Iterate identities without recursion. On excessive input returns no more than the limit. - `pub fn contains(&self, panel: &P) -> bool`. Whether the layout holds `panel`, docked or floating. @@ -562,7 +564,7 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn panel_state(&self, panel: &P) -> PanelState`. Hidden, open behind another tab or in a collapsed container, or showing. In a column, docked or floating, - `pub fn restore(&mut self, panel: P, location: &Location

) -> Result<(), DockError>`. Restore an absent panel at a captured location. Missing anchors are reported without - `pub fn open_at_edge(&mut self, panel: P) -> Result<(), DockError>`. Open an absent panel as a frame at the outer edge of the docked area, taking most of it: -- `craft_behavior::dock::Location`: `pub struct Location

{ pub floating: Option, pub anchor: Option

, pub placement: DockPlacement

, pub size: Option, pub stack: Option<(bool, Option)>, pub sibling: Vec

, pub group: Option }`. A closed panel's former placement. Applications may retain this beside visibility flags. +- `craft_behavior::dock::Location`: `pub struct Location

{ pub floating: Option, pub anchor: Option

, pub placement: DockPlacement

, pub size: Option, pub stack: Option<(bool, Option)>, pub sibling: Vec

, pub group: Option, pub closed_with: Vec

}`. A closed panel's former placement. Applications may retain this beside visibility flags. - `pub fn new(anchor: Option

, placement: DockPlacement

) -> Self`. A location relative to `anchor` by `placement`, with no recorded sizes or siblings. - `craft_behavior::dock::MAX_DEPTH`: `pub const MAX_DEPTH: usize`. Limits are checked before cloning or recursively modifying an application layout. - `craft_behavior::dock::MAX_PANELS`: `pub const MAX_PANELS: usize`. Most panels a layout may hold. Larger layouts fail with [`DockError::LimitExceeded`](super::DockError::LimitExceeded). @@ -600,10 +602,17 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn new_dock(side: DockEdge) -> Self`. Builds [`Target::NewDock`]. - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`] with no edge: the area takes the edge nearer `rect`. - `pub fn float_with_edge(rect: Rect, edge: Option) -> Self`. Builds [`Target::Float`] with the edge a collapsed window keeps to. -- `craft_behavior::dock::Workspace`: `pub struct Workspace

{ pub version: u32, pub layout: Layout

, pub hidden: Vec<(P, Location

)>, pub floated: Vec<(P, Location

)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. +- `craft_behavior::dock::Workspace`: `pub struct Workspace

`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. - `pub const VERSION: u32`. The format version written to files. Version 4 saves a floating window as one column; older floating - - `pub fn revision(&self) -> u64`. The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else. - - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next revision. + - `pub fn version(&self) -> u32`. The format version the workspace was read with. + - `pub fn layout(&self) -> &Layout

`. The current arrangement. + - `pub fn hidden(&self) -> &[(P, Location

)]`. The closed panels, and panels the application does not register now, with where each one goes back. + - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels with the docked location each one left. + - `pub fn revision(&self) -> Revision`. The revision of this workspace value: it moves with every write, and no other value has it. + - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. + - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a + - `pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool)`. Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. + - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this - `pub fn apply(&mut self, action: Action

, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError>`. Apply one action. Closed panels record where they go back, so each one can be reopened - `pub fn apply_all(&mut self, actions: impl IntoIterator>, locked: bool, permissions: impl Fn(&P) -> Permissions,) -> Result, DockError>`. Apply every action in order, or none, as [`Self::apply`] does. Returns the panels the - `craft_behavior::dock::WorkspaceChrome`: `pub struct WorkspaceChrome { pub menu_bar: bool, pub tool_rail: bool, pub options_bar: bool, pub status_bar: bool }`. Chrome a workspace remembers beside the dock layout: which bars show. The default shows every bar. @@ -1375,7 +1384,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point - `craft_behavior::overlay::Align`: `pub enum Align { Start, Center, End }`. How the overlay lines up with the anchor along the edge it hangs from. - `craft_behavior::overlay::MinWidth`: `pub enum MinWidth { None, Anchor, Points(f32) }`. The narrowest an overlay may be. - `pub fn points(self, anchor_width: f32, side: Side) -> f32`. The width in points, given the anchor's width and the side the overlay takes: beside its anchor (`Start`, -- `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option, pub flips_across: bool }`. What `place` reads. +- `craft_behavior::overlay::PlaceRequest`: `pub struct PlaceRequest { pub anchor: Rect, pub size: Vec2, pub side: Side, pub align: Align, pub rtl: bool, pub gap: f32, pub min_width: MinWidth, pub bounds: Rect, pub kept: Option, pub flips_across: bool, pub covers_anchor: bool }`. What `place` reads. - `pub const fn new(anchor: Rect, size: Vec2, bounds: Rect) -> Self`. A request for `size` around `anchor` inside `bounds`: below, aligned to the start, no gap, free width. - `pub const fn size(mut self, size: Vec2) -> Self`. Sets the content size. - `pub const fn side(mut self, side: Side) -> Self`. Sets the preferred side. @@ -1385,6 +1394,7 @@ The one-press-per-pass rule: a pass carries at most one press, as its last point - `pub const fn min_width(mut self, min_width: MinWidth) -> Self`. Sets the narrowest width. - `pub const fn kept(mut self, side: Option) -> Self`. Keeps `side` instead of flipping. - `pub const fn flips_across(mut self, on: bool) -> Self`. Lines up with the anchor's other end, beside it, when that fits and the aligned end does not. + - `pub const fn covers_anchor(mut self, on: bool) -> Self`. Below or above the anchor, slides over the anchor when the overlay fits neither side but fits the bounds. - `craft_behavior::overlay::Placement`: `pub struct Placement { pub rect: Rect, pub side: Side }`. Where `place` put the overlay. - `craft_behavior::overlay::Side`: `pub enum Side { Below, Above, Start, End }`. The side of the anchor an overlay prefers. `Start` and `End` follow the reading direction. - `craft_behavior::overlay::place`: `pub fn place(request: &PlaceRequest) -> Placement`. Places an overlay: the preferred side unless the other has more room and the content does not fit, shifted to @@ -1955,6 +1965,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn labelled_with(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C, content: D,) -> C::Output`. `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). The - `pub fn style(&self) -> Option<&'a C::Style>`. The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body - `pub fn gap(&self) -> Option`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places + - `pub fn derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc`. The value this body derives from `key`: kept while `key` is unchanged, else built by `build` - `pub fn take_cancel(&mut self) -> bool`. Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it - `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]>, fit: GridFit, cells: CellAlign } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. - `pub const fn stack() -> Self`. Children one under another. @@ -1964,6 +1975,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. +- `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. @@ -1971,7 +1983,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. - `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection(SelectionChange), LeadMoved { key: K, by: LeadSource }, Activate(K), Rested(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option

, panel_of: impl Fn(u64) -> P) -> Vec>`. The dock actions that put `self` into `layout`, for the dock to draw the windows. The - `craft_behavior::dock::Floating`: `pub struct Floating

{ pub id: u64, pub column: Column

, pub rect: Rect, pub native: Option, pub edge: Option }`. A floating window: one column of groups, the same [`Column`] a dock holds. Nothing sits beside the column - - `pub fn new(column: Column

, rect: Rect) -> Self`. A window holding `column`. Each call makes a new window, with a fresh [`Self::id`]: build - - `pub fn single(panels: Vec

, active: usize, rect: Rect) -> Self`. A window with one group. Each call makes a new window, as [`Self::new`] does. - - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id`, for a layout the app builds in code, such as a default layout: + - `pub fn new(id: u64, column: Column

, rect: Rect) -> Self`. The window `id` holding `column`. Ids are unique within a layout; a window added to a live layout takes its id + - `pub fn single(id: u64, panels: Vec

, active: usize, rect: Rect) -> Self`. The window `id` with one group. + - `pub fn with_id(mut self, id: u64) -> Self`. The window with `id` in place of its own. Ids must be unique within a layout. - `pub fn panels(&self) -> impl Iterator`. Every panel in the window, top group first. - - `pub fn stack(groups: Vec>, rect: Rect) -> Option`. A window of `groups`, stacked top to bottom, expanded. `None` without groups. Each call makes a new window, + - `pub fn stack(id: u64, groups: Vec>, rect: Rect) -> Option`. The window `id` of `groups`, stacked top to bottom, expanded. `None` without groups. - `pub fn groups(&self) -> &[Group

]`. The window's groups, top to bottom. - `pub fn contains(&self, panel: &Q) -> bool where P: std::borrow::Borrow,`. True when a group of this window holds `panel`. Takes any borrowed form of `P`, such - `craft_behavior::dock::Group`: `pub struct Group

{ pub panels: Vec

, pub active: usize, pub minimized: bool, pub height: Option, pub flyout_width: Option, pub flyout_offset: Option }`. Tabs that move, minimize and size together in a column, docked or floating. @@ -553,7 +553,9 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub const fn with_flyout_width(mut self, width: Option) -> Self`. The location with the group's flyout `width` points wide. - `pub const fn with_flyout_offset(mut self, offset: Option) -> Self`. The location with the group's flyout top `offset` points from its icons' top. - `craft_behavior::dock::Layout`: `pub struct Layout

{ pub root: Option>, pub floating: Vec> }`. The panels of a workspace: a docked tree plus floating windows. Every panel occurs once. - - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. + - `pub fn new(root: Option>, floating: Vec>) -> Self`. A layout with the docked tree `root` and the floating windows `floating`. New windows take ids above every id + - `pub fn fresh_window_id(&mut self) -> u64`. An id for a new floating window: above every window id the layout held when it was built or loaded and every + - `pub fn window_floor(&self) -> u64`. The least id above every id the layout holds or has held. - `pub fn validate(&self) -> Result<(), DockError>`. Check depth, allocation bounds, geometry, selection, globally unique panel ownership and - `pub fn panels(&self) -> Vec<&P>`. Iterate identities without recursion. On excessive input returns no more than the limit. - `pub fn contains(&self, panel: &P) -> bool`. Whether the layout holds `panel`, docked or floating. @@ -600,10 +602,17 @@ The dock model: the tree of splits over panel frames, the side of a group a drop - `pub fn new_dock(side: DockEdge) -> Self`. Builds [`Target::NewDock`]. - `pub fn float(rect: Rect) -> Self`. Builds [`Target::Float`] with no edge: the area takes the edge nearer `rect`. - `pub fn float_with_edge(rect: Rect, edge: Option) -> Self`. Builds [`Target::Float`] with the edge a collapsed window keeps to. -- `craft_behavior::dock::Workspace`: `pub struct Workspace

{ pub version: u32, pub layout: Layout

, pub hidden: Vec<(P, Location

)>, pub floated: Vec<(P, Location

)> }`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. +- `craft_behavior::dock::Workspace`: `pub struct Workspace

`. A saved arrangement of panels: the [`Layout`] and the closed panels' former places. - `pub const VERSION: u32`. The format version written to files. Version 4 saves a floating window as one column; older floating - - `pub fn revision(&self) -> u64`. The revision of this live workspace: it changes with every [`replace`](Self::replace) and nothing else. - - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next revision. + - `pub fn version(&self) -> u32`. The format version the workspace was read with. + - `pub fn layout(&self) -> &Layout

`. The current arrangement. + - `pub fn hidden(&self) -> &[(P, Location

)]`. The closed panels, and panels the application does not register now, with where each one goes back. + - `pub fn floated(&self) -> &[(P, Location

)]`. The floating panels with the docked location each one left. + - `pub fn revision(&self) -> Revision`. The revision of this workspace value: it moves with every write, and no other value has it. + - `pub fn generation(&self) -> u64`. The generation of this live workspace: it moves with every [`replace`](Self::replace) and nothing else. + - `pub fn raise_window_floor(&mut self, floor: u64)`. Keeps the ids of new floating windows at or above `floor`. A dock that showed windows below `floor` raises a + - `pub fn forget_hidden(&mut self, forget: impl Fn(&P) -> bool)`. Drops the closed-panel records of the panels `forget` names, so reopening them does not restore their place. + - `pub fn replace(&mut self, with: Workspace

)`. Replaces the arrangement with `with` and moves to the next generation. The windows of `with` take ids this - `pub fn apply(&mut self, action: Action

, locked: bool, permissions: impl Fn(&P) -> Permissions) -> Result, DockError>`. Apply one action. Closed panels record where they go back, so each one can be reopened - `pub fn apply_all(&mut self, actions: impl IntoIterator>, locked: bool, permissions: impl Fn(&P) -> Permissions,) -> Result, DockError>`. Apply every action in order, or none, as [`Self::apply`] does. Returns the panels the - `craft_behavior::dock::WorkspaceChrome`: `pub struct WorkspaceChrome { pub menu_bar: bool, pub tool_rail: bool, pub options_bar: bool, pub status_bar: bool }`. Chrome a workspace remembers beside the dock layout: which bars show. The default shows every bar. @@ -1955,6 +1964,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn labelled_with(&mut self, ui: &mut Ui, key: impl Hash + Debug, label: Label, side: SideLabel, child: C, content: D,) -> C::Output`. `labelled`, with `content` shown inside the label after its text (a sample of what the option picks). The - `pub fn style(&self) -> Option<&'a C::Style>`. The style of the container `C` whose body this is, as step 2 resolved it for this pass: the one way a body - `pub fn gap(&self) -> Option`. The gap the body's layout puts between its children (`ContainerProps::body_gap`), for a body that places + - `pub fn derived(&self, key: &K, build: impl FnOnce() -> V) -> std::sync::Arc`. The value this body derives from `key`: kept while `key` is unchanged, else built by `build` - `pub fn take_cancel(&mut self) -> bool`. Takes the Escape of this pass that no component took: a field that clears on Escape passes it on once it - `craft_ui::contract::BodyLayout`: `pub enum BodyLayout { Stack, Row { wrap: bool, align: RowAlign }, Grid { columns: Cow<'static, [ColumnWidth]>, fit: GridFit, cells: CellAlign } }`. How a body lays out its children, in reading order: mirrored under a right-to-left direction. - `pub const fn stack() -> Self`. Children one under another. @@ -1964,6 +1974,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub fn cells(self, cells: CellAlign) -> Self`. A `Grid` with `cells`; any other layout is unchanged. - `pub fn wrap(self, on: bool) -> Self`. A `Row` that wraps; any other layout is unchanged. - `pub fn align(self, align: RowAlign) -> Self`. A `Row` with `align`; any other layout is unchanged. +- `craft_ui::contract::Bracket`: `pub enum Bracket { Linked, Unlinked }`. The bracket a `Row` draws from the labelled rows of its first child to the child after them (Image Size's width and - `craft_ui::contract::CanvasGesture`: re-export of `craft_ui::runtime::sampler::CanvasGesture`. - `craft_ui::contract::CellWidth`: `pub type CellWidth = ColumnWidth`. The width of a caption's cell. - `craft_ui::contract::Collapse`: `pub struct Collapse { pub initially_open: bool, pub animated: bool }`. Collapse configuration. @@ -1971,7 +1982,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st - `pub const fn initially_open(mut self, on: bool) -> Self`. Whether the body starts open. - `pub const fn animated(mut self, on: bool) -> Self`. Whether opening and closing animate. - `craft_ui::contract::CollectionEvent`: `pub enum CollectionEvent { Selection(SelectionChange), LeadMoved { key: K, by: LeadSource }, Activate(K), Rested(K), EmptyActivated, EmptyContextMenu { at: Pos2 }, Preview(K), ContextMenu(ContextMenuRequest), EdgePressed { above: K, below: K, mods: craft_keymap::Mods }, CommandClick { key: K, mods: craft_keymap::Mods }, Delete(Vec), Open(OpenChange), Reorder(EditEvent>), Move(EditEvent), Dropped { at: DropAt, op: DropOperation, payload: DropPayload }, Zoom { factor: f32, about: Pos2 }, Rename(EditEvent>), Toggle(EditEvent>), Column(ColumnEvent), Item(K, E) }`. What a collection reports, in drawing order. -- `craft_ui::contract::CollectionProps`: `pub struct CollectionProps { pub select: SelectMode, pub reorder: Option, pub rename: bool, pub rename_column: Option, pub slow_click_rename: bool, pub columns: Vec, pub sort: Option, pub empty: Option

(), crate::runtime::lazy::Key::Memo(key), |ui, run| { // The content is a layout room of its own: the flow of the body around it does not reach in. - let installed = Env::install_for(ui, env.derive_local(Scoped::start_room)); + let installed = Env::install_for(ui, env.derive_local(Scoped::start_view_room)); let out = show(&mut props, ui); Env::restore(&ctx, installed); run.output = Some(Arc::new(out.clone())); @@ -114,6 +119,9 @@ impl MemoVie } out }); + if let Some(installed) = unbounded { + Env::restore(&ctx, installed); + } match shown { Shown::Ran(out) => Some(out), // A replay at another place moves what the run returned with its record. diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index fd3733682..4c3e1e8e1 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -409,6 +409,21 @@ impl Scoped { self.offered = None; } + /// Starts the layout room of a memoized view's content (`start_room`). A view in a shrinking `Row` is one of the + /// units the row narrows: its content's leaves fit the room the view is given (`Shrink::Fit`). + pub(crate) fn start_view_room(&mut self) { + let fits = self.row_unit(); + self.start_room(); + if fits { + self.shrink = Some(Shrink::Fit); + } + } + + /// Whether a child shown in flow here is a unit of the shrinking `Row` around it. + pub(crate) const fn row_unit(&self) -> bool { + matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))) + } + /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its /// place compares): the scope's state (enabled, read-only, size, glyphs, ink, surface, wheel, directions), the /// containers around it (arena, roving group, transform, collection item and row, inside label, footer slot, line @@ -678,9 +693,12 @@ impl Env { Env { scoped: Arc::new(scoped) } } - /// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot. + /// Reuse a sweep's scope while it is uniquely held. A captured child env keeps its snapshot. The scope key is + /// computed again by the first view that asks after the edit. pub(crate) fn local_mut(&mut self) -> &mut Scoped { - Arc::make_mut(&mut self.scoped) + let scoped = Arc::make_mut(&mut self.scoped); + scoped.scope_key = std::sync::OnceLock::new(); + scoped } /// This env's container scope on top of `root`, the root env of the viewport the scope now runs in: the scale, diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 19b1b46e3..9edc13020 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -166,7 +166,7 @@ pub(crate) struct Measured { pub(crate) room: Rect, } -/// Where a memoized view ran: it replays only at a place of the same size, layer, layout and environment, and its +/// Where a memoized view ran: it replays only at a place of the same size, layer, layout, fit and environment, and its /// record moves with the room's position (`Place::shift_to`). #[derive(Clone, Copy, Debug, PartialEq)] pub(crate) struct Place { @@ -182,6 +182,9 @@ pub(crate) struct Place { /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, + /// Whether the view is a unit of the shrinking `Row` around it, so the leaves of its content fit the view's room + /// (`Scoped::start_view_room`). + pub(crate) fits: bool, } /// How a kept run replays at another place: the shift its record moves by, and whether the clip moved with the room. @@ -211,7 +214,8 @@ impl Place { && now.layout == self.layout && now.pixels_per_point == self.pixels_per_point && now.atlas == self.atlas - && now.env == self.env; + && now.env == self.env + && now.fits == self.fits; let placeable = offset == Vec2::ZERO || (keeps_placement(rect.union(self.room), offset, now.pixels_per_point) && movable && !transformed); if !same || !placeable { return None; diff --git a/crates/ui-widgets/src/menu/bar.rs b/crates/ui-widgets/src/menu/bar.rs index 50e060a8f..c74ef97b5 100644 --- a/crates/ui-widgets/src/menu/bar.rs +++ b/crates/ui-widgets/src/menu/bar.rs @@ -37,7 +37,7 @@ use crate::runtime::words::common::CommonWords; use crate::style::{ComponentStyle, FocusLook, IconLook, StyleCx, SurfaceLook, TextLook, TypeRole}; use crate::text::TextField; use craft_behavior::fit::{FitItem, FitKeep, fit_items}; -use craft_behavior::{Arrows, Axis, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Roving, Sense}; +use craft_behavior::{Arrows, Flow, Intent, Metrics, NavMove, NavShape, PartKey, PartRef, Proposal, Roving, Sense}; use craft_host::target::MenuPlacement; use craft_keymap::mnemonic; use craft_theme::Flags; @@ -436,18 +436,15 @@ impl Component for MenuBar<'_> { MenuBarStyle { metrics: Metrics::new() } } - /// Every title's width when the room allows it; the bar fills the row, so what is left over is room for the - /// overflow. + /// Every title's width; at its least (`Proposal::Min`) the width of the "…" title alone. A row that has less room + /// than every title needs narrows the bar, and the titles that no longer fit go into "…". fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { if !Self::in_window(&cx.env) { return Vec2::ZERO; } - let (widths, height, _) = self.widths(cx); - Vec2::new(widths.iter().sum(), height) - } - - fn fills(&self) -> Option { - Some(Axis::X) + let (widths, height, more) = self.widths(cx); + let width = if cx.proposal == Proposal::Min { more } else { widths.iter().sum() }; + Vec2::new(width, height) } fn sense(&self) -> Sense { diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index 0c52bb966..e175ecd2d 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -5,7 +5,7 @@ use crate::values::kit::Scrub; use craft_ui::buttons::Button; use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Tracked}; -use craft_ui::display::Text; +use craft_ui::display::{Elide, Text}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::runtime::env::{BodyMode, RevealEdge, ShellCx, WindowKey}; use craft_ui::runtime::memory::{SaveKey, set_saved_value}; @@ -1128,3 +1128,48 @@ fn a_view_in_a_content_sized_column_lays_out_its_fill_width_row_as_outside_a_vie assert!(outside.0.width() < outside.1.width(), "the column outside a view is as narrow as its button: {outside:?}"); assert_eq!(inside, outside, "the view's column and its sibling lie as without the view"); } + +#[derive(MemoProps)] +struct Line { + line: String, +} + +/// One line of text cut with an ellipsis where its room is short. +fn line(props: &mut Line, ui: &mut Ui) -> Rect { + Text::new(props.line.clone()).elide(Elide::End).show(ui).rect +} + +/// A memoized view is one unit of the shrinking row around it: with room it is as wide as its content, and when a +/// sibling after it grows it narrows so the row fits, though the region it is offered stays the same. It replays while +/// the row's width for it is unchanged and runs once when that width changes. +#[trial] +fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { + const ROOM: Rect = Rect { min: Pos2::new(10.0, 10.0), max: Pos2::new(310.0, 50.0) }; + let mut frames = Frames::new(); + let frame = |frames: &mut Frames, after: &str| { + let mut rects = (Rect::NOTHING, Rect::NOTHING); + frames.frame(vec![], |ui| { + in_region(ui, ROOM, |ui| { + Row::new().fill_width().show(ui, |ui, _| { + let view = MemoView::new("line", Line { line: "A line of text long enough to be cut".to_owned() }, line).show(ui); + let after = Button::new(after.to_owned()).show(ui).response.rect; + rects = (view.unwrap_or(Rect::NOTHING), after); + }); + }); + }); + rects + }; + for _ in 0..WARM { + frame(&mut frames, "B"); + } + let (wide, _) = frame(&mut frames, "B"); + assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "an idle frame replays the view"); + let (narrow, after) = frame(&mut frames, "A much longer button label"); + assert_eq!(runs_of(&frames, "Line"), [MemoRun::Ran], "a new width runs the view"); + assert!(narrow.width() < wide.width(), "the view narrows: {narrow:?} from {wide:?}"); + assert!(narrow.right() <= after.left() && after.right() <= ROOM.right() + 0.5, "the row fits: {narrow:?}, {after:?} in {ROOM:?}"); + for _ in 0..WARM { + frame(&mut frames, "A much longer button label"); + } + assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "at the same width it replays again"); +} From df6c100b78803c6f47b39f967770178215e78127 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 09:23:14 +0000 Subject: [PATCH 57/74] Repin egui to storytold/egui next 72cb386ac: a word laid out in room equal to its width keeps its width egui's galley cache rounded a finite wrap width to whole points and then clamped the reported width to it, so "200" (22.47 pt) laid out at 22.47 came back 22.0 and an Info readout row stacked under its label. The fork rounds to GUI_ROUNDING instead. The repin also brings next's two commits ahead of the old pin (AccessKit parent map reader, replayed widgets as used ids). Trials: ui-contract text::band (a word in room equal to its width, Wrap and Elide, at 1x and 2x) and the Info panel trial at G=200, K=44%. --- Cargo.lock | 28 ++++----- Cargo.toml | 28 ++++----- crates/color-ui/tests/it/panels.rs | 6 +- crates/craft/src/egui_fork.rs | 2 +- crates/ui-contract/tests/it/text/band.rs | 75 ++++++++++++++++++++++++ crates/ui-contract/tests/it/text/mod.rs | 1 + 6 files changed, 108 insertions(+), 32 deletions(-) create mode 100644 crates/ui-contract/tests/it/text/band.rs diff --git a/Cargo.lock b/Cargo.lock index add7ab337..39b7cf0f5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5449,7 +5449,7 @@ dependencies = [ [[package]] name = "ecolor" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "emath", @@ -5505,7 +5505,7 @@ dependencies = [ [[package]] name = "eframe" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5540,7 +5540,7 @@ dependencies = [ [[package]] name = "egui" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "accesskit", "ahash", @@ -5559,7 +5559,7 @@ dependencies = [ [[package]] name = "egui-wgpu" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5578,7 +5578,7 @@ dependencies = [ [[package]] name = "egui-winit" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "block2 0.6.2", "bytemuck", @@ -5598,7 +5598,7 @@ dependencies = [ [[package]] name = "egui_glow" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", "egui", @@ -5611,7 +5611,7 @@ dependencies = [ [[package]] name = "egui_kittest" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "eframe", "egui", @@ -5688,7 +5688,7 @@ dependencies = [ [[package]] name = "emath" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "bytemuck", ] @@ -5761,7 +5761,7 @@ dependencies = [ [[package]] name = "epaint" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" dependencies = [ "ahash", "bytemuck", @@ -5787,7 +5787,7 @@ dependencies = [ [[package]] name = "epaint_default_fonts" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[package]] name = "equator" @@ -15118,19 +15118,19 @@ dependencies = [ [[patch.unused]] name = "egui_demo_lib" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_extras" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_inspection" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" [[patch.unused]] name = "egui_system_font_provider" version = "0.37.0" -source = "git+https://github.com/storytold/egui.git?rev=6525c87923ca47465aac244460fe4b1139349060#6525c87923ca47465aac244460fe4b1139349060" +source = "git+https://github.com/storytold/egui.git?rev=72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1#72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1" diff --git a/Cargo.toml b/Cargo.toml index 984ee25ca..8afdc685c 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 = "6525c87923ca47465aac244460fe4b1139349060" } -emath = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-winit = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -eframe = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } -egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6525c87923ca47465aac244460fe4b1139349060" } +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" } 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/color-ui/tests/it/panels.rs b/crates/color-ui/tests/it/panels.rs index a02f696a9..fdd92d03e 100644 --- a/crates/color-ui/tests/it/panels.rs +++ b/crates/color-ui/tests/it/panels.rs @@ -429,13 +429,13 @@ fn run(fixture: &Fixture, text: &str) -> egui::Rect { #[trial] fn the_info_panel_shows_rgb_and_cmyk_as_two_aligned_columns() { let mut fixture = Fixture::new(|ui| { - let color = craft_color_ui::ui::InfoColor::from_parts([100, 128, 255], [11, 22, 33, 25]); + let color = craft_color_ui::ui::InfoColor::from_parts([10, 200, 30], [1, 22, 33, 44]); let readings = craft_color_ui::ui::InfoReadings::new().color(Some(color)).document(Some([640, 480])); let _ = craft_color_ui::ui::InfoPanel::new("Info", &readings).show(ui); }); fixture.settle(); - let [r, g, b] = ["100", "128", "255"].map(|value| run(&fixture, value)); - let [c, m, y, k] = ["11%", "22%", "33%", "25%"].map(|value| run(&fixture, value)); + let [r, g, b] = ["10", "200", "30"].map(|value| run(&fixture, value)); + let [c, m, y, k] = ["1%", "22%", "33%", "44%"].map(|value| run(&fixture, value)); assert!(c.left() > r.right().max(g.right()).max(b.right()), "CMYK starts right of RGB: {r:?} {c:?}"); assert!(r.left() == g.left() && g.left() == b.left(), "the RGB values share a column"); assert!(c.left() == m.left() && m.left() == y.left() && y.left() == k.left(), "the CMYK values share a column"); diff --git a/crates/craft/src/egui_fork.rs b/crates/craft/src/egui_fork.rs index 32efeff02..acd621c1e 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 = "6525c87923ca47465aac244460fe4b1139349060"; +pub const REV: &str = "72cb386ac73dc0ade2b2d15cc8314e236a8e5eb1"; /// The packages the workspace patches to the fork (the `[patch.crates-io]` entries that name [`GIT`]). pub const PACKAGES: &[&str] = &[ diff --git a/crates/ui-contract/tests/it/text/band.rs b/crates/ui-contract/tests/it/text/band.rs new file mode 100644 index 000000000..4e99a5730 --- /dev/null +++ b/crates/ui-contract/tests/it/text/band.rs @@ -0,0 +1,75 @@ +//! A run laid out in room equal to its own width. + +use craft_behavior::Sense; +use craft_ui::contract::{Common, Component, Cx, MeasureCx, Props as _, Role, Show as _}; +use craft_ui::primitives::{TextRun, Wrap}; +use craft_ui::style::StyleCx; +use craft_ui::testing::{Fixture, trial}; +use craft_ui_test_kit::contract::PlainStyle; +use egui::{Response, Vec2}; +use std::cell::Cell; +use std::rc::Rc; + +const WORDS: [&str; 9] = ["200", "100", "44%", "40%", "201", "45%", "Hello", "Width", "mm"]; + +/// Lays each word out unbounded and again in room equal to that width, and counts the words whose width is less than +/// half a point past a whole point: the widths a whole-point wrap width would round down. +#[derive(Component)] +struct OwnWidth { + #[common] + common: Common, + below_half: Rc>, +} + +impl Component for OwnWidth { + const ROLE: Role = Role::GROUP; + type Style = PlainStyle; + type Output = Response; + + fn style(_: &StyleCx<'_>, _: OwnWidthStyleKey) -> PlainStyle { + PlainStyle::default() + } + + fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 { + let mut below_half = 0; + for word in WORDS { + for wrap in [Wrap::Wrap, Wrap::Elide] { + let run = TextRun::new(word).wrap(wrap); + let whole = cx.layout_at(&run, f32::INFINITY); + let width = whole.size().x; + let fitted = cx.layout_at(&run, width); + assert_eq!(fitted.galley.rows.len(), 1, "{word:?} {wrap:?}"); + assert!(!fitted.elided, "{word:?} {wrap:?}"); + assert_eq!(fitted.size().x, width, "{word:?} {wrap:?}: room equal to its width keeps its width"); + } + let width = cx.layout_at(&TextRun::new(word), f32::INFINITY).size().x; + if width.fract() > 0.0 && width.fract() < 0.5 { + below_half += 1; + } + } + self.below_half.set(below_half); + Vec2::ZERO + } + + fn sense(&self) -> Sense { + Sense::empty() + } + + fn finish(self, cx: Cx<'_, Self>) -> Response { + cx.response.clone() + } +} + +#[trial] +fn room_equal_to_its_width_keeps_a_word_whole() { + for pixels_per_point in [1.0, 2.0] { + let below_half = Rc::new(Cell::new(0)); + let output = below_half.clone(); + let mut fixture = Fixture::new(move |ui| { + OwnWidth { common: Common::new(), below_half: output.clone() }.id_salt("own-width").show(ui); + }); + fixture.pixels_per_point(pixels_per_point); + fixture.frame(Vec::new()); + assert!(below_half.get() > 0, "at {pixels_per_point}x some word must be less than half a point past a whole point"); + } +} diff --git a/crates/ui-contract/tests/it/text/mod.rs b/crates/ui-contract/tests/it/text/mod.rs index abda7da2e..c121edcb9 100644 --- a/crates/ui-contract/tests/it/text/mod.rs +++ b/crates/ui-contract/tests/it/text/mod.rs @@ -1,3 +1,4 @@ +pub(crate) mod band; pub(crate) mod editor; pub(crate) mod input_cap; pub(crate) mod memo; From 8db22341b4bf6fbf1445c5cfa72153d317c93eb3 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 58/74] A memoized view in a Stack fits its content to its room, as in a shrinking row; the menu bar folds in any Stack --- crates/menu/README.md | 8 +++-- crates/menu/src/bar.rs | 3 +- crates/menu/tests/it/title_bar.rs | 32 ++++++++++++++++++-- crates/ui-contract/src/contract/lazy.rs | 2 +- crates/ui-contract/src/contract/memo_view.rs | 3 +- crates/ui-contract/src/runtime/env.rs | 14 +++++---- crates/ui-contract/src/runtime/lazy.rs | 4 +-- 7 files changed, 51 insertions(+), 15 deletions(-) diff --git a/crates/menu/README.md b/crates/menu/README.md index a654dbcaf..edacb7028 100644 --- a/crates/menu/README.md +++ b/crates/menu/README.md @@ -132,7 +132,9 @@ app translates. The dialog never opens a file dialog or touches the file system. ## Windows, Linux and web: the in-window bar -`MenuBarUi` draws a laid-out bar in a top panel and returns the titles' rect (`MenuBarOutput`). +`MenuBarUi` draws a laid-out bar and returns the titles' rect (`MenuBarOutput`). Show it inside a +`Stack` (a top panel's body) or the title bar's row: there the titles that don't fit its room fold +into "…". Each item is a command row: its enabled state, check mark and chord follow the command in the runtime's command state and keymap, and a choice is a `Fired` with `FireSource::Menu` in the frame's output. `.help_search(true)` starts the Help menu with a search field over every command @@ -141,7 +143,9 @@ frame's output. `.help_search(true)` starts the Help menu with a search field ov ```rust let laid_out = craft_menu::layout(&menu_bar, Target::current(), &LayoutOptions::new("Sample")).bar; egui::Panel::top("menu-bar").show(ui, |ui| { - MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui); + Stack::new().show(ui, |ui, _| { + MenuBarUi::new(&laid_out).keyboard(!dialog_open).help_search(true).show(ui); + }); }); // The commands chosen arrive in `FrameOutput.fired`. ``` diff --git a/crates/menu/src/bar.rs b/crates/menu/src/bar.rs index 35e8fe9ae..8f40a716c 100644 --- a/crates/menu/src/bar.rs +++ b/crates/menu/src/bar.rs @@ -81,7 +81,8 @@ pub struct MenuBarOutput { /// The English-label hook a bar takes by default: none is set, so this type only names the slot. pub type EnglishFn = fn(Labeled<'_>) -> Option; -/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, in a top panel. +/// The bar for one frame: `MenuBarUi::new(&bar).show(ui)`. Draw it at the top of the window, inside a `Stack` (a top +/// panel's body) or the title bar's row: there it folds the titles that don't fit its room into "…". /// The commands chosen come back through the command queue, not from `show`. /// /// The bar is a memoized view: while its model, options, place and environment are those of its last run and nothing diff --git a/crates/menu/tests/it/title_bar.rs b/crates/menu/tests/it/title_bar.rs index 9eee46092..1e79bf5c1 100644 --- a/crates/menu/tests/it/title_bar.rs +++ b/crates/menu/tests/it/title_bar.rs @@ -1,12 +1,15 @@ //! The in-window menu bar in an app's title bar: every title shows while the bar has room for them, the document title -//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". +//! takes the rest of the bar, and only a bar too narrow for every title folds the last into "…". In a `Stack` +//! narrower than its titles the bar folds the same way and draws nothing past the stack's edge. +use std::cell::Cell; use std::rc::Rc; use craft_host::target::{Os, WindowChrome}; use craft_menu::{CommandRef, MenuBar, MenuBarUi, Row, Target, from_items}; -use craft_ui::contract::{Role, Show as _, Tracked}; +use craft_ui::contract::{Role, Show as _, ShowContainer as _, Tracked}; use craft_ui::display::Picture; +use craft_ui::layout_components::Stack; use craft_ui::runtime::env::WindowKey; use craft_ui::shell::{AppShell, Caption, CaptionFamily, Captions, Frame, Title, TitleBar}; use craft_ui::testing::{Fixture, trial}; @@ -103,3 +106,28 @@ fn a_narrow_title_bar_folds_the_last_menus_into_more() { assert!(fixture.by_label("Help").is_some(), "{pixels_per_point}x: Help is a row of the \"…\" menu"); } } + +#[trial] +fn a_bar_in_a_stack_narrower_than_its_titles_folds_them_and_draws_nothing_past_its_edge() { + let bar = Rc::new(model()); + let stack = Rc::new(Cell::new(egui::Rect::NOTHING)); + let seen = Rc::clone(&stack); + let mut fixture = Fixture::new(move |ui| { + let bar = Rc::clone(&bar); + let shown = Stack::new().show(ui, |ui, _| { + MenuBarUi::new(&bar).target(Target::Windows).show(ui); + }); + seen.set(shown.output.rect); + }); + fixture.os(Os::Windows).room(vec2(240.0, 600.0)).settle(); + let shown = titles(&fixture); + assert_eq!(shown.last().map(String::as_str), Some("…"), "{shown:?}"); + assert!(!shown.iter().any(|title| title == "Help"), "Help is not a title: {shown:?}"); + let edge = stack.get().right(); + for run in fixture.texts().iter().filter(|run| MENUS.contains(&run.text.as_str()) || run.text == "…") { + assert!(run.rect.right() <= edge + 0.5, "{:?} at {:?} reaches past the stack's edge {edge}", run.text, run.rect); + } + let more = fixture.by_label("…").expect("the \"…\" title"); + fixture.click(&more).settle(); + assert!(fixture.by_label("Help").is_some(), "Help is a row of the \"…\" menu"); +} diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index c5d44670b..01d74889f 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -122,7 +122,7 @@ impl Lazy { pixels_per_point: ctx.pixels_per_point(), atlas: ctx.fonts(|fonts| fonts.atlas_generation()), env: Env::of(ui).key, - fits: Env::of(ui).row_unit(), + fits: Env::of(ui).view_fits(), }; if real && memo { crate::runtime::memory::claim_id(&ctx, id, "two memoized views share an id in one pass"); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index a391b8e53..d503b1895 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -53,7 +53,8 @@ use std::sync::Arc; /// cursor) does not reach in, so the room it is given reaches it only through its place. To the body /// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows /// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its -/// least. The width the row gives it is the room of its place, and the leaves of its content fit that room. +/// least. The width the row gives it is the room of its place, and the leaves of its content fit that room, as they +/// fit the room of a `Stack` the view is shown in. /// /// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept /// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 4c3e1e8e1..891f8abb6 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -409,19 +409,21 @@ impl Scoped { self.offered = None; } - /// Starts the layout room of a memoized view's content (`start_room`). A view in a shrinking `Row` is one of the - /// units the row narrows: its content's leaves fit the room the view is given (`Shrink::Fit`). + /// Starts the layout room of a memoized view's content (`start_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`). pub(crate) fn start_view_room(&mut self) { - let fits = self.row_unit(); + let fits = self.view_fits(); self.start_room(); if fits { self.shrink = Some(Shrink::Fit); } } - /// Whether a child shown in flow here is a unit of the shrinking `Row` around it. - pub(crate) const fn row_unit(&self) -> bool { - matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_))) + /// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body, + /// whose leaves show at most its room, and as one of the units a shrinking `Row` narrows. In a `Grid` cell, a + /// wrapping `Row` or a `Ui` with no body around it a leaf keeps its measured width, and so does the view's content. + pub(crate) const fn view_fits(&self) -> bool { + matches!(self.shrink, Some(Shrink::Count(_) | Shrink::Least(_) | Shrink::Apply(_) | Shrink::Fit)) } /// The key of everything a memoized view shown in this scope inherits beyond `key` (the style inputs, which its diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 9edc13020..5aa98cc1d 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -182,8 +182,8 @@ pub(crate) struct Place { /// The scope's environment (`Env::key`): its tokens (theme, density), scale, direction, language and whether the /// window is active. pub(crate) env: EnvKey, - /// Whether the view is a unit of the shrinking `Row` around it, so the leaves of its content fit the view's room - /// (`Scoped::start_view_room`). + /// Whether the leaves of the view's content fit the view's room, as in a `Stack` or a shrinking `Row` + /// (`Scoped::view_fits`). pub(crate) fits: bool, } From 688df999d5563f19023e9422d1631c3fd639b2ce Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 59/74] Layout: a labelled control's row takes its place in flow through place_in_cell, its control on the line --- crates/ui-contract/src/contract/label/step.rs | 180 +++++++++++++----- crates/ui-contract/src/layout/body.rs | 40 +--- crates/ui-contract/src/layout/mod.rs | 6 +- crates/ui-widgets/tests/it/layout/row_line.rs | 52 ++++- 4 files changed, 191 insertions(+), 87 deletions(-) diff --git a/crates/ui-contract/src/contract/label/step.rs b/crates/ui-contract/src/contract/label/step.rs index 2ec5f5a0a..e9126f28b 100644 --- a/crates/ui-contract/src/contract/label/step.rs +++ b/crates/ui-contract/src/contract/label/step.rs @@ -110,55 +110,124 @@ impl LeafPlaced { } } -/// The label step for one leaf child: measures the child's narrowest width, runs the step in `row` with the -/// `trailing` content inside the label and returns the rect left for the child. The caller shows the child there and -/// then calls `LeafPlaced::finish`. -pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option>) -> LeafPlaced { - let scope = sub(at.id, "field"); - let enabled = at.under.enabled; +/// The label step for one leaf child, decided: measures the child's narrowest width and decides where the label, with +/// content of `trailing` size inside it, and the child sit in `at.row`. Nothing shows and no room is taken; `show_leaf` +/// then shows the label where the row's place in flow puts it, and the caller shows the child at the control's rect +/// and calls `LeafPlaced::finish`. +pub(crate) fn decide_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Vec2) -> Decided { // Read before the child measures: nothing it does there may count as a child placed in flow. let in_column = in_column(ui); let control_min = crate::contract::run::measure_under(child, &*ui, Some(at.id), craft_behavior::Proposal::Min, Some(at.under)).x; - let input = LabelIn { - scope, + let facts = LeafFacts { control_min, in_column, claims: C::LABELLED_AFTER }; + decide_step(ui, env, &leaf_input(env, at, at.row, facts, trailing)) +} + +/// Shows the label of a leaf child's step `decided` for `at`, moved down by `down`, with the `trailing` content inside +/// it, and returns the rect left for the child. +pub(crate) fn show_leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, decided: Decided, down: f32, trailing: Option>) -> LeafPlaced { + let size = trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size); + let input = leaf_input(env, at, at.row.translate(Vec2::new(0.0, down)), decided.facts, size); + let placed = show(ui, env, &input, decided.moved(down), trailing); + LeafPlaced { control: placed.control, label: placed.label, scope: input.scope } +} + +/// What a label step reads of its control before it decides. +#[derive(Clone, Copy)] +struct LeafFacts { + control_min: f32, + in_column: bool, + claims: bool, +} + +/// The step's input for the leaf child of `at` in `row`, with content of `trailing` size inside the label. +fn leaf_input<'a>(env: &Env, at: &LeafLabel<'a>, row: Rect, facts: LeafFacts, trailing: Vec2) -> LabelIn<'a> { + LabelIn { + scope: sub(at.id, "field"), owner: at.owner, parent: at.parent, - row: at.row, - room: at.row.width(), + row, + room: row.width(), content_row: env.content.0, text: at.text, side: at.side, help: None, - enabled, + enabled: at.under.enabled, size: at.under.size, - control_min, + control_min: facts.control_min, leaf: true, - in_column, - claims: C::LABELLED_AFTER, + in_column: facts.in_column, + claims: facts.claims, status: false, - trailing: trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size), - }; - let placed = run(ui, env, &input, trailing); - LeafPlaced { control: placed.control, label: placed.label, scope } + trailing, + } +} + +/// The label step for one leaf child in `at.row`, decided and shown where it was decided: returns the rect left for +/// the child. The caller shows the child there and then calls `LeafPlaced::finish`. +pub(crate) fn leaf(ui: &mut Ui, env: &Env, at: &LeafLabel<'_>, child: &mut C, trailing: Option>) -> LeafPlaced { + let decided = decide_leaf(ui, env, at, child, trailing.as_ref().map_or(Vec2::ZERO, |trailing| trailing.size)); + show_leaf(ui, env, at, decided, 0.0, trailing) } /// Runs the label step in `ui`: shows the label and the `trailing` content inside it (`input.trailing` is its size), /// opens the label scope and returns where the label and the control sit. The caller closes the scope with /// `scope::finish` after the control ran. pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option>) -> Placed { + let decided = decide_step(ui, env, input); + show(ui, env, input, decided, trailing) +} + +/// The label step decided for a row, before anything shows: where the label and the control sit, and the label leaf +/// measured in the child `Ui` it shows in. +pub(crate) struct Decided { + placed: Placed, + /// `None` for a label that shows no leaf. + leaf: Option, + /// What the step read of its control. + facts: LeafFacts, +} + +struct DecidedLeaf { + leaf: LabelLeaf, + kids: Ui, + installed: crate::runtime::env::Installed, + reset: Option, +} + +impl Decided { + /// The rect left for the control. + pub(crate) fn control(&self) -> Rect { + self.placed.control + } + + /// The label's rect; `Rect::NOTHING` for a hidden label. + pub(crate) fn label(&self) -> Rect { + self.placed.label + } + + /// The step moved down by `down`, as the row's place in flow moves it. + fn moved(mut self, down: f32) -> Self { + let by = Vec2::new(0.0, down); + self.placed.label = self.placed.label.translate(by); + self.placed.control = self.placed.control.translate(by); + self.placed.trailing = self.placed.trailing.translate(by); + self + } +} + +/// Decides the label step for `input`: measures the label in the child `Ui` it shows in and places it and the control +/// in `input.row`. Nothing shows. +fn decide_step(ui: &mut Ui, env: &Env, input: &LabelIn<'_>) -> Decided { let ctx = ui.ctx().clone(); let rtl = env.direction.is_rtl(); - let tokens = &env.tokens; - let (gap, slot_side) = (label_gap(env), tokens.size.handle.sm); + let (gap, slot_side) = (label_gap(env), env.tokens.size.handle.sm); let reset = scope::last_reset(&ctx, input.scope); let flow = Flow::new(input.row, rtl); - let label_id = sub(input.scope, "label"); let content = input.trailing.x > 0.0; + let facts = LeafFacts { control_min: input.control_min, in_column: input.in_column, claims: input.claims }; if input.side.shows_no_leaf(content) { - scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING))); let control = hidden_control(&ctx, input, flow, gap); - scope::place_controls(&ctx, input.scope, control.top()); - return Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 }; + return Decided { placed: Placed { label: Rect::NOTHING, control, trailing: Rect::NOTHING, caption: 0.0 }, leaf: None, facts }; } let slot = if reset.is_some() && input.side.reset_dot { slot_side } else { 0.0 }; let mut leaf = LabelLeaf::new(input.side.kind.shown(input.text).clone(), slot); @@ -192,24 +261,41 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option< Some(parent) => access::with_parent(builder, parent), None => builder, }; - let mut kids = alloc::child(ui, builder); + let kids = alloc::child(ui, builder); let kid_env = crate::contract::cx::child_env(env, &Under::new(input.enabled, input.size)); let installed = Env::install_for(&kids, kid_env); let glyph = leaf.glyph.is_some(); let mut placed = decide(&ctx, env, input, &kids, &mut leaf, glyph, flow); - // The label without its reset dot, which keeps its own press; the content sits at its end, on the first line. - let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot); if input.trailing.x > 0.0 { + // The label without its reset dot, which keeps its own press; the content sits at its end, on the first line. + let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot); let cell = unslotted.take_end(input.trailing.x).0; let middle = cell.top() + leaf.first_line.get() / 2.0; placed.trailing = Rect::from_min_size(egui::pos2(cell.min.x, middle - input.trailing.y / 2.0), input.trailing); } - let label_id_for_scope = sub(input.scope, "label"); + Decided { placed, leaf: Some(DecidedLeaf { leaf, kids, installed, reset }), facts } +} + +/// Shows the label step `decided` for `input`: the label and the `trailing` content inside it, and opens the label +/// scope. Returns where the label and the control sit. +fn show(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, decided: Decided, trailing: Option>) -> Placed { + let ctx = ui.ctx().clone(); + let rtl = env.direction.is_rtl(); + let label_id = sub(input.scope, "label"); + let Decided { placed, leaf, .. } = decided; + let Some(DecidedLeaf { leaf, mut kids, installed, reset }) = leaf else { + scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(field_label(env, input, label_id, Rect::NOTHING))); + scope::place_controls(&ctx, input.scope, placed.control.top()); + return placed; + }; + let slot = if reset.is_some() && input.side.reset_dot { env.tokens.size.handle.sm } else { 0.0 }; + // The label without its reset dot, which keeps its own press. + let (_, unslotted) = Flow::new(placed.label, rtl).take_end(slot); // A label shows with the control it names: where a bar's view shows the two only in part, neither shows. if crate::contract::run::cut_by_bar_view(env, placed.label.union(placed.control)) { kids.set_clip_rect(Rect::NOTHING); } - let shown = Props::id(leaf, label_id_for_scope).show_at(&mut kids, placed.label); + let shown = Props::id(leaf, label_id).show_at(&mut kids, placed.label); Env::restore(&ctx, installed); if let Some(fact) = reset.filter(|_| shown.double_click || shown.dot_click) { keys::route_whole_reset(&ctx, fact.control); @@ -219,8 +305,7 @@ pub(crate) fn run(ui: &mut Ui, env: &Env, input: &LabelIn<'_>, trailing: Option< if let Some(trailing) = trailing { (trailing.show)(ui, placed.trailing); } - let label = - field_label(env, input, label_id_for_scope, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated); + let label = field_label(env, input, label_id, placed.label).with_press(shown.press).with_hover(shown.hovered).activated(shown.activated); scope::begin(&ctx, input.scope, input.owner, scope::Kind::Label(label)); scope::place_controls(&ctx, input.scope, placed.control.top()); if input.claims { @@ -302,30 +387,36 @@ fn flow_leaf_row( region if in_cell => Rect::from_min_size(region.min, Vec2::new(flow.width(), region.height())), _ => flow, }; - // The child's own height: a stacked label pushes the control down, and the allocation below follows the placement. - // 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. - // Outside a grid's cell the row sits on the line of the flow around it, as a control without a label after it does. - let (above, taken) = if in_cell { (0.0, 0.0) } else { crate::layout::labelled_above(ui, avail.height(), ideal.y) }; - let row = Rect::from_min_max(egui::pos2(avail.min.x, avail.min.y + above), egui::pos2(avail.max.x, avail.min.y + above + ideal.y)); + // The label step decides where the label and the control sit at the flow's top, and the row then takes its place + // in flow as any other child does: its control's line is the row's line, on a row's or bracket's line, centred in a + // 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 }; - let placed = leaf(ui, &env, &at, &mut child, trailing); + 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; - let control_width = if content { placed.control.width().min(ideal.x) } else { placed.control.width() }; + let control_width = if content { decided.control().width().min(ideal.x) } else { decided.control().width() }; let rtl = env.direction.is_rtl(); - let cell = Rect::from_min_max(placed.control.min, egui::pos2(placed.control.max.x, placed.control.min.y + ideal.y)); - let control = Flow::new(cell, rtl).span(0.0, control_width); + 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()); let extent = if !content { avail.width() } else if rtl { - avail.max.x - control.min.x.min(placed.label.min.x) + avail.max.x - decided_control.min.x.min(decided_label.min.x) } else { - control.max.x.max(placed.label.max.x) - avail.min.x + decided_control.max.x.max(decided_label.max.x) - avail.min.x }; + // The child's own height: a stacked label pushes the control down, and a label taller than the control reaches + // below it. + let height = (decided_control.bottom().max(decided_label.bottom()) - row.top()).max(ideal.y); + let first = decided_control.top() - row.top() + ideal.y / 2.0; + let took = crate::layout::place_in_cell(ui, Vec2::new(extent, height), crate::layout::InFlow { fill: false, first: Some(first), line: true }); + let placed = show_leaf(ui, &env, &at, decided, took.top() - row.top(), trailing); + let control = span(placed.control); // A control beside its label in a content-sized column reports how far it reaches past the label column, so // the column's container measures its rows at the widest label. if content && ui.is_sizing_pass() && side.layout == FieldLayout::Beside && placed.label.bottom() > placed.control.top() { @@ -355,10 +446,7 @@ fn flow_leaf_row( if let Some(installed) = installed { Env::restore(ui.ctx(), installed); } - let bottom = control.bottom().max(placed.label.bottom()); placed.finish(ui.ctx()); - // The grid's cursor takes the row as its next cell (outside a grid, the next allocation of `ui`'s layout). - let _ = crate::layout::take_in_flow(ui, Vec2::new(extent, (bottom - row.top()).max(ideal.y) + taken)); output } diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index b1d4f3974..de1ac5bc8 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -1155,8 +1155,9 @@ pub(crate) struct InFlow { /// rows run along Y, or a container whose first child is one. The child is one line when that centre lies at /// half its height (`one_line`). pub first: Option, - /// `first` is the line of the child's own unwrapped `Row` body: the child sits on a row's line by it even when it - /// is more than one line (a nested row with a child of two lines). + /// `first` is the line of the child's own unwrapped `Row` body, or of the control of a labelled control's row: the + /// child sits on a row's line by it even when it is more than one line (a nested row with a child of two lines, a + /// check box whose label has a detail line under it, a control under its label). pub line: bool, } @@ -1171,37 +1172,6 @@ fn one_line(first: Option, height: f32) -> Option { first.filter(|first| (2.0 * first - height).abs() <= ONE_LINE_SLACK) } -/// The offset of a child whose first line is `first` below its top, on the row line whose centre is `centre` below -/// the flow's top: its first line's centre lands on the line. -fn centre_on_line(centre: f32, first: f32) -> f32 { - (centre - first).max(0.0) -} - -/// The offset of a child in `spare` room left over beside it: half of it. -fn centred(spare: f32) -> f32 { - spare.max(0.0) / 2.0 -} - -/// Where a labelled control's row of `height` sits below the top of the flow, as `place_in_cell` places any other -/// one-line child: `(offset, taken)`. On the line of the unwrapped `Row` around it the row's centre is on the line, and -/// it takes the offset with its height, as the line does. Else, in a horizontal layout that does not wrap, it is -/// centred in `room`, the flow's height, and takes only its height, so a tall room does not make the row taller. -/// Anywhere else it sits at the top. An options bar shown in a slot shorter than it asks for centres its members this -/// way; without it a check box with its label after it stood at the bar's top edge while the fields beside it sat on -/// the bar's middle. -pub(crate) fn labelled_above(ui: &Ui, room: f32, height: f32) -> (f32, f32) { - let env = Env::of(ui); - let layout = ui.layout(); - match env.row_line.and_then(|line| line.centre) { - Some(centre) => { - let above = centre_on_line(centre, height / 2.0); - (above, above) - } - None if layout.is_horizontal() && !layout.main_wrap && !env.grid_top && room.is_finite() => (centred(room - height), 0.0), - None => (0.0, 0.0), - } -} - /// The rect a child of measured `size` takes 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. A direct 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) @@ -1226,7 +1196,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { Some((line.body, took.centre().map(|centre| centre - ui.available_rect_before_wrap().top()))) }); let centre = bracket.and_then(|(_, centre)| centre).or_else(|| line.and_then(|line| line.centre)); - let above = centre.zip(child.first).map_or(0.0, |(centre, first)| centre_on_line(centre, first)); + let above = centre.zip(child.first).map_or(0.0, |(centre, first)| (centre - first).max(0.0)); let slot = Vec2::new(size.x, line.and_then(|line| line.height).map_or(above + size.y, |height| height.max(above + size.y))); let (rect, in_cell) = take_in(ui, &env, slot); let placed = if child.fill && in_cell { @@ -1236,7 +1206,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect { Some(_) => (above, (rect.height() - above - size.y).max(0.0)), None => { let spare = (rect.height() - size.y).max(0.0); - if env.grid_top { (0.0, spare) } else { (centred(spare), spare / 2.0) } + if env.grid_top { (0.0, spare) } else { (spare / 2.0, spare / 2.0) } } }; Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below)) diff --git a/crates/ui-contract/src/layout/mod.rs b/crates/ui-contract/src/layout/mod.rs index 6a499e060..b5fbb0c2e 100644 --- a/crates/ui-contract/src/layout/mod.rs +++ b/crates/ui-contract/src/layout/mod.rs @@ -25,7 +25,7 @@ pub use body::place_in_flow; pub(crate) use body::run_body; pub(crate) use body::{ BracketTook, 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, in_grid_content_column, labelled_above, 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, + flow_room, flow_start, grid_cell, 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, }; diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 538ff2eff..9ba63754d 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -1,15 +1,20 @@ //! 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 its label above or a help line below) sits at the row's top. +//! than one line (a column, a field with its label above or a help line below) sits at the row's top. A control with +//! its label after it sits on the line by its control, as a bare control does, in a row and in a grid's cell. +use craft_behavior::ColumnWidth; use craft_theme::ControlSize; use craft_ui::buttons::Button; -use craft_ui::contract::{FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::choice::Checkbox; +use craft_ui::contract::{Bind, FieldLayout, Props as _, Show as _, ShowContainer as _, Sizing}; use craft_ui::display::Text; use craft_ui::form::{Field, Help}; -use craft_ui::layout_components::{Row, Stack}; +use craft_ui::layout_components::{Grid, Row, Stack}; use craft_ui::runtime::env::Label; use craft_ui::testing::{Fixture, last_pass_measuring_runs, trial}; use egui::Rect; +use std::cell::Cell; +use std::rc::Rc; /// Half a pixel at the scales the box runs. const ROUNDING: f32 = 0.5; @@ -118,3 +123,44 @@ fn a_field_labelled_above_sits_at_the_rows_top() { assert!(caption.bottom() < control.top(), "the label sits above its control"); assert!(button.center().y < control.top(), "the button {button:?} sits level with the label, above the control {control:?}"); } + +/// A check box whose label runs to a second line under it, beside a button in a row: its box sits on the button's +/// line and the label's second line hangs below. In a grid's cell, beside a taller cell, a check box with its label +/// after it sits on the line of the button in the next cell. +#[trial] +fn a_labelled_check_box_sits_with_its_box_on_a_buttons_line_in_a_row_and_a_grid_cell() { + const LONG: &str = "Smooth the edges of every selection the tool makes"; + for grid in [false, true] { + 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(260.0, 400.0)); + let out = Rc::clone(&out); + Stack::new().fill().show_at(ui, room, move |ui, _| { + if grid { + Grid::new(&[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content]).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + Text::new("A").show(ui); + Text::new("B").show(ui); + }); + let button = Button::new("Go").show(ui).rect; + let check = Checkbox::new(Bind::given(true)).label("Snap").show(ui).response.rect; + out.set((button, check)); + }); + } else { + Row::new().show(ui, |ui, _| { + let button = Button::new("Go").show(ui).rect; + let check = Checkbox::new(Bind::given(true)).label(LONG).show(ui).response.rect; + out.set((button, check)); + }); + } + }); + }); + let (button, check) = seen.get(); + let at = if grid { "in a grid's cell" } else { "in a row" }; + if !grid { + assert!(text(&fixture, LONG).bottom() > check.bottom() + ROUNDING, "the label runs to a second line under the box {check:?}"); + } + assert!((button.center().y - check.center().y).abs() <= ROUNDING, "{at}: the box {check:?} sits on the button's line {button:?}"); + } +} From 75e8e49ef58c2b41282bf3e05a768ec4b1ab0537 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 60/74] Overlay placement: only a menu's layer covers its anchor --- .../src/contract/overlay/placement.rs | 12 +++-- crates/ui-widgets/tests/it/menu/overflow.rs | 47 +++++++++++++++++-- 2 files changed, 51 insertions(+), 8 deletions(-) diff --git a/crates/ui-contract/src/contract/overlay/placement.rs b/crates/ui-contract/src/contract/overlay/placement.rs index 59602d1bc..47ca407e0 100644 --- a/crates/ui-contract/src/contract/overlay/placement.rs +++ b/crates/ui-contract/src/contract/overlay/placement.rs @@ -52,10 +52,13 @@ pub(super) fn opened_overlay(ctx: &Context, overlay: &Overlay, stored: Option) -> bool { + if overlay.keys != OwnerClass::Menu { + return false; + } let (anchor, requested) = match &overlay.opener { Some(first) => { let (opener, opening) = first.active(ctx, stored); @@ -67,8 +70,7 @@ pub(super) fn layer_covers_anchor(ctx: &Context, overlay: &Overlay, stored: Opti }, }; match anchor { - Anchor::Pointer => true, - Anchor::Point(_) => overlay.keys == OwnerClass::Menu, + Anchor::Pointer | Anchor::Point(_) => true, // `opener_anchor` gives a requested rect only for a context request's opening. Anchor::Rect(_) => requested, _ => false, diff --git a/crates/ui-widgets/tests/it/menu/overflow.rs b/crates/ui-widgets/tests/it/menu/overflow.rs index 66a4fe8a1..2cbd656e9 100644 --- a/crates/ui-widgets/tests/it/menu/overflow.rs +++ b/crates/ui-widgets/tests/it/menu/overflow.rs @@ -1,11 +1,12 @@ //! A menu taller than its room: it stays inside the room at the width of its rows, scrolls by the strips above and //! below its rows and by the wheel, and reopens at its first row; one that fits shows no strips. A tall submenu of a -//! low row opens upward. A context menu that fits on neither side of the pointer but fits the window covers the -//! pointer instead of scrolling. +//! low row opens upward. A context menu that fits on neither side of the pointer, or of the control a key asked it +//! for, but fits the window covers its anchor instead of scrolling; a tooltip at the pointer never covers the pointer. use craft_host::target::Os; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, Entry, Role, STRIP_BACK, STRIP_FORWARD, Show as _, ShowContainer as _, Trigger}; +use craft_ui::contract::tooltip::DELAY; +use craft_ui::contract::{Bind, Entry, Props as _, Role, STRIP_BACK, STRIP_FORWARD, Show as _, ShowContainer as _, TooltipAt, TooltipSpec, Trigger}; use craft_ui::menu::bar::{MenuBar, MenuTitle}; use craft_ui::menu::{Menu, MenuItem}; use craft_ui::pickers::Select; @@ -147,6 +148,46 @@ fn a_context_menu_too_tall_for_either_side_of_the_pointer_covers_it_and_shows_ev assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}"); } +/// The same menu asked for with Shift+F10 on the focused target: it hangs from the target's rect, which it covers. +#[trial] +fn a_context_menu_a_key_asked_for_covers_its_target_when_it_fits_neither_side() { + let rows = 18; + let (mut fixture, menu, _) = context_menu(290.0, rows); + fixture.key(Key::Escape, Modifiers::NONE).settle(); + assert!(fixture.by_role(Role::MENU).is_empty(), "Escape closes the menu the pointer opened"); + let target = fixture.by_label("Target").expect("the target").rect; + fixture.key(Key::Tab, Modifiers::NONE); + fixture.key(Key::F10, Modifiers::SHIFT).settle(); + let room = fixture.ctx().content_rect(); + let rect = menu_rect(&fixture); + assert!(strips(&fixture, menu).is_none(), "the menu {rect:?} fits the window {room:?}: no strips"); + let (first, last) = (fixture.by_label(&row(0)).expect("the first row").rect, fixture.by_label(&row(rows - 1)).expect("the last row").rect); + assert!(rect.contains_rect(first) && rect.contains_rect(last), "every row shows: {first:?} to {last:?} in {rect:?}"); + assert!(rect.intersects(target), "the menu {rect:?} covers its target {target:?}"); +} + +/// A tooltip at the pointer too tall for either side of it stays off the pointer: it opens on its preferred side, +/// below, where the room is larger, and does not slide up over the pointer as a menu does. +#[trial] +fn a_tooltip_at_the_pointer_too_tall_for_either_side_does_not_cover_the_pointer() { + let text = (0..40).map(|line| format!("Line {line}")).collect::>().join("\n"); + let mut fixture = Fixture::new(move |ui| { + ui.add_space(200.0); + Button::new("Target").tooltip(TooltipSpec::new(text.clone()).at(TooltipAt::Pointer)).show(ui); + }); + fixture.settle(); + let at = fixture.by_label("Target").expect("the target").center(); + fixture.frame(vec![pointer::moved(at)]); + fixture.advance(DELAY); + fixture.settle(); + let tips = fixture.by_role(Role::TOOLTIP); + let tip = tips.first().expect("the tooltip shows").rect; + let room = fixture.ctx().content_rect(); + let lines = fixture.texts().iter().filter(|run| run.text.starts_with("Line ")).fold(Rect::NOTHING, |all, run| all.union(run.rect)); + assert!(lines.height() > at.y - room.top() && lines.height() > room.bottom() - at.y, "the text ({lines:?}) fits on neither side of {at:?}"); + assert!(tip.top() >= at.y, "the tooltip {tip:?} opens below the pointer at {at:?} and does not cover it"); +} + /// A menu of `above` rows over a submenu row whose submenu has `rows` rows, in the fixture's 800 x 600 window. fn low_submenu(above: usize, rows: usize) -> Fixture { let mut fixture = Fixture::new(move |ui| { From 8983476f09e6bde4c6d040d3e3c201310eeed601 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 61/74] Memo trial: a view in a shrinking row runs at most once per measuring sweep of the row --- crates/ui-widgets/tests/it/body/memo_view.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/crates/ui-widgets/tests/it/body/memo_view.rs b/crates/ui-widgets/tests/it/body/memo_view.rs index e175ecd2d..ad0671faa 100644 --- a/crates/ui-widgets/tests/it/body/memo_view.rs +++ b/crates/ui-widgets/tests/it/body/memo_view.rs @@ -1164,6 +1164,7 @@ fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { } let (wide, _) = frame(&mut frames, "B"); assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "an idle frame replays the view"); + assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "an idle frame runs the view at most once per measuring sweep of the row"); let (narrow, after) = frame(&mut frames, "A much longer button label"); assert_eq!(runs_of(&frames, "Line"), [MemoRun::Ran], "a new width runs the view"); assert!(narrow.width() < wide.width(), "the view narrows: {narrow:?} from {wide:?}"); @@ -1172,4 +1173,18 @@ fn a_view_in_a_row_narrows_with_it_and_runs_only_when_its_width_changes() { frame(&mut frames, "A much longer button label"); } assert_eq!(runs_of(&frames, "Line"), [MemoRun::Replayed], "at the same width it replays again"); + assert!(measuring_runs_of(&frames, "Line") <= SWEEPS, "at the same width the view runs at most once per measuring sweep of the row"); +} + +/// The sweeps of a shrinking row's measuring run that show its units: the counting sweep and, for a short row, the +/// sweep that asks its body units for their least. Until FW-310 moves `unbounded` out of the scope key, the counting +/// sweep's call keys apart from the real call's and a memoized unit runs in each sweep; FW-310 tightens this to none. +const SWEEPS: usize = 2; + +/// How many times the views named `name` ran in the last frame outside the real run of its last pass: in sizing and +/// measuring runs. +fn measuring_runs_of(frames: &Frames, name: &str) -> usize { + let ran = + |runs: Vec<(&'static str, egui::Id, MemoRun)>| runs.into_iter().filter(|(of, _, run)| of.contains(name) && *run == MemoRun::Ran).count(); + ran(last_frame_memo_runs(&frames.ctx)) - ran(last_pass_memo_runs(&frames.ctx)) } From 69ed953094d249f2dc769bf25a16ebe6350d0da5 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 62/74] Preferences: host-labelled rows show their rule's help and follow its enabled state --- .../src/patterns/preferences/rows.rs | 8 ++++- .../ui-patterns/tests/it/preferences/page.rs | 35 +++++++++++++++++++ crates/ui-widgets/src/form/field.rs | 18 +++++++--- 3 files changed, 55 insertions(+), 6 deletions(-) diff --git a/crates/ui-patterns/src/patterns/preferences/rows.rs b/crates/ui-patterns/src/patterns/preferences/rows.rs index 46d5c5d62..bc03be521 100644 --- a/crates/ui-patterns/src/patterns/preferences/rows.rs +++ b/crates/ui-patterns/src/patterns/preferences/rows.rs @@ -179,7 +179,13 @@ pub(super) fn show_row(ui: &mut Ui, host: &mut H, } } Kind::CustomRows => { - Stack::new().id_salt(key).show(ui, |ui, _| host.custom_row(ui, key)); + // The host draws the rows and their labels; the rule's enabled state and help apply to them as to a field. + Stack::new().id_salt(key).enabled(row.enabled).show(ui, |ui, _| { + host.custom_row(ui, key); + if let Some(help) = &row.help { + Help::Text(help.clone()).show(ui); + } + }); } Kind::Custom => { field().show(ui, |ui, _| { diff --git a/crates/ui-patterns/tests/it/preferences/page.rs b/crates/ui-patterns/tests/it/preferences/page.rs index edf044554..bc3759740 100644 --- a/crates/ui-patterns/tests/it/preferences/page.rs +++ b/crates/ui-patterns/tests/it/preferences/page.rs @@ -1,5 +1,6 @@ //! `PreferencesPage` over a model with no draft: each edit reaches the model in the pass it lands in. +use craft_ui::buttons::Button; use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _}; use craft_ui::display::Text; use craft_ui::form::Field; @@ -141,3 +142,37 @@ fn a_host_labelled_custom_row_shows_its_label_once() { let fields = tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some("Hosted") && tree.role_of(*key) == Some(Role::GROUP)).count(); assert_eq!(fields, 1, "the host's field is the row's only labelled group"); } + +/// A disabled host-labelled row with help: the host draws a button. +struct HelpedRows; + +impl PreferencesModel for HelpedRows { + fn pages(&self) -> Vec> { + let row = RowSpec::new("general.host", "Hosted", RowKind::CustomRows).help("Drawn with its note").enabled(false); + vec![PageSpec::new("general", "General", vec![row])] + } + + fn set(&mut self, _: &str, _: PrefValue) {} + + fn custom_row(&mut self, ui: &mut Ui, _: &str) { + Button::new("Hosted button").show(ui); + } + + fn custom_page(&mut self, _: &mut Ui, _: &str) {} + + fn reset_page(&mut self, _: &str) {} +} + +/// The rule's help shows under the rows the host draws, and a disabled rule disables them. +#[trial] +fn a_host_labelled_row_shows_its_rules_help_and_follows_its_enabled_state() { + let mut state = PreferencesState::default(); + let mut fixture = Fixture::new(move |ui| { + PreferencesPage::new(Bind::bound(&mut state)).show(ui, &mut HelpedRows); + }); + fixture.settle(); + let button = fixture.by_label("Hosted button").expect("the host's button"); + let help = fixture.texts().iter().find(|run| run.text == "Drawn with its note").map(|run| run.rect).expect("the help shows"); + assert!(help.top() >= button.rect.bottom(), "the help {help:?} sits under the host's rows {:?}", button.rect); + assert!(fixture.tree().is_disabled_key(button.node), "the disabled rule disables the host's button"); +} diff --git a/crates/ui-widgets/src/form/field.rs b/crates/ui-widgets/src/form/field.rs index 5f634c2fd..dee769d3d 100644 --- a/crates/ui-widgets/src/form/field.rs +++ b/crates/ui-widgets/src/form/field.rs @@ -21,6 +21,16 @@ pub enum Help { Status(Tone, Label), } +impl Help { + /// Shows the help line as a field shows it under its control. + pub fn show(&self, ui: &mut Ui) { + match self { + Help::Text(text) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui), + Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone).show(ui), + }; + } +} + /// The style of a field: no look of its own; the label step and the help line carry it. #[derive(Clone, Debug, Default, PartialEq, ComponentStyle)] #[non_exhaustive] @@ -116,10 +126,8 @@ impl Container for Field { Text::new(message.text.clone()).role(TypeRole::Caption).tone(tone).show(ui); return; } - match &self.help { - Some(Help::Text(text)) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui), - Some(Help::Status(tone, text)) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone).show(ui), - None => return, - }; + if let Some(help) = &self.help { + help.show(ui); + } } } From 9bb77ccba4d724f366b2f8827d85c17e752ecd80 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:18:40 +0000 Subject: [PATCH 63/74] Preferences docs name host-labelled rows; trials for their search and for a palette's context menu popup --- .../src/patterns/preferences/model.rs | 12 ++-- crates/ui-patterns/tests/it/docking/native.rs | 71 ++++++++++++++++++- .../ui-patterns/tests/it/preferences/model.rs | 23 ++++++ 3 files changed, 99 insertions(+), 7 deletions(-) diff --git a/crates/ui-patterns/src/patterns/preferences/model.rs b/crates/ui-patterns/src/patterns/preferences/model.rs index f9b2826fd..feecabe47 100644 --- a/crates/ui-patterns/src/patterns/preferences/model.rs +++ b/crates/ui-patterns/src/patterns/preferences/model.rs @@ -102,8 +102,8 @@ pub struct RowSpec<'a> { pub key: &'a str, /// Translated; also the row's accessible name. pub label: &'a str, - /// Extra search text: the key, the English label, synonyms. A [`RowKind::Custom`] row, which the search can't look - /// into, lists the terms of its control here. + /// Extra search text: the key, the English label, synonyms. A [`RowKind::Custom`] or [`RowKind::CustomRows`] row, + /// which the search can't look into, lists the terms of what the host draws here. pub keywords: &'a str, /// Help under the control: "Applies at next launch." A line break starts a new paragraph. The search matches it. pub help: Option<&'a str>, @@ -206,8 +206,9 @@ pub enum RowKind<'a> { Text(&'a str), /// The host draws the control ([`PreferencesModel::custom_row`]); the window labels it beside the control. Custom, - /// The host draws whole rows, labels included ([`PreferencesModel::custom_row`]): the window adds no label. The - /// row's label stays its search text and its group's name. + /// The host draws whole rows, labels included ([`PreferencesModel::custom_row`]): the window adds no label, and + /// shows the row's help under them and its enabled state on them. The row's label stays its search text and its + /// group's name. CustomRows, } @@ -301,7 +302,8 @@ pub trait PreferencesModel { fn set_color(&mut self, key: &str, color: Srgba) { self.set(key, PrefValue::Color(color.into())); } - /// Draws a [`RowKind::Custom`] row's control. + /// Draws a [`RowKind::Custom`] row's control, which the window labels from the row's label (an empty label shows + /// an empty one), or a [`RowKind::CustomRows`] row's whole rows, labels included. fn custom_row(&mut self, ui: &mut Ui, key: &str); /// Draws a [`PageSpec::custom`] page. fn custom_page(&mut self, ui: &mut Ui, page: &str); diff --git a/crates/ui-patterns/tests/it/docking/native.rs b/crates/ui-patterns/tests/it/docking/native.rs index 2cc0dd9c8..d31e9adf9 100644 --- a/crates/ui-patterns/tests/it/docking/native.rs +++ b/crates/ui-patterns/tests/it/docking/native.rs @@ -1,20 +1,23 @@ //! Native dock windows: when a float gets an OS window, what the dock records when the OS moves it, the OS close, and -//! docking the whole window by dragging its title row. +//! docking the whole window by dragging its title row. A context menu opened in a palette places its popup window as +//! it places the menu in the main window. use craft_behavior::dock::{Action, Column, DockEdge, Floating, Group, Layout, Node, Permissions, Workspace}; use craft_behavior::placement::Placement; use craft_host::target::{Backend, Caps, Os, ShellInfo}; +use craft_ui::buttons::Button; use craft_ui::contract::Role; use craft_ui::contract::{Bind, BodyCx, DropMark, PlainData, Show as _, ShowContainer as _, SizeLimits, Tracked}; use craft_ui::display::Text; use craft_ui::docking::{DockConfig, DockGrid, DockPanels, PanelSpec, PanelSpecs}; +use craft_ui::menu::{Menu, MenuItem}; use craft_ui::patterns::dock::DockArea; use craft_ui::popover::DropVeil; use craft_ui::runtime::InstallSpec; use craft_ui::runtime::drag; use craft_ui::testing::access::AccessTree; use craft_ui::testing::input::key_press; -use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::pointer::{moved, press, release, secondary}; use craft_ui::testing::trial; use craft_ui::testing::windows::FakeSystem; use craft_ui_test_kit::windows::{Out, Windows}; @@ -1218,3 +1221,67 @@ fn scaled(focused: bool, rect: Rect, pixels_per_point: f32) -> ViewportInfo { ..ViewportInfo::default() } } + +/// How far down panel 1's body the context menu's target sits, and the menu's rows: in the native palette at +/// `FLOAT_AT`, the pointer on the target has about 300 points above it and below it in the windows' span, and the +/// menu is taller than either and shorter than the span. +const CONTEXT_DROP: f32 = 220.0; +const CONTEXT_ROWS: usize = 18; + +/// A palette whose panel 1 holds a button with a context menu of `CONTEXT_ROWS` rows. +struct ContextTarget; + +impl DockPanels for ContextTarget { + fn body(&mut self, panel: &u32, ui: &mut Ui, _: &mut BodyCx<'_>) { + if *panel != 1 { + return; + } + ui.add_space(CONTEXT_DROP); + let target = Button::new("Target").show(ui); + let _ = Menu::context("Target menu", &target).show(ui, |ui, _| { + for at in 0..CONTEXT_ROWS { + MenuItem::new(format!("Row {at}")).show(ui); + } + }); + } +} + +/// A context menu opened in a native palette shows in a popup OS window; too tall for the room on either side of the +/// pointer but not for the room the popup has, it covers the pointer and shows every row, as it does in the main window. +#[trial] +fn a_context_menu_from_a_native_palette_too_tall_for_either_side_covers_the_pointer_in_its_popup_window() { + let mut dock = NativeDock::on(Os::Windows, Arc::new(FakeSystem::new())); + dock.windows.root_info(scaled(true, MAIN_AT, COLLAPSED_SCALE)); + let mut at = FLOAT_AT; + dock.windows.child_info(scaled(true, at, COLLAPSED_SCALE)); + let mut panels = ContextTarget; + let out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]); + let palette = dock.palette.expect("the palette's window opened"); + let target = node_rect(tree_of_viewport(&out, palette), "Target", Role::BUTTON).expect("the palette shows the target").center(); + for events in [vec![moved(target)], vec![secondary(target, true)], vec![secondary(target, false)]] { + collapsed_frame(&mut dock, &mut panels, &mut at, vec![], events); + } + let mut out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]); + for _ in 0..4 { + out = collapsed_frame(&mut dock, &mut panels, &mut at, vec![], vec![]); + } + let menu = popups(&dock, &out) + .into_iter() + .find(|viewport| !tree_of_viewport(&out, *viewport).with_role(Role::MENU).is_empty()) + .expect("the menu shows in a popup window"); + let rect = window_rect(&dock, menu); + let pointer = at.min + target.to_vec2(); + let room = MAIN_AT.union(at); + assert!( + rect.height() > pointer.y - room.top() && rect.height() > room.bottom() - pointer.y, + "the menu {rect:?} fits on neither side of {pointer:?}" + ); + assert!(room.contains_rect(rect.shrink(0.5)), "the menu {rect:?} stays inside the windows' span {room:?}"); + assert!(rect.contains(pointer), "the menu {rect:?} covers the pointer at {pointer:?}"); + let tree = tree_of_viewport(&out, menu); + let window = Rect::from_min_size(Pos2::ZERO, rect.size()).expand(FIT_ROUNDING); + for row in [0, CONTEXT_ROWS - 1] { + let shown = node_rect(tree, &format!("Row {row}"), Role::MENU_ITEM).unwrap_or_else(|| panic!("row {row} shows")); + assert!(window.contains_rect(shown), "row {row} {shown:?} lies whole in the menu's window {window:?}"); + } +} diff --git a/crates/ui-patterns/tests/it/preferences/model.rs b/crates/ui-patterns/tests/it/preferences/model.rs index ca902ef50..3b370bdcd 100644 --- a/crates/ui-patterns/tests/it/preferences/model.rs +++ b/crates/ui-patterns/tests/it/preferences/model.rs @@ -1,8 +1,11 @@ //! The settings document without a window: rows, applied edits, rebase and row conditions. +use craft_i18n::Folder; +use craft_i18n::matcher::Matcher; use craft_theme::Rgba; use craft_ui::patterns::preferences::{ CustomSettings, PageInfo, PrefValue, PreferencesDraft, PreferencesModel, RowKind, SettingRule, SettingsDocument, SettingsDraft, StandardPage, + list_pages, row_shown, }; use craft_ui::testing::trial; use serde::{Deserialize, Serialize}; @@ -276,3 +279,23 @@ fn a_removed_draft_value_applies_as_no_value() { assert_eq!(edits, vec![("memory.percent".to_owned(), None)]); assert_eq!(doc.saved().memory.percent, None); } + +/// A row whose app draws its own labels is found by its rule's label: the search lists its page and shows it. +#[trial] +fn the_search_finds_a_host_labelled_row_by_its_rules_label() { + let rules = vec![ + SettingRule::new("export.format").choices(&[("png", "PNG"), ("webp", "WebP")]), + SettingRule::new("export.tablet").label("Tablet pressure").custom_rows(), + ]; + let doc = SettingsDocument::new(ExportPrefs::default()).expect("serializes").rules(rules); + let pages = PreferencesModel::pages(&doc); + let matcher = Matcher::new(&Folder::new("en"), "tablet"); + let listed = list_pages(&pages, &matcher); + let found: Vec<(&str, bool)> = listed + .iter() + .flat_map(|listed| pages[listed.index].groups.iter().flat_map(|group| group.rows.iter()).map(move |row| (row, listed))) + .filter(|(row, listed)| row_shown(&matcher, listed, row)) + .map(|(row, _)| (row.key, matches!(row.kind, RowKind::CustomRows))) + .collect(); + assert_eq!(found, [("export.tablet", true)], "the search shows the host-labelled row alone"); +} From b62b64af52af53c22033ddecc3e8ef9fb79fa838 Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 06:46:13 +0000 Subject: [PATCH 64/74] FloatingGroup::scale is a declared prop (display scale, pixels per point) --- crates/ui-panels/src/docking/floating.rs | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/crates/ui-panels/src/docking/floating.rs b/crates/ui-panels/src/docking/floating.rs index fc6369b3b..ba0c58ef9 100644 --- a/crates/ui-panels/src/docking/floating.rs +++ b/crates/ui-panels/src/docking/floating.rs @@ -277,8 +277,9 @@ pub struct FloatingGroup<'a> { placed: Option, /// The width a resize gave the collapsed column this pass. collapsed_width: Option, - /// The display scale of the OS window the group shows in, which sizes the rule under its title row; unset, the - /// running window's. + /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the + /// running window's: its chrome, the rule under its title row included, is sized at that scale. + #[prop(quantity = "display scale, pixels per point")] scale: Option, /// Starts the window-unit drag; set by `window_of`. start_drag: Option>, @@ -363,14 +364,6 @@ impl<'a> FloatingGroup<'a> { self } - /// The display scale of the OS window the group shows in (`native::pixels_per_point`), when it differs from the - /// running window's: its chrome is sized at that scale. - #[must_use] - pub fn scale(mut self, pixels_per_point: f32) -> Self { - self.scale = Some(pixels_per_point); - self - } - /// The action parts at the end of the title row, in reading order. #[must_use] pub fn actions(mut self, actions: impl IntoIterator) -> Self { From 2ef7bbff3843f4fbe7f0af8f3461966e65fced7d Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:33:46 +0000 Subject: [PATCH 65/74] A field labelled above sits on a row's line by its control, as a control labelled above does A container labelled above its body reports its body's first control line as the line it sits on in a row, so a button beside a field labelled above sits level with the field's control, not its label. --- crates/ui-contract/src/contract/body/hooks.rs | 9 +++++++-- crates/ui-contract/src/layout/body.rs | 11 ++++++----- crates/ui-widgets/tests/it/layout/row_line.rs | 13 +++++++------ 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/crates/ui-contract/src/contract/body/hooks.rs b/crates/ui-contract/src/contract/body/hooks.rs index 70f69657c..3661a1a5f 100644 --- a/crates/ui-contract/src/contract/body/hooks.rs +++ b/crates/ui-contract/src/contract/body/hooks.rs @@ -416,10 +416,15 @@ impl ShapeHooks for BodyHooks<'_> { layout_memory::measured(ctx, sub(id, "first")).map(|found| found.took.y) } - /// A container with no header whose body is an unwrapped row reports that row's line as its first line. + /// A container with no header whose body is an unwrapped row reports that row's line as its first line, and one + /// labelled above its body the line of its body's first control: it sits on a row's line by that control, as a + /// control labelled above does. fn first_is_row_line(&self, comp: &C) -> bool { let props = comp.props(Internal::new()); - props.header.is_none() && super::size::unwrapped_row(props) + let above = props.label.as_ref().is_some_and(|side| { + matches!(side.layout, label::FieldLayout::Above | label::FieldLayout::Caption(_)) && side.kind != label::LabelKind::Hidden + }); + props.header.is_none() && (above || super::size::unwrapped_row(props)) } fn member(&self, comp: &C) -> bool { diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index de1ac5bc8..5a7d9148a 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -1155,9 +1155,10 @@ pub(crate) struct InFlow { /// rows run along Y, or a container whose first child is one. The child is one line when that centre lies at /// half its height (`one_line`). pub first: Option, - /// `first` is the line of the child's own unwrapped `Row` body, or of the control of a labelled control's row: the - /// child sits on a row's line by it even when it is more than one line (a nested row with a child of two lines, a - /// check box whose label has a detail line under it, a control under its label). + /// `first` is the line of the child's own unwrapped `Row` body, of the control of a labelled control's row, or of + /// the first control of a container labelled above its body: the child sits on a row's line by it even when it is + /// more than one line (a nested row with a child of two lines, a check box whose label has a detail line under it, + /// a control or a field under its label). pub line: bool, } @@ -1166,8 +1167,8 @@ const ONE_LINE_SLACK: f32 = 0.5; /// The centre of the line of a child `height` tall whose first line's centre lies `first` below its top, when the /// child is one line: a control, a row of one-line children, a container around one line (a field with its label -/// beside its control). A child of more than one line (a column, a field with its label above or a help line below) -/// has its first line above its middle. +/// beside its control). A child of more than one line (a column, a field with a help line below) has its first line +/// above its middle. fn one_line(first: Option, height: f32) -> Option { first.filter(|first| (2.0 * first - height).abs() <= ONE_LINE_SLACK) } diff --git a/crates/ui-widgets/tests/it/layout/row_line.rs b/crates/ui-widgets/tests/it/layout/row_line.rs index 9ba63754d..92a3cd6b8 100644 --- a/crates/ui-widgets/tests/it/layout/row_line.rs +++ b/crates/ui-widgets/tests/it/layout/row_line.rs @@ -1,6 +1,7 @@ //! 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 its label above or a help line below) sits at the row's top. A control with -//! its label after it sits on the line by its control, as a bare control does, in a row and in a grid's cell. +//! 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. use craft_behavior::ColumnWidth; use craft_theme::ControlSize; @@ -107,10 +108,10 @@ fn columns_sit_at_the_rows_top_and_lines_on_the_line() { assert!(four.top() <= control(&fixture, &["Go"]).top() + ROUNDING, "the four-line column starts below the button's top"); } -/// A field labelled above its control is two lines and sits at the row's top, so a button beside it sits level with -/// the label, not the control. +/// A field labelled above its control sits on the row's line by its control, as a control labelled above does: a +/// button beside it sits level with the control, and the label stands above the line. #[trial] -fn a_field_labelled_above_sits_at_the_rows_top() { +fn a_field_labelled_above_sits_on_the_row_line_by_its_control() { let fixture = settled(|ui| { Row::new().show(ui, |ui, _| { Field::new("Caption").layout(FieldLayout::Above).sizing(Sizing::Content).show(ui, |ui, _| { @@ -121,7 +122,7 @@ fn a_field_labelled_above_sits_at_the_rows_top() { }); let (caption, control, button) = (text(&fixture, "Caption"), text(&fixture, "X"), text(&fixture, "Y")); assert!(caption.bottom() < control.top(), "the label sits above its control"); - assert!(button.center().y < control.top(), "the button {button:?} sits level with the label, above the control {control:?}"); + assert!((button.center().y - control.center().y).abs() <= ROUNDING, "the button {button:?} sits on the control's line {control:?}"); } /// A check box whose label runs to a second line under it, beside a button in a row: its box sits on the button's From 6c72055339f113d73afdb9a7b85cfc0a86afbc5a Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 10:38:11 +0000 Subject: [PATCH 66/74] A memoized row unit's room follows the row, not its own content; a call's key is its own A memoized view the row does not narrow shows as in no room, in the row's flow region, and its content sizes from its content along x; only a row that narrows it cuts its room to the width it gives. The cap of a view the row did not narrow was its own counted width, so new content changed the view's room and the discard pass ran it again. The shrink record carries whether the row narrowed the unit. The replay decision of a pass covers the kept run; each call compares its own key. A row's counting sweep calls the view with another key (its content shows unbounded): that call no longer decides the pass against the real call after it, and a sizing call takes the extent the last sizing run measured for its own key. --- crates/ui-contract/src/contract/lazy.rs | 8 ++- crates/ui-contract/src/contract/memo_view.rs | 5 +- crates/ui-contract/src/layout/body.rs | 27 ++++++--- crates/ui-contract/src/runtime/env.rs | 8 ++- .../ui-contract/src/runtime/layout_memory.rs | 28 +++++---- crates/ui-contract/src/runtime/lazy.rs | 25 ++++---- .../ui-contract/tests/it/contract/memo_row.rs | 59 +++++++++++++++++++ crates/ui-contract/tests/it/contract/mod.rs | 1 + 8 files changed, 128 insertions(+), 33 deletions(-) create mode 100644 crates/ui-contract/tests/it/contract/memo_row.rs diff --git a/crates/ui-contract/src/contract/lazy.rs b/crates/ui-contract/src/contract/lazy.rs index 01d74889f..b087b47f6 100644 --- a/crates/ui-contract/src/contract/lazy.rs +++ b/crates/ui-contract/src/contract/lazy.rs @@ -78,11 +78,13 @@ impl Lazy { }; let rtl = ui.layout().prefer_right_to_left(); let memo = matches!(key, Key::Memo(_)); - // A memoized view is one unit of the shrinking row around it: it shows at most the width the row's measuring - // run gave it, the room its place then holds, so a new width runs it. + // A memoized view is one unit of the shrinking row around it. A row that narrows it gives it at most the width + // its measuring run settled on, the room its place then holds, so a new width runs it. A view the row does not + // narrow shows as in no room, in the row's flow region: its room does not follow its own content's width, so a + // new content runs it once and the discard pass its new size asks for replays that run. let shrink = Env::of(ui).shrink.filter(|_| memo); let cap = match shrink { - Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id), + Some(Shrink::Apply(row)) => crate::layout::shrink_cap(&ctx, row, id).filter(|cap| cap.narrowed), _ => None, }; let available = cap.map_or_else(|| flow_region(ui), |cap| at_most(flow_region(ui), rtl, cap.width)); diff --git a/crates/ui-contract/src/contract/memo_view.rs b/crates/ui-contract/src/contract/memo_view.rs index d503b1895..aaea525f7 100644 --- a/crates/ui-contract/src/contract/memo_view.rs +++ b/crates/ui-contract/src/contract/memo_view.rs @@ -53,8 +53,9 @@ use std::sync::Arc; /// cursor) does not reach in, so the room it is given reaches it only through its place. To the body /// around it the view is one unit, sized by its content's measure. In a shrinking `Row` it is a unit the row narrows /// as it narrows a body unit: from what its content takes in no room down to what it takes with every leaf at its -/// least. The width the row gives it is the room of its place, and the leaves of its content fit that room, as they -/// fit the room of a `Stack` the view is shown in. +/// least. When the row narrows it, the width the row gives it is the room of its place; otherwise it shows as in no +/// room, in the row's flow region. Its content sizes from its content along x, and its leaves fit the view's room, as +/// they fit the room of a `Stack` the view is shown in. /// /// What `show` returns holds layout facts only (a size, a rect, which part took the room). A replay returns the kept /// value again, moved with the record when the room moved (`Shift`), so an event returned through it would arrive once diff --git a/crates/ui-contract/src/layout/body.rs b/crates/ui-contract/src/layout/body.rs index 5a7d9148a..eef131a3a 100644 --- a/crates/ui-contract/src/layout/body.rs +++ b/crates/ui-contract/src/layout/body.rs @@ -541,11 +541,18 @@ pub(crate) struct ShrinkCap { pub width: f32, /// The unit dropped out of the row (`shrink_or_drop`): it shows nothing and takes no place. pub dropped: bool, + /// The row gave the unit less than it asks for in no room, or dropped it: what the unit shows depends on the row's + /// room. A unit the row did not narrow shows as in no room. + pub narrowed: bool, } /// What the shrink step of the row `row` gave its unit `leaf` in this pass's measuring run. pub(crate) fn shrink_cap(ctx: &egui::Context, row: Id, leaf: Id) -> Option { - layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, dropped)| ShrinkCap { width: found.took.x, dropped }) + layout_memory::shrink(ctx, shrink_key(row, leaf)).map(|(found, given)| ShrinkCap { + width: found.took.x, + dropped: given.dropped, + narrowed: given.narrowed, + }) } fn shrink_key(row: Id, leaf: Id) -> Id { @@ -649,9 +656,13 @@ fn shrink_or_drop( let shown_first: Vec = first.iter().zip(&kept).filter(|(_, kept)| **kept).map(|(first, _)| *first).collect(); let mut widths = shrink_in_turns(&shown, &pick(whole), &shown_first, fixed, room, order).into_iter(); kept.iter() - .map(|kept| match kept { - true => ShrinkCap { width: widths.next().unwrap_or_default(), dropped: false }, - false => ShrinkCap { width: 0.0, dropped: true }, + .zip(units) + .map(|(kept, unit)| match kept { + true => { + let width = widths.next().unwrap_or_default(); + ShrinkCap { width, dropped: false, narrowed: unit.ideal - width >= 0.5 } + } + false => ShrinkCap { width: 0.0, dropped: true, narrowed: true }, }) .collect() } @@ -732,21 +743,23 @@ fn run_shrinking(ui: &mut Ui, id: Id, mut body: impl FnMut(&mut Ui) -> R) -> let widths = if room.is_finite() { shrink_or_drop(&units, &whole, &first, (fixed + held, gap), room, order, drops) } else { - units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false }).collect() + units.iter().map(|unit| ShrinkCap { width: unit.ideal, dropped: false, narrowed: false }).collect() }; // A levelled unit took no place of its own content in the first sweep (it measured each level apart), so the // records its content's run leaves for the real run come from a sweep at the levels given. let mut again = !levelled.is_empty(); for (leaf, cap) in continuous.iter().zip(widths) { let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(cap.width, 0.0)); - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, cap.dropped); + let given = layout_memory::ShrinkGiven { dropped: cap.dropped, narrowed: cap.narrowed }; + layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); // Half a point: less than a pixel shows at any scale the box runs. again |= (leaf.took - cap.width).abs() >= 0.5; } for (leaf, level) in levelled.iter().zip(levels) { // The level travels as the record's height (`level_of`). let measured = layout_memory::Measured::new(Vec2::new(room, 0.0), Vec2::new(width_at(leaf, level), level as f32)); - layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, false); + let given = layout_memory::ShrinkGiven { dropped: false, narrowed: level > 0 }; + layout_memory::emit_shrink(&ctx, shrink_key(id, leaf.leaf), measured, given); } again }; diff --git a/crates/ui-contract/src/runtime/env.rs b/crates/ui-contract/src/runtime/env.rs index 891f8abb6..bf7ac1ed0 100644 --- a/crates/ui-contract/src/runtime/env.rs +++ b/crates/ui-contract/src/runtime/env.rs @@ -410,13 +410,19 @@ impl Scoped { } /// Starts the layout room of a memoized view's content (`start_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`). + /// (`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 content along x, as the row counted it: a child that fills there takes + /// its measured width, not the row's flow region a view the row does not narrow is shown in. 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(_))); self.start_room(); if fits { self.shrink = Some(Shrink::Fit); } + if row_unit { + self.content.0 = true; + } } /// Whether a memoized view shown in flow here fits its content to its room, as a leaf here would: in a `Stack` body, diff --git a/crates/ui-contract/src/runtime/layout_memory.rs b/crates/ui-contract/src/runtime/layout_memory.rs index 3894fd46b..84ab4bb8c 100644 --- a/crates/ui-contract/src/runtime/layout_memory.rs +++ b/crates/ui-contract/src/runtime/layout_memory.rs @@ -97,8 +97,8 @@ pub(crate) type TakeBack = Box; #[derive(Clone, Debug, PartialEq)] enum Recorded { Measured(Measured), - /// The width a row's shrink step gave a unit, as a measure, and whether the unit dropped out of the row. - Shrink(Measured, bool), + /// The width a row's shrink step gave a unit, as a measure, and whether it narrowed the unit or dropped it. + Shrink(Measured, ShrinkGiven), Text(Option>), } @@ -499,10 +499,18 @@ pub(crate) fn emit_record(ctx: &Context, id: Id, measured: Measured) { emit(ctx, id, Recorded::Measured(measured)); } -/// Hands forward what a row's shrink step gave a unit under `id`: its width as `measured` and whether it `dropped` -/// out of the row. It serves as [`emit_record`]'s measure does. -pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, dropped: bool) { - emit(ctx, id, Recorded::Shrink(measured, dropped)); +/// Whether a row's shrink step narrowed a unit below what it asks for in no room, and whether it dropped the unit out +/// of the row. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ShrinkGiven { + pub dropped: bool, + pub narrowed: bool, +} + +/// Hands forward what a row's shrink step gave a unit under `id`: its width as `measured` and what else it `given`. +/// It serves as [`emit_record`]'s measure does. +pub(crate) fn emit_shrink(ctx: &Context, id: Id, measured: Measured, given: ShrinkGiven) { + emit(ctx, id, Recorded::Shrink(measured, given)); } /// Hands forward a text a run found under `id` that content outside the body it runs in shows, as `emit_record` @@ -565,7 +573,7 @@ fn kept_differs(last: &Found, now: &Recorded, pass: u64, tolerance: f32) -> Opti }; let differs = match (was, now) { (Recorded::Measured(was), Recorded::Measured(now)) => measures(was, now, false), - (Recorded::Shrink(was, was_dropped), Recorded::Shrink(now, now_dropped)) => measures(was, now, was_dropped != now_dropped), + (Recorded::Shrink(was, was_given), Recorded::Shrink(now, now_given)) => measures(was, now, was_given != now_given), (was, now) => was != now, }; if *at != pass || !differs { @@ -922,12 +930,12 @@ pub(crate) fn measured(ctx: &Context, id: Id) -> Option { } /// What a row's shrink step of this pass gave the unit under `id` ([`emit_shrink`]): its width as a measure and -/// whether it dropped out of the row. -pub(crate) fn shrink(ctx: &Context, id: Id) -> Option<(Measured, bool)> { +/// whether it narrowed or dropped the unit. +pub(crate) fn shrink(ctx: &Context, id: Id) -> Option<(Measured, ShrinkGiven)> { let moment = Moment::of(ctx); let pass = ctx.cumulative_pass_nr(); with(ctx, &moment, |memory| match memory.measured.get(&id).filter(|found| found.pass == pass && !memory.probing()) { - Some(Found { recorded: Recorded::Shrink(measured, dropped), .. }) => Some((*measured, *dropped)), + Some(Found { recorded: Recorded::Shrink(measured, given), .. }) => Some((*measured, *given)), _ => None, }) } diff --git a/crates/ui-contract/src/runtime/lazy.rs b/crates/ui-contract/src/runtime/lazy.rs index 5aa98cc1d..5e4031df6 100644 --- a/crates/ui-contract/src/runtime/lazy.rs +++ b/crates/ui-contract/src/runtime/lazy.rs @@ -449,10 +449,12 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// Whether the memoized view `id` adds its last real run to this pass in place of running, the extent that run took in /// a run of this kind (`sizing`: the room a sizing run offers it, `None` outside a sizing pass), the rect the kept real /// run takes now and the shift its record moves by. The first run of a pass decides from what changed since that run; a -/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. A sizing -/// run of a pass that replays takes the extent the last sizing run measured of the content the kept run showed (its -/// key) in the room it offers now; when that sizing run showed other content or had another room, or there was none, it -/// runs once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still +/// real run also needs a `place` the run can move to (`Place::shift_to`), which a measuring run cannot tell. Each call +/// also needs the key of the kept run: any other call with another key (a row's counting sweep shows the content +/// unbounded, and the scope key holds that) runs, and leaves the decision of the pass alone for the calls after it. A +/// sizing run of a pass that replays takes the extent the last sizing run measured of the content it shows (its key) in +/// the room it offers now; when that sizing run showed other content or had another room, or there was none, it runs +/// once as a measuring run, which keeps no record and leaves the decision of the pass alone, so the real run still /// replays. /// /// It replays when its last run was in an earlier pass, of this frame or an earlier one, and since then: @@ -464,8 +466,8 @@ pub(crate) fn replay(ctx: &Context, id: Id) { /// - no intent of this pass is routed to a component in it (an AccessKit request on one of its nodes); /// - no value it read (a bound value, an inspection record, a command's state) changed this frame (`note_edit`), or, /// replaying a run of this frame, after that run started; -/// - its key is the one of its last run (its props key after that run), and its environment (theme, density, scale, -/// language, window active) the one it ran in; +/// - the call's key is the one of its last run (its props key after that run), and its environment (theme, density, +/// scale, language, window active) the one it ran in; /// - the run did nothing a replay cannot repeat (`runtime::replay`) and asked for no discard pass: what it added is /// what the pass was thrown away for; /// - the shown life of no component it showed ended (`memory::ended_since`): a replay would show memory state that is @@ -492,6 +494,10 @@ pub(crate) fn settled( // Usually `None`: only the values written this frame. let edited = changes.edited_in(frame); let entry = store.touch(owner, id, frame); + // The decision of the pass covers the kept run; the key is the call's own. A call that shows other content (a + // row's counting sweep, which shows it unbounded) leaves the decision alone for the calls after it: a sizing call + // takes the extent the last sizing run measured of its own content, and any other runs. + let keyed = entry.settled.as_ref().is_some_and(|settled| settled.key == key) || sizing.is_some(); let replays = match entry.replays { Some((decided_in, replays)) if decided_in == pass_nr => replays, _ => { @@ -500,7 +506,6 @@ pub(crate) fn settled( // A run of this frame read the values edited before it started. let edited = edited_since(edited.as_ref(), if settled.frame < frame { 0 } else { settled.edits }); (settled.frame < frame || settled.pass < pass_nr) - && settled.key == key && !settled.engaged && !facts.blocked && !facts.discards @@ -518,14 +523,14 @@ pub(crate) fn settled( Some(place) => settled.place.shift_to(settled.rect, place, settled.record.movable(), transformed), None => Some(Moved { shift: RecordShift::none(settled.place.clip), with_clip: true }), }; - let settled = entry.settled.clone().filter(|_| replays).and_then(|settled| Some((moved(&settled)?, settled))); - if replays && settled.is_none() { + let settled = entry.settled.clone().filter(|_| replays && keyed).and_then(|settled| Some((moved(&settled)?, settled))); + if replays && keyed && settled.is_none() { entry.replays = Some((pass_nr, false)); } settled.and_then(|(moved, settled)| { // An extent depends on the room's size, not on where the room is. let size = match sizing { - Some(room) => entry.sizes[0].filter(|measured| measured.key == settled.key && measured.room.size() == room.size())?.size, + Some(room) => entry.sizes[0].filter(|measured| measured.key == key && measured.room.size() == room.size())?.size, None => entry.sizes[1].filter(|measured| measured.key == settled.key).map_or(settled.rect.size(), |measured| measured.size), }; Some((size, moved, settled)) diff --git a/crates/ui-contract/tests/it/contract/memo_row.rs b/crates/ui-contract/tests/it/contract/memo_row.rs new file mode 100644 index 000000000..1c5019b3e --- /dev/null +++ b/crates/ui-contract/tests/it/contract/memo_row.rs @@ -0,0 +1,59 @@ +//! A memoized view that is one unit of a shrinking row: the row's counting sweep calls it with another key than its +//! real run, and that call leaves the replay decision of the pass to the calls after it and reuses its own measure. + +use craft_ui::contract::{MemoProps, MemoView, Props as _, Show as _, ShowContainer as _, Sizing}; +use craft_ui::layout::BodyLayout; +use craft_ui::testing::layout::in_region; +use craft_ui::testing::{Frames, MemoRun, last_frame_memo_runs, last_pass_memo_runs, trial}; +use craft_ui_test_kit::contract::{Panel, Probe, Seen}; +use egui::{Pos2, Rect, Ui, Vec2}; +use std::cell::{Cell, RefCell}; + +/// A view that shows one probe `width` wide. +#[derive(MemoProps)] +struct Widened { + width: f32, +} + +fn widened(props: &mut Widened, ui: &mut Ui) { + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).size(Vec2::new(props.width, 20.0)).id_salt("content").show(ui); +} + +/// How the `Widened` views took part in `runs`. +fn of_view(runs: Vec<(&'static str, egui::Id, MemoRun)>) -> Vec { + runs.into_iter().filter(|(name, _, _)| name.contains("Widened")).map(|(_, _, run)| run).collect() +} + +/// A memoized view in a row that is not short, whose new content is wider: it runs once in the real run that meets the +/// new props and once as a measuring run in the row's counting sweep, whose call keys apart from the real run's +/// (the content shows unbounded there). The real run of the discard pass that sweep belongs to replays, and so does +/// every call of the next frame, a counting sweep's included. +#[trial] +fn a_memoized_row_unit_replays_after_the_rows_counting_call_with_another_key() { + let width = Cell::new(60.0); + let mut frames = Frames::new(); + let frame = |frames: &mut Frames| { + frames.frame(vec![], |ui| { + in_region(ui, Rect::from_min_size(Pos2::new(10.0, 10.0), Vec2::new(400.0, 40.0)), |ui| { + Panel::new().layout(BodyLayout::row()).sizing(Sizing::FillWidth).id_salt("row").show(ui, |ui, _| { + let _ = MemoView::new("view", Widened { width: width.get() }, widened).show(ui); + let seen = RefCell::new(Seen::default()); + Probe::new(&seen).id_salt("after").show(ui); + }); + }); + }); + }; + for _ in 0..30 { + frame(&mut frames); + } + assert_eq!(of_view(last_frame_memo_runs(&frames.ctx)), [MemoRun::Replayed], "an idle frame replays the view"); + width.set(90.0); + frame(&mut frames); + let calls = of_view(last_frame_memo_runs(&frames.ctx)); + assert_eq!(calls.iter().filter(|run| **run == MemoRun::Ran).count(), 2, "one real run and one measuring run: {calls:?}"); + assert_eq!(of_view(last_pass_memo_runs(&frames.ctx)), [MemoRun::Replayed], "the discard pass's real call replays: {calls:?}"); + frame(&mut frames); + let calls = of_view(last_frame_memo_runs(&frames.ctx)); + assert!(calls.iter().all(|run| *run == MemoRun::Replayed), "the next frame replays the view in every call: {calls:?}"); +} diff --git a/crates/ui-contract/tests/it/contract/mod.rs b/crates/ui-contract/tests/it/contract/mod.rs index 556140903..2e95af053 100644 --- a/crates/ui-contract/tests/it/contract/mod.rs +++ b/crates/ui-contract/tests/it/contract/mod.rs @@ -5,6 +5,7 @@ pub(crate) mod gesture; pub(crate) mod hit_order; pub(crate) mod level; pub(crate) mod memo_key; +pub(crate) mod memo_row; pub(crate) mod pages; pub(crate) mod pointer; pub(crate) mod style; From efb06e99510879fa2be07fda891794d44310b769 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 11:54:42 +0100 Subject: [PATCH 67/74] Home layout: the rail's look from before the PhotoCraft port The desktop Home layout (`StartScreen::home_layout`) drew its rail with the dialog button look and inline links: pill New and Open, Home as a filled pill, Learn and the community links underlined in the link colour, and the page title as a Display heading. The rail is back to how PhotoCraft drew it before it moved onto the framework (photocraft#15449): - New and Open at the control radius. - Every link a full-width row with its icon: muted at rest, normal under the pointer; a URL row opens its URL (its tooltip), a command row fires it. - The selected row (Home) keeps normal ink and has an accent bar at its leading edge. - The page title as a Heading. Only the Home layout changes; the other start-screen layouts keep their links. Part of photocraft#15476 Co-Authored-By: Claude Opus 5.5 --- crates/ui-shell/src/shell/start.rs | 88 +++++++++++++++++++++++-- crates/ui-shell/tests/it/shell/start.rs | 34 ++++++++++ 2 files changed, 118 insertions(+), 4 deletions(-) diff --git a/crates/ui-shell/src/shell/start.rs b/crates/ui-shell/src/shell/start.rs index f9d2447c1..1b3f20f94 100644 --- a/crates/ui-shell/src/shell/start.rs +++ b/crates/ui-shell/src/shell/start.rs @@ -59,6 +59,13 @@ const HOME_DROP_ICON: f32 = 34.0; // design: allow[literal-size/vec2](the desktop Home page's outer margins are larger than any spacing token) const HOME_DESKTOP_INSET: Vec2 = vec2(36.0, 54.0); const HOME_DROP_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-drop", home_drop_look); +/// New and Open on the desktop Home page: the control radius, not the pill of dialog buttons. +const HOME_NEW_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-new", home_new_look); +const HOME_OPEN_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-open", home_open_look); +/// A row of the Home rail (Home, Learn, the community links): no edge or fill at rest, muted ink that turns normal +/// under the pointer. The selected row keeps normal ink and an accent bar at its leading edge. +const HOME_ROW_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-row", home_row_look); +const HOME_ROW_SELECTED_LOOK: CustomVariant = CustomVariant::new::("craft_ui.home-row-selected", home_row_selected_look); /// The revealed part of a recent row that takes the file off the list. pub(super) const REMOVE: TrailingPart = TrailingPart::new(0); @@ -586,9 +593,9 @@ impl HomeLayout<'_> { Stack::new().id_salt("home-page").fill().pad(Pad::Regular).gap(gap).scroll(Scroll::vertical()).show_at(ui, content, |ui, cx| { let top = ui.available_rect_before_wrap().top(); if !wide { - let _ = Row::new().gap(Gap::Tight).fill_width().show(ui, |ui, _| new_and_open(page, ui, Sizing::FillWidth)); + let _ = Row::new().gap(Gap::Tight).fill_width().show(ui, |ui, _| home_new_and_open(page, ui)); } - let _ = Text::new(self.title.clone()).role(TypeRole::Display).show(ui); + let _ = Text::new(self.title.clone()).role(TypeRole::Heading).show(ui); home_divider(ui); sections(ui, cx, top + content.height() / 2.0, wide); if !wide { @@ -604,7 +611,7 @@ impl HomeLayout<'_> { let stack = || Stack::new().id_salt("home-rail").pad(Pad::Regular).gap(Gap::Section); let top = |ui: &mut Ui| { let _ = Stack::new().id_salt("home-actions").gap(Gap::Stack).fill_width().show(ui, |ui, _| { - new_and_open(page, ui, Sizing::FillWidth); + home_new_and_open(page, ui); }); home_divider(ui); home_links(ui, page, "home-nav", links, Gap::Section); @@ -654,7 +661,8 @@ fn home_columns(room: Rect, rtl: bool) -> (Rect, Rect) { fn home_links(ui: &mut Ui, page: &Page<'_>, id: &'static str, links: &[StartLink], gap: Gap) { if !links.is_empty() { - let _ = Stack::new().id_salt(id).gap(gap).label(page.words.start_links.clone()).fill_width().show(ui, |ui, _| link_items(ui, links, true)); + let _ = + Stack::new().id_salt(id).gap(gap).label(page.words.start_links.clone()).fill_width().show(ui, |ui, cx| home_link_items(ui, cx, links)); } } @@ -675,6 +683,78 @@ fn home_edge(tokens: &Tokens) -> Rgba { if color.line.divider == color.surface.canvas { color.text.faint } else { color.line.divider } } +fn home_new_look(tokens: &Tokens) -> VariantLook { + Variant::PRIMARY.resolve(tokens).radius(RadiusStep::Control) +} + +fn home_open_look(tokens: &Tokens) -> VariantLook { + home_drop_look(tokens) +} + +fn home_row_look(tokens: &Tokens) -> VariantLook { + let mut look = Variant::GHOST.resolve(tokens).radius(RadiusStep::Control); + look.text.rest = tokens.color.text.muted; + look.muted.rest = tokens.color.text.muted; + look +} + +fn home_row_selected_look(tokens: &Tokens) -> VariantLook { + Variant::GHOST.resolve(tokens).radius(RadiusStep::Control) +} + +/// New and Open on the desktop Home page, filling the rail (or the narrow page's row). +fn home_new_and_open(page: &Page<'_>, ui: &mut Ui) { + let words = page.words; + let new = Button::new(words.new.clone()).id_salt("new").variant(Variant::Custom(HOME_NEW_LOOK)).sizing(Sizing::FillWidth); + if clicked(&new.show(ui)) { + page.push(StartAction::New); + } + let open = Button::new(words.open.clone()).id_salt("open").variant(Variant::Custom(HOME_OPEN_LOOK)).sizing(Sizing::FillWidth); + if clicked(&open.show(ui)) { + page.push(StartAction::Open); + } +} + +/// The rows of a Home rail group: each link is a full-width row with its icon, a URL opening in the browser (the URL +/// is its tooltip) and a command firing as a pointer activation. A selected row has an accent bar at its leading edge. +fn home_link_items(ui: &mut Ui, cx: &mut BodyCx<'_>, links: &[StartLink]) { + for (at, link) in links.iter().enumerate() { + let look = if link.selected { HOME_ROW_SELECTED_LOOK } else { HOME_ROW_LOOK }; + let mut button = + Button::new(link.label.clone()).id_salt(("start-link", at)).variant(Variant::Custom(look)).align(HAlign::Start).sizing(Sizing::FillWidth); + if let Some(icon) = &link.icon { + button = button.icon(icon.clone()); + } + if let StartLinkTarget::Url(url) = &link.target { + button = button.tooltip(url.clone()); + } + let shown = button.show(ui); + if link.selected { + home_selected_bar(ui, shown.response().rect); + } + if clicked(&shown) { + match &link.target { + StartLinkTarget::Url(url) => cx.open_url(url, false), + StartLinkTarget::Command(command) => { + let _ = commands::fire(ui.ctx(), command.clone(), FireSource::Pointer); + } + } + } + } +} + +/// The accent bar at the leading edge of the selected Home row, as tall as its icon. +fn home_selected_bar(ui: &mut Ui, row: Rect) { + let env = Env::of(ui); + let style = StyleCx::of_env(ui.ctx(), &env); + // The accent mark's look: `accent.solid`, `stroke.thick` wide. + let look = style.rule(RuleKind::DropMark); + let scale = ui.ctx().pixels_per_point(); + let bar = Rect::from_center_size(row.center(), vec2(row.width(), env.tokens.size.icon.md.min(row.height()))); + let side = if env.direction.is_rtl() { RectSide::Right } else { RectSide::Left }; + ui.painter().extend(Rule::edge(&look, bar, side, scale)); +} + fn home_drop_look(tokens: &Tokens) -> VariantLook { let mut look = Variant::SECONDARY.resolve(tokens).radius(RadiusStep::Control); if let Some(edge) = &mut look.edge { diff --git a/crates/ui-shell/tests/it/shell/start.rs b/crates/ui-shell/tests/it/shell/start.rs index 877371463..8b648caa8 100644 --- a/crates/ui-shell/tests/it/shell/start.rs +++ b/crates/ui-shell/tests/it/shell/start.rs @@ -210,6 +210,40 @@ fn the_home_screen_places_navigation_to_the_left_of_recent_files() { assert!(rect("GitHub").top() - rect("Discord").bottom() >= 6.0); } +/// The Home rail's links are rows as wide as the rail, as New and Open are, not inline links; the selected row (Home) +/// shows a bar at its leading edge and the others none. +#[trial] +fn the_home_rail_shows_its_links_as_rows_with_a_bar_on_the_selected_one() { + use egui::{Shape, vec2}; + + let (mut fixture, _) = home_screen(true); + fixture.room(vec2(1100.0, 700.0)).settle(); + let new = fixture.by_label("New…").expect("New").rect; + let rows: Vec<_> = + ["Home", "Learn", "Website", "Discord", "GitHub"].into_iter().map(|label| (label, fixture.by_label(label).expect(label).rect)).collect(); + for (label, row) in &rows { + assert!((row.width() - new.width()).abs() < 1.0, "{label} {row:?} is a row as wide as New {new:?}"); + } + let rect = |label: &str| rows.iter().find(|(name, _)| *name == label).map(|(_, row)| *row).expect(label); + // Upright lines at the rail's leading edge: the selected row's bar. + let bars: Vec<_> = fixture + .frame_shapes() + .into_iter() + .filter_map(|shape| match shape { + Shape::LineSegment { points, .. } if (points[0].x - points[1].x).abs() < 0.5 && (points[0].x - new.left()).abs() <= 2.0 => Some(points), + _ => None, + }) + .collect(); + let on = |label| { + let row = rect(label); + bars.iter().any(|p| row.y_range().contains(p[0].y) && row.y_range().contains(p[1].y)) + }; + assert!(on("Home"), "the selected Home row has a bar at its leading edge: {bars:?}"); + for label in ["Learn", "Website", "Discord", "GitHub"] { + assert!(!on(label), "{label} is not selected and has no bar: {bars:?}"); + } +} + /// A desktop Recent tile gives its picture and filename room while keeping the whole card clickable. #[trial] fn desktop_home_recent_cards_give_the_picture_and_caption_room() { From 282d45bb2875e01b83ec592d9fe70d08beb5f03f Mon Sep 17 00:00:00 2001 From: aiongg Date: Sat, 21 Nov 2026 11:19:46 +0000 Subject: [PATCH 68/74] Help gives the help line's Text, which its callers show --- crates/ui-patterns/src/patterns/preferences/rows.rs | 2 +- crates/ui-widgets/src/form/field.rs | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/ui-patterns/src/patterns/preferences/rows.rs b/crates/ui-patterns/src/patterns/preferences/rows.rs index bc03be521..2ad99b1ca 100644 --- a/crates/ui-patterns/src/patterns/preferences/rows.rs +++ b/crates/ui-patterns/src/patterns/preferences/rows.rs @@ -183,7 +183,7 @@ pub(super) fn show_row(ui: &mut Ui, host: &mut H, Stack::new().id_salt(key).enabled(row.enabled).show(ui, |ui, _| { host.custom_row(ui, key); if let Some(help) = &row.help { - Help::Text(help.clone()).show(ui); + Help::Text(help.clone()).text().show(ui); } }); } diff --git a/crates/ui-widgets/src/form/field.rs b/crates/ui-widgets/src/form/field.rs index dee769d3d..19d4f456b 100644 --- a/crates/ui-widgets/src/form/field.rs +++ b/crates/ui-widgets/src/form/field.rs @@ -22,12 +22,12 @@ pub enum Help { } impl Help { - /// Shows the help line as a field shows it under its control. - pub fn show(&self, ui: &mut Ui) { + /// The help line as a field shows it under its control. + pub fn text(&self) -> Text { match self { - Help::Text(text) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted).show(ui), - Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone).show(ui), - }; + Help::Text(text) => Text::new(text.clone()).role(TypeRole::Caption).shade(Shade::Muted), + Help::Status(tone, text) => Text::new(text.clone()).role(TypeRole::Caption).tone(*tone), + } } } @@ -127,7 +127,7 @@ impl Container for Field { return; } if let Some(help) = &self.help { - help.show(ui); + help.text().show(ui); } } } From ec5bcc602de459b5e1846db0cacd0716a0f73669 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 12:28:28 +0100 Subject: [PATCH 69/74] Layers and Channels panels read the modifiers, not the pointer frame (#2812) Both panels read pointer::frame(..).mods on every pass: the Layers panel for its rows' held modifiers and its drop test, the Channels panel before it takes its commands. pointer::frame notes the pointer as a tracked input, so a memoized view holding either panel ran on every pointer move in the window. pointer::mods reads the same modifiers and notes only the modifiers. Trials: a pointer move beside each panel replays its host view and Alt held runs it; both fail without the change. Co-Authored-By: Claude Opus 5.5 --- crates/imaging/src/ui/channels/panel.rs | 2 +- crates/imaging/tests/it/channels_memo.rs | 52 ++++++++++++++++++++++++ crates/imaging/tests/it/main.rs | 1 + crates/layers/src/ui/panel/body.rs | 4 +- crates/layers/src/ui/panel/mod.rs | 2 +- crates/layers/tests/it/panel_memo.rs | 32 +++++++++++++++ 6 files changed, 88 insertions(+), 5 deletions(-) create mode 100644 crates/imaging/tests/it/channels_memo.rs diff --git a/crates/imaging/src/ui/channels/panel.rs b/crates/imaging/src/ui/channels/panel.rs index fe9539467..f81be39e7 100644 --- a/crates/imaging/src/ui/channels/panel.rs +++ b/crates/imaging/src/ui/channels/panel.rs @@ -154,7 +154,7 @@ impl<'a, K: Clone + Eq + Hash + Debug + Send + Sync + 'static> ChannelsPanel<'a, events.borrow_mut().extend(out); }) .show(ui, |ui, stack| { - let mods = craft_ui::runtime::pointer::frame(&ctx).mods; + let mods = craft_ui::runtime::pointer::mods(&ctx); while let Some((command, _)) = stack.take_command::() { match (command, targeted_row(rows)) { (ChannelsCommands::RenameChannel, Some(row)) if row.kind.renames() => request_rename(&ctx, list, &row.key), diff --git a/crates/imaging/tests/it/channels_memo.rs b/crates/imaging/tests/it/channels_memo.rs new file mode 100644 index 000000000..bc42aced8 --- /dev/null +++ b/crates/imaging/tests/it/channels_memo.rs @@ -0,0 +1,52 @@ +//! The Channels panel in a host's memoized view: a pointer move beside it replays it (#2812). + +use craft_ui::contract::{MemoProps, MemoView}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, pointer, trial}; +use egui::{Modifiers, Pos2, Rect, UiBuilder, Vec2}; + +use crate::ui::channels::{ChannelKind, ChannelRow, ChannelsPanel}; + +const PANEL: Vec2 = Vec2::new(320.0, 400.0); + +/// What a host's view of the panel reads: its rows, which the host's revision stands for. +#[derive(MemoProps)] +struct Host<'a> { + revision: u64, + #[memo_props(covered_by = "revision", reason = "the rows are fixed in this trial")] + rows: &'a [ChannelRow], +} + +fn host(props: &mut Host<'_>, ui: &mut egui::Ui) { + let _ = ChannelsPanel::new(props.rows).show(ui); +} + +/// The panel reads the modifiers its commands take, not the pointer: a pointer move beside it replays its view, and a +/// modifier change runs it. Before, every pointer move in the window ran it. +#[trial] +fn a_pointer_move_beside_the_panel_replays_it_and_a_modifier_runs_it() { + let rows = + [(0, ChannelKind::Composite, "RGB"), (1, ChannelKind::Color, "Red"), (2, ChannelKind::Color, "Green"), (3, ChannelKind::Color, "Blue")] + .map(|(key, kind, name)| ChannelRow::new(key, kind, name)); + let mut fixture = Fixture::new(move |ui| { + let at = Rect::from_min_size(ui.max_rect().min, PANEL); + ui.scope_builder(UiBuilder::new().max_rect(at), |ui| { + MemoView::new("channels", Host { revision: 0, rows: &rows }, host).show(ui); + }); + }); + fixture.room(Vec2::new(PANEL.x + 400.0, PANEL.y)).settle().idle(2); + let runs = |fixture: &Fixture| { + let runs = last_frame_memo_runs(fixture.ctx()); + let count = |wanted: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("Host") && *run == wanted).count(); + (count(MemoRun::Ran), count(MemoRun::Replayed)) + }; + // The pointer enters the window beside the panel; in an app it is already there. + fixture.frame(vec![pointer::moved(Pos2::new(PANEL.x + 200.0, 90.0))]); + for step in 0..3 { + fixture.frame(vec![pointer::moved(Pos2::new(PANEL.x + 200.0, 100.0 + step as f32 * 10.0))]); + assert_eq!(runs(&fixture), (0, 1), "pointer move {step} beside the panel replays its view"); + } + fixture.hold(Modifiers::ALT).frame(Vec::new()); + assert_eq!(runs(&fixture).0, 1, "Alt held runs the view"); + fixture.frame(Vec::new()); + assert_eq!(runs(&fixture), (0, 1), "and it replays while Alt stays held"); +} diff --git a/crates/imaging/tests/it/main.rs b/crates/imaging/tests/it/main.rs index 2a7b0442b..250998236 100644 --- a/crates/imaging/tests/it/main.rs +++ b/crates/imaging/tests/it/main.rs @@ -4,6 +4,7 @@ pub(crate) mod adjust_editors; pub(crate) mod adjust_tone; pub(crate) mod blur_pins; pub(crate) mod channels_delete; +pub(crate) mod channels_memo; pub(crate) mod color_range; pub(crate) mod contour_field; pub(crate) mod curve; diff --git a/crates/layers/src/ui/panel/body.rs b/crates/layers/src/ui/panel/body.rs index 155359e35..94c6371a4 100644 --- a/crates/layers/src/ui/panel/body.rs +++ b/crates/layers/src/ui/panel/body.rs @@ -76,9 +76,7 @@ pub(super) fn show_body( .columns(columns) .selection(Bind::bound(&mut selection)) .can_rename(|key| matches!(key, LayerRowKey::Layer(id) if tree.info(id).renamable)) - .accepts(|drag: &ListDrag>, _over, insert| { - accepts_drop(tree, drag, order, insert, craft_ui::runtime::pointer::frame(&ctx).mods) - }) + .accepts(|drag: &ListDrag>, _over, insert| accepts_drop(tree, drag, order, insert, craft_ui::runtime::pointer::mods(&ctx))) .drag_payload({ let document = cx.document; move |drag: &ListDrag>| Some(LayersDrag::of_rows(drag, document)) diff --git a/crates/layers/src/ui/panel/mod.rs b/crates/layers/src/ui/panel/mod.rs index 65073fec8..21f08aff0 100644 --- a/crates/layers/src/ui/panel/mod.rs +++ b/crates/layers/src/ui/panel/mod.rs @@ -378,7 +378,7 @@ impl<'a, T: LayerTree> LayersPanel<'a, T> { lock_column, visibility_key, trailing: trailing.as_deref(), - held: craft_ui::runtime::pointer::frame(ui.ctx()).mods, + held: craft_ui::runtime::pointer::mods(ui.ctx()), }; let events = RefCell::new(Vec::new()); let current = RefCell::new(LayerFilter::default()); diff --git a/crates/layers/tests/it/panel_memo.rs b/crates/layers/tests/it/panel_memo.rs index 5f72626bf..753c3f8e4 100644 --- a/crates/layers/tests/it/panel_memo.rs +++ b/crates/layers/tests/it/panel_memo.rs @@ -132,3 +132,35 @@ fn a_clicks_event_is_delivered_once_across_the_run_and_the_replays() { let selects = rig.seen.borrow().iter().filter(|event| matches!(event, LayersEvent::Select(_))).count(); assert_eq!(selects, 1, "{:?}", rig.seen.borrow()); } + +/// A pointer move beside the panel replays its view: the panel reads the modifiers it shows its rows with, not the +/// pointer, so only a modifier change runs it (#2812). Before, every pointer move in the window ran it. +#[trial] +fn a_pointer_move_beside_the_panel_replays_it_and_a_modifier_runs_it() { + let tree = Tracked::new(FakeLayers::fifty()); + let mut fixture = Fixture::new(move |ui| { + let mut filter = LayerFilter::default(); + let mut events = Vec::new(); + let at = egui::Rect::from_min_size(ui.max_rect().min, PANEL); + ui.scope_builder(egui::UiBuilder::new().max_rect(at), |ui| { + MemoView::new("layers", Host { tree: &tree, filter: Bind::bound(&mut filter), events: Outbox::new(&mut events) }, host).show(ui); + }); + }); + fixture.room(Vec2::new(PANEL.x + 400.0, PANEL.y)); + fixture.settle().idle(2); + let runs = |fixture: &Fixture| { + let runs = last_frame_memo_runs(fixture.ctx()); + let count = |wanted: MemoRun| runs.iter().filter(|(name, _, run)| name.contains("Host") && *run == wanted).count(); + (count(MemoRun::Ran), count(MemoRun::Replayed)) + }; + // The pointer enters the window beside the panel; in an app it is already there. + fixture.frame(vec![pointer::moved(egui::Pos2::new(PANEL.x + 200.0, 90.0))]); + for step in 0..3 { + fixture.frame(vec![pointer::moved(egui::Pos2::new(PANEL.x + 200.0, 100.0 + step as f32 * 10.0))]); + assert_eq!(runs(&fixture), (0, 1), "pointer move {step} beside the panel replays its view"); + } + fixture.hold(egui::Modifiers::ALT).frame(Vec::new()); + assert_eq!(runs(&fixture).0, 1, "Alt held runs the view"); + fixture.frame(Vec::new()); + assert_eq!(runs(&fixture), (0, 1), "and it replays while Alt stays held"); +} From 3b572a3954f84eb02463d6f48b145b1e4a77f030 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 15:01:27 +0100 Subject: [PATCH 70/74] Every panel and widget reads the modifiers, not the pointer frame (#2812) The same read as in the Layers and Channels panels: pointer::frame(..).mods notes the pointer as a tracked input, so a memoized view holding the component ran on every pointer move in the window. pointer::mods returns the same modifiers and notes only the modifiers. Fifteen more sites read the frame for its modifiers only (the preset browser, the tile grid, the section footer, the dock's drop, the canvas guides, the crop tool, the bins, Color Range, the raw develop dialog, the table conditions, the form dialogs, Save for Web) and the text style panel; each reads pointer::mods now. The preset browser also reads the pointer's buttons, press and release for its rows' events; it reads the frame only when there are events, so a pass without one does not depend on the pointer. In PhotoCraft this left Swatches, Gradients, Patterns, Styles, Shapes, Tool Presets, Character and Paragraph Styles, Brushes and Glyphs running on every pointer move over the canvas; with the change every docked panel replays. Trial: the preset browser in a host view replays on a pointer move beside it, in its list view (fails without the browser change) and its tile view (fails without the tile grid change), and Alt held runs it. Co-Authored-By: Claude Opus 5.5 --- crates/browse/src/ui/bin/free_view.rs | 2 +- crates/browse/src/ui/bin/icon.rs | 2 +- crates/browse/src/ui/bin/list.rs | 2 +- crates/draw/src/ui/crop/tool.rs | 2 +- crates/imaging/src/ui/color_range/dialog.rs | 4 +- crates/imaging/src/ui/raw_develop/mod.rs | 2 +- crates/table/src/ui/conditions.rs | 2 +- crates/text/src/ui/style_panel.rs | 6 +-- .../src/canvas_controls/guides/mod.rs | 2 +- crates/ui-panels/src/docking/drop.rs | 2 +- crates/ui-panels/src/sections/footer.rs | 2 +- .../src/patterns/form_dialogs/dialog.rs | 2 +- .../form_dialogs/save_for_web/panes.rs | 2 +- .../src/patterns/presets/browser.rs | 15 +++--- .../ui-patterns/tests/it/presets/browser.rs | 50 +++++++++++++++++++ crates/ui-widgets/src/tile_grid/grid.rs | 2 +- 16 files changed, 76 insertions(+), 23 deletions(-) diff --git a/crates/browse/src/ui/bin/free_view.rs b/crates/browse/src/ui/bin/free_view.rs index 3b42beebd..9eddab3f5 100644 --- a/crates/browse/src/ui/bin/free_view.rs +++ b/crates/browse/src/ui/bin/free_view.rs @@ -32,7 +32,7 @@ where let (entries, _) = entries_of(model, state, collator); let searching = !state.search.trim().is_empty(); let shown = Cards::new(model, entries); - let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft_ui::runtime::pointer::mods(ui.ctx()); if let Some(key) = rename { request_rename(ui.ctx(), id, &key); } diff --git a/crates/browse/src/ui/bin/icon.rs b/crates/browse/src/ui/bin/icon.rs index 941e44333..9fde6bb1d 100644 --- a/crates/browse/src/ui/bin/icon.rs +++ b/crates/browse/src/ui/bin/icon.rs @@ -152,7 +152,7 @@ where let (entries, user_order) = entries_of(model, state, collator); let searching = !state.search.trim().is_empty(); let cards = Cards::new(model, entries); - let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft_ui::runtime::pointer::mods(ui.ctx()); if let Some(key) = rename { request_rename(ui.ctx(), id, &key); } diff --git a/crates/browse/src/ui/bin/list.rs b/crates/browse/src/ui/bin/list.rs index 2893f2225..78c587f30 100644 --- a/crates/browse/src/ui/bin/list.rs +++ b/crates/browse/src/ui/bin/list.rs @@ -103,7 +103,7 @@ where let thumb = state.settings.thumbnails; let specs = columns_of(columns, &state.settings.widths, words.name.clone()); let value_columns: Vec = specs.iter().map(|spec| spec.key.clone()).filter(|key| *key != NAME).collect(); - let mods = craft_ui::runtime::pointer::frame(ui.ctx()).mods; + let mods = craft_ui::runtime::pointer::mods(ui.ctx()); let tile_words = Env::of(ui).words::(); if let Some(key) = rename { request_rename(ui.ctx(), id, &key); diff --git a/crates/draw/src/ui/crop/tool.rs b/crates/draw/src/ui/crop/tool.rs index 4b6308fd0..11eca1c61 100644 --- a/crates/draw/src/ui/crop/tool.rs +++ b/crates/draw/src/ui/crop/tool.rs @@ -260,7 +260,7 @@ impl CropTool { // Straighten surface is there for a press on the pass after the key came down; a line in progress keeps the // state it started with, so letting go of the key mid-line does not turn it into a frame drag. if !self.dragging { - self.session.straighten_mut().set_held(pointer::frame(ui.ctx()).mods.cmd); + self.session.straighten_mut().set_held(pointer::mods(ui.ctx()).cmd); } let (ratio, default, straighten, dismissed) = (settings.ratio_value(document, &units), self.session.is_default(), self.session.straighten().on(), self.session.dismissed()); diff --git a/crates/imaging/src/ui/color_range/dialog.rs b/crates/imaging/src/ui/color_range/dialog.rs index 5a6ff114b..308292570 100644 --- a/crates/imaging/src/ui/color_range/dialog.rs +++ b/crates/imaging/src/ui/color_range/dialog.rs @@ -223,7 +223,7 @@ impl<'a> ColorRangeDialog<'a> { let preview_words = env.words::(); // Holding ⌘ (Ctrl off macOS; `Mods` folds Ctrl into `cmd` there) shows the other view while held: view only, // `show_image` does not change. - let swapped = pointer::frame(ui.ctx()).mods.cmd; + let swapped = pointer::mods(ui.ctx()).cmd; let image_shown = show_image != swapped; let source = if image_shown { image } else { mask }; let state = match (&error, source) { @@ -288,7 +288,7 @@ impl<'a> ColorRangeDialog<'a> { f64::from(p.x.floor().max(0.0)) * f64::from(k) + f64::from(k / 2), f64::from(p.y.floor().max(0.0)) * f64::from(k) + f64::from(k / 2), ]; - let mods = pointer::frame(ui.ctx()).mods; + let mods = pointer::mods(ui.ctx()); let mut next = pass.current.clone(); next.samples.pick(at, document, tool, mods); pass.set(&words.eyedropper, next); diff --git a/crates/imaging/src/ui/raw_develop/mod.rs b/crates/imaging/src/ui/raw_develop/mod.rs index 98f0249be..1a695e6ef 100644 --- a/crates/imaging/src/ui/raw_develop/mod.rs +++ b/crates/imaging/src/ui/raw_develop/mod.rs @@ -524,7 +524,7 @@ impl FullWindowWorkspace for RawDevelopWorkspace { let words = env.words::(); let common = env.words::(); let ctx = ui.ctx().clone(); - let alt = craft_ui::runtime::pointer::frame(&ctx).mods.alt; + let alt = craft_ui::runtime::pointer::mods(&ctx).alt; self.open_scope(&ctx, source); let name = if self.target == RawTarget::OpenRaw { words.name.clone() } else { words.name_filter.clone() }; diff --git a/crates/table/src/ui/conditions.rs b/crates/table/src/ui/conditions.rs index 3c75105a8..d415433d5 100644 --- a/crates/table/src/ui/conditions.rs +++ b/crates/table/src/ui/conditions.rs @@ -445,7 +445,7 @@ impl Rows<'_> { .id_salt((path.to_vec(), "add")) .show(ui); if clicked(&plus) { - let group = pointer::frame(ui.ctx()).mods.alt && depth < MAX_DEPTH; + let group = pointer::mods(ui.ctx()).alt && depth < MAX_DEPTH; let item = if group { ConditionItem::Group(self.new_group()) } else { ConditionItem::Rule(self.new_rule()) }; *insert = Some((at + 1, item)); } diff --git a/crates/text/src/ui/style_panel.rs b/crates/text/src/ui/style_panel.rs index d1372b934..8210e0bb3 100644 --- a/crates/text/src/ui/style_panel.rs +++ b/crates/text/src/ui/style_panel.rs @@ -407,9 +407,9 @@ impl<'a> TextStylesPanel<'a> { }); let (events, second) = (shown_rows.events, shown_rows.activation_clicks >= 2); - let pointer = craft_ui::runtime::pointer::frame(ui.ctx()); - let alt = pointer.mods.alt; - let plain = !pointer.mods.shift && !pointer.mods.cmd; + let mods = craft_ui::runtime::pointer::mods(ui.ctx()); + let alt = mods.alt; + let plain = !mods.shift && !mods.cmd; for event in events { match event { CollectionEvent::Activate(id) if second && (id != 0 || paragraph) => action.set(Some(TextStyleAction::Options(id))), diff --git a/crates/ui-canvas/src/canvas_controls/guides/mod.rs b/crates/ui-canvas/src/canvas_controls/guides/mod.rs index 47899d7a9..0fd6e4fb6 100644 --- a/crates/ui-canvas/src/canvas_controls/guides/mod.rs +++ b/crates/ui-canvas/src/canvas_controls/guides/mod.rs @@ -479,7 +479,7 @@ impl Component for Guides<'_> { /// `run_pointer` reads only declared parts, so this is the one gate of the pointer. fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) { let held = cx.press_slot::().is_some() || cx.gesture_running(); - let takes = self.interactive || (self.moves_with_command && (crate::runtime::pointer::frame(cx.ui.ctx()).mods.cmd || held)); + let takes = self.interactive || (self.moves_with_command && (crate::runtime::pointer::mods(cx.ui.ctx()).cmd || held)); let (Some(space), Some(guides), true) = (canvas_space(&cx.env), cx.value(), takes) else { return }; let mut any = false; for &at in &place::keyboard_order(guides) { diff --git a/crates/ui-panels/src/docking/drop.rs b/crates/ui-panels/src/docking/drop.rs index b08d63c16..887a46116 100644 --- a/crates/ui-panels/src/docking/drop.rs +++ b/crates/ui-panels/src/docking/drop.rs @@ -326,7 +326,7 @@ impl DockDropTarget<'_, P> { } let unit = drag.unit(self.layout)?; let window = matches!(unit, DragUnit::Window(_)); - if pointer::frame(self.ctx).mods.cmd { + if pointer::mods(self.ctx).cmd { return if window { None } else { self.float(&unit, at, drag.source(), drag.strip()) }; } if window && !self.title_bar_docks { diff --git a/crates/ui-panels/src/sections/footer.rs b/crates/ui-panels/src/sections/footer.rs index d983d9722..07c093c1f 100644 --- a/crates/ui-panels/src/sections/footer.rs +++ b/crates/ui-panels/src/sections/footer.rs @@ -681,7 +681,7 @@ impl FooterBar { } }); let inner = shown.inner.unwrap_or_default(); - let mods = if inner.picked.is_some() { crate::runtime::pointer::frame(ui.ctx()).mods } else { craft_keymap::Mods::NONE }; + let mods = if inner.picked.is_some() { crate::runtime::pointer::mods(ui.ctx()) } else { craft_keymap::Mods::NONE }; let output = FooterOutput { response: shown.output, picked: inner.picked, diff --git a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs index 92f838b93..29e9df9b0 100644 --- a/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs +++ b/crates/ui-patterns/src/patterns/form_dialogs/dialog.rs @@ -636,7 +636,7 @@ impl ResetFooter { pub fn new(ui: &Ui, cancel: Option