From c49a12a99d4376cf4319e94de11f55d66bffb641 Mon Sep 17 00:00:00 2001 From: David Mann Date: Sat, 21 Nov 2026 01:24:29 +0100 Subject: [PATCH 01/34] Crop: an edge or corner drag may take a document crop past its bounds The Crop tool bounds the overlay by the canvas while Delete Cropped Pixels is on so that an image-mode turn keeps the frame inside the image (photocraft#10869). The drag rules also cut every edge and corner resize to those bounds, so a crop could not grow the canvas. In the reference application it does. A resize of a document crop now goes past the bounds; turns, moves, drawn frames, nudges and a placed picture's crop (bounded by its source) are unchanged. Fixes storytold/photocraft#16043. Co-Authored-By: Claude Opus 5.5 --- crates/ui-canvas/src/canvas/crop/gesture.rs | 7 +++++- crates/ui-canvas/src/canvas/crop/mod.rs | 4 ++- crates/ui-canvas/tests/it/canvas/crop.rs | 27 +++++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/crates/ui-canvas/src/canvas/crop/gesture.rs b/crates/ui-canvas/src/canvas/crop/gesture.rs index b0c322a19..40ca29c96 100644 --- a/crates/ui-canvas/src/canvas/crop/gesture.rs +++ b/crates/ui-canvas/src/canvas/crop/gesture.rs @@ -70,6 +70,9 @@ pub(super) struct Rules { pub image: bool, pub auto_center: bool, pub fills_uncovered: bool, + /// An edge or corner drag may take the frame past `bounds`: the crop grows the canvas there, as in the reference + /// application (a document crop, not one bounded by a placed picture's source). + pub resize_grows: bool, /// The canvas's snapping, with this pass's tolerance. pub snap: Option, pub os: Platform, @@ -89,6 +92,7 @@ impl Rules { /// as it was (a draw not yet sized) or cannot be kept inside. pub fn proposal(&self, drag: &mut Drag, to: Point, mods: Mods, space: bool) -> Option { let at = drag.at_press; + let mut grows = false; let (next, resizing, held) = match &mut drag.kind { Kind::Draw { anchor, cur, last } => { if space { @@ -115,6 +119,7 @@ impl Rules { } else { at.resized(*part, by, hold, mods.alt) }; + grows = self.resize_grows; (next, true, self.ratio.is_some() || mods.shift) } Kind::Turn { grab } => { @@ -137,7 +142,7 @@ impl Rules { if !next.is_finite() { return None; } - match self.bounds { + match self.bounds.filter(|_| !grows) { Some(bounds) => next.within(bounds, resizing, held).or(Some(drag.last)), None => Some(next), } diff --git a/crates/ui-canvas/src/canvas/crop/mod.rs b/crates/ui-canvas/src/canvas/crop/mod.rs index 906c5d810..d3e193be5 100644 --- a/crates/ui-canvas/src/canvas/crop/mod.rs +++ b/crates/ui-canvas/src/canvas/crop/mod.rs @@ -154,7 +154,8 @@ pub struct CropOverlay<'a> { #[prop(flag)] straighten: bool, /// The area the frame may not leave, in document units. An image-mode turn moves or shrinks the frame to keep it - /// inside (Command keeps it as it was at the press). + /// inside (Command keeps it as it was at the press). An edge or corner drag of a document crop may still take it + /// past them: the crop grows the canvas. #[prop] bounds: Option, /// Image mode: the frame stays upright on screen and a move or turn moves or turns the view instead. @@ -232,6 +233,7 @@ impl<'a> CropOverlay<'a> { image: self.image_mode, auto_center: self.auto_center, fills_uncovered: self.fills_uncovered, + resize_grows: matches!(self.scope, CropScope::Document), snap: canvas_snap(env), os: env.shell().os, } diff --git a/crates/ui-canvas/tests/it/canvas/crop.rs b/crates/ui-canvas/tests/it/canvas/crop.rs index 7f85b1012..01f4a6c7b 100644 --- a/crates/ui-canvas/tests/it/canvas/crop.rs +++ b/crates/ui-canvas/tests/it/canvas/crop.rs @@ -803,6 +803,33 @@ fn a_shift_corner_follows_the_diagonal_and_snaps_along_it() { assert!(rig.seen.borrow().snapped.is_empty(), "no snap line reported"); } +#[trial] +fn a_document_crop_grows_past_its_bounds_on_an_edge_or_corner_drag_only() { + // The canvas as the bounds, as the Crop tool sets them with Delete Cropped Pixels on. + let canvas = Rect::new(50.0, 50.0, 350.0, 250.0); + for (what, base) in [("classic", Setup::new()), ("image mode", Setup::image(0.0, false))] { + let mut setup = base; + setup.bounds = Some(canvas); + // An edge dragged past the canvas takes the frame with it: the crop grows the canvas there. + let mut rig = Rig::new(CropBox::upright(RECT), setup.clone()); + rig.drag(rig.at(RECT.x1, 150.0), rig.at(380.0, 150.0), Modifiers::NONE); + let r = rig.rect(); + assert!((r.x1 - 380.0).abs() < 1e-6 && r.x0 == RECT.x0, "{what}: the right edge follows past the canvas: {r:?}"); + // So does a corner. + let mut rig = Rig::new(CropBox::upright(RECT), setup.clone()); + rig.drag(rig.at(RECT.x1, RECT.y1), rig.at(380.0, 280.0), Modifiers::NONE); + let r = rig.rect(); + assert!(r.x1 > canvas.x1 + 1.0 && r.y1 > canvas.y1 + 1.0, "{what}: the corner follows past the canvas: {r:?}"); + } + // A classic move still stops at the canvas. + let mut setup = Setup::new(); + setup.bounds = Some(canvas); + let mut rig = Rig::new(CropBox::upright(RECT), setup); + rig.drag(rig.at(200.0, 150.0), rig.at(300.0, 150.0), Modifiers::NONE); + let r = rig.rect(); + assert!(r.x1 <= canvas.x1 + 1e-6 && (r.width() - RECT.width()).abs() < 1e-6, "a move stays inside: {r:?}"); +} + #[trial] fn an_object_crop_is_bounded_by_its_source_and_a_press_outside_it_reaches_what_lies_beneath() { let source = Rect::new(50.0, 50.0, 350.0, 250.0); From 3502761b8985ee0e964c84d7031973763bd473b6 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 04:12:25 +0000 Subject: [PATCH 02/34] 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 03/34] 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 04/34] 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 05/34] 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 06/34] 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 07/34] 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 08/34] 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 09/34] 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