From 1b62c5687d563429a79fe80e968603f0a8495c8d Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 21:29:31 +0000 Subject: [PATCH] Preset sources: the remaining framework callers, the popover replay trial and the preset count trials ParamRows and ParamDialog take a PresetSource for their pattern rows (a hosted dialog's build gives one over owned inputs); the export and PDF export dialogs, the swatch list (swatch_source, thumbs from the drawn colours), the gradient palette and Gradient Map picker, the pattern fill editor, the text style picker (style_source) and the Layer Style dialog (patterns, style presets, contour_source) build their presets from sources. Their painters are fns: RampSampler, SwatchPainter, ContourSampler. Key types and the model types they are built from are memo props. A memoized view inside an open popover replays while nothing changes; an open preset picker runs no list row while nothing changes; a Size drag in the Brush Preset picker runs its head and replays the list. The Swatches panel's rows stay public as `swatch_rows(groups, words)`, which the source's rows fn calls. --- crates/color-ui/src/gradient/value.rs | 4 + crates/color-ui/src/palette.rs | 4 + crates/color-ui/src/ui/mod.rs | 2 +- crates/color-ui/src/ui/paint_chip.rs | 18 +-- crates/color-ui/src/ui/swatches.rs | 2 +- crates/color-ui/src/ui/swatches/library.rs | 42 ++++++- crates/color-ui/src/ui/swatches/panel.rs | 26 ++-- crates/draw/src/ui/gradient/map/mod.rs | 33 ++--- crates/draw/src/ui/gradient/mod.rs | 2 +- crates/draw/src/ui/gradient/palette/mod.rs | 119 +++++++++++------- crates/draw/src/ui/mod.rs | 2 +- crates/draw/src/ui/pattern/dialog.rs | 11 +- crates/draw/src/ui/pattern/editor.rs | 66 +++++----- crates/draw/src/ui/pattern/mod.rs | 2 +- crates/draw/tests/it/brush_presets.rs | 35 +++++- crates/imaging/src/layer_style/contour.rs | 2 + .../src/ui/layer_style/contour/editor.rs | 14 +-- .../imaging/src/ui/layer_style/contour/mod.rs | 62 +++++---- .../src/ui/layer_style/contour/stories.rs | 7 +- crates/imaging/src/ui/layer_style/dialog.rs | 54 ++++---- crates/imaging/src/ui/layer_style/hosted.rs | 47 ++++--- crates/imaging/src/ui/layer_style/mod.rs | 5 +- crates/imaging/src/ui/layer_style/page.rs | 15 ++- crates/imaging/src/ui/layer_style/stories.rs | 20 ++- crates/imaging/src/ui/layer_style/styles.rs | 34 ++--- crates/imaging/src/ui/mod.rs | 2 +- crates/imaging/tests/it/contour_field.rs | 7 +- crates/imaging/tests/it/layer_style.rs | 27 ++-- crates/text/src/ui/style_panel.rs | 2 +- crates/text/src/ui/style_panel/picker.rs | 19 +-- crates/text/src/ui/style_panel/stories.rs | 5 +- crates/ui-contract/src/contract/memo.rs | 21 ++-- crates/ui-contract/src/runtime/env/units.rs | 11 -- .../src/patterns/form_dialogs/dialog.rs | 24 ++-- .../patterns/form_dialogs/export/as_dialog.rs | 10 +- .../src/patterns/form_dialogs/pdf_export.rs | 16 ++- .../src/patterns/form_dialogs/rows.rs | 32 +++-- .../src/patterns/form_dialogs/rows/stories.rs | 10 +- .../src/patterns/presets/browser.rs | 9 +- .../src/patterns/presets/model/library.rs | 6 +- .../src/patterns/presets/picker.rs | 3 +- .../src/patterns/presets/source.rs | 2 +- .../tests/it/form_dialogs/dialog.rs | 8 +- .../tests/it/form_dialogs/params.rs | 17 ++- crates/ui-patterns/tests/it/presets/picker.rs | 36 +++++- crates/ui-widgets/src/choice/swatch.rs | 2 +- crates/ui-widgets/tests/it/body/memo_view.rs | 36 ++++++ 47 files changed, 540 insertions(+), 393 deletions(-) diff --git a/crates/color-ui/src/gradient/value.rs b/crates/color-ui/src/gradient/value.rs index a0d70a8fc..76819b4c2 100644 --- a/crates/color-ui/src/gradient/value.rs +++ b/crates/color-ui/src/gradient/value.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize}; /// How a gradient's opacity is stored, which decides the rows of its stop bar. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[non_exhaustive] pub enum StopRows { /// Opacity stops in their own row above the ramp, colour stops below; a colour's alpha is @@ -36,6 +37,7 @@ pub enum StopRow { /// A colour stop. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct ColorStop { @@ -56,6 +58,7 @@ pub struct ColorStop { /// An opacity stop of a [`StopRows::Split`] gradient. #[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct OpacityStop { @@ -120,6 +123,7 @@ impl OpacityStop { /// A gradient's stops, each list sorted by location. #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub struct GradientStops { diff --git a/crates/color-ui/src/palette.rs b/crates/color-ui/src/palette.rs index b8d97267e..fb7b69230 100644 --- a/crates/color-ui/src/palette.rs +++ b/crates/color-ui/src/palette.rs @@ -97,6 +97,7 @@ impl SwatchFormat { /// A swatch colour in its own model. #[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(tag = "model", content = "values", rename_all = "camelCase")] pub enum SwatchColor { /// Encoded RGB, 0–1 each, in the RGB working space. @@ -148,6 +149,7 @@ impl SwatchColor { /// How an `.ase` file marks a colour. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] pub enum SwatchKind { #[default] @@ -161,6 +163,7 @@ pub enum SwatchKind { /// One named swatch. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct SwatchEntry { /// The swatch's label. pub name: String, @@ -181,6 +184,7 @@ impl SwatchEntry { /// A named group of swatches, as the Swatches panel shows them. A file without groups reads as /// one group named after the file. #[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct SwatchGroup { /// The group's label. pub name: String, diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index 4f08f463d..7d3c18cc6 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -87,7 +87,7 @@ pub use screen_picker::{CaptureResult, CaptureSource, LOUPE_PIXELS, LOUPE_ZOOM, pub use strip::{ColorStrip, ColorStripStyle}; pub use swatches::{ MAX_GROUPS, MAX_SWATCHES, SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput, - SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows, + SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows, swatch_source, }; pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle}; pub use wheel::{ diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index 8db24aab3..2893b5a41 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -14,14 +14,14 @@ use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey}; use craft_cms::convert::CmykConverter; use craft_theme::Srgba; use craft_ui::buttons::Button; -use craft_ui::choice::{ChoiceWords, Segmented, Swatch, SwatchFace}; +use craft_ui::choice::{ChoiceWords, Segmented, Swatch}; use craft_ui::contract::{ Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, }; use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::Row; -use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState, ThumbInfo}; +use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState}; use craft_ui::primitives::textures::CachedTexture; use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth}; use craft_ui::runtime::env::{Env, Label}; @@ -30,7 +30,7 @@ use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx} use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2}; use super::popover::compact_picker; -use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, SwatchesWords, swatch_rows}; +use super::{PickedColor, ScreenPickGesture, SwatchKey, SwatchPalette, swatch_source}; use crate::palette::{SwatchColor, SwatchGroup}; pub(crate) mod paint_list; @@ -475,7 +475,6 @@ impl Component for PaintChip<'_> { let solid = cx.memory::().0.unwrap_or(self.fallback); let current = FillKind::of(&paint); let sampled = self.sampled; - let swatch_words = cx.words::(); let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); let full_picker = self.full_picker; let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated()); @@ -514,21 +513,14 @@ impl Component for PaintChip<'_> { } if let Some((groups, state)) = swatches.as_mut() { let groups: &[SwatchGroup] = groups; - let rows = swatch_rows(groups, &swatch_words); + let source = swatch_source(groups, cmyk); let colors: HashMap<&str, &SwatchColor> = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); - let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &rows) + let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &source) .toolbar(false) .row_menu(false) .default_open(DefaultOpen::None) .room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS) - .thumb(|painter: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { - if let SwatchKey::Swatch(name) = info.key - && let Some(color) = colors.get(name.as_str()) - { - SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(painter, rect); - } - }) .show(ui); for event in out.events { if let PresetEvent::Select { key: SwatchKey::Swatch(name), .. } = event diff --git a/crates/color-ui/src/ui/swatches.rs b/crates/color-ui/src/ui/swatches.rs index 17bed44a5..d66a11bab 100644 --- a/crates/color-ui/src/ui/swatches.rs +++ b/crates/color-ui/src/ui/swatches.rs @@ -11,7 +11,7 @@ pub(crate) mod panel; #[cfg(feature = "suite")] pub(crate) mod stories; -pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows}; +pub use library::{SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesState, swatch_rows, swatch_source}; pub use menu::{SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput}; pub use panel::{SwatchesPanel, SwatchesPanelOutput}; diff --git a/crates/color-ui/src/ui/swatches/library.rs b/crates/color-ui/src/ui/swatches/library.rs index b5ca7d726..2ab31c803 100644 --- a/crates/color-ui/src/ui/swatches/library.rs +++ b/crates/color-ui/src/ui/swatches/library.rs @@ -2,8 +2,15 @@ use std::collections::HashSet; +use craft_cms::convert::CmykConverter; +use craft_theme::Srgba; +use craft_ui::choice::SwatchFace; use craft_ui::contract::ReorderMove; -use craft_ui::patterns::presets::{PresetRow, PresetState}; +use craft_ui::patterns::presets::{PresetFns, PresetRow, PresetSource, PresetState, ThumbInfo}; +use craft_ui::primitives::ContentPainterCx; +use craft_ui::runtime::env::Env; +use egui::Rect; +use std::collections::BTreeMap; use super::{MAX_GROUPS, MAX_SWATCHES, SWATCH_ZOOM, SwatchesWords}; use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchReport}; @@ -11,7 +18,7 @@ use crate::ui::PickedColor; /// What the browser names its rows by. Swatch names are unique across the library and group names among groups, so /// both survive reordering. -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum SwatchKey { /// A group, by name. @@ -556,8 +563,27 @@ impl SwatchLibrary { } } -/// The rows of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as its -/// tooltip and accessible name. `SwatchesPanel` and `PaintChip`'s swatches list build their rows with it. +/// The swatch list's inputs: the library's groups and each swatch's colour as drawn, by name. +#[derive(craft_ui::contract::MemoProps)] +struct SwatchInputs<'a> { + groups: &'a [SwatchGroup], + drawn: BTreeMap<&'a str, Srgba>, +} + +/// The presets of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as +/// its tooltip and accessible name, painted in its colour through `cmyk`. `SwatchesPanel` and `PaintChip`'s swatches +/// list show it. +pub fn swatch_source<'a>(groups: &'a [SwatchGroup], cmyk: &CmykConverter) -> PresetSource<'a, SwatchKey> { + let drawn = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), e.color.to_srgb(cmyk)))).collect(); + PresetSource::new(SwatchInputs { groups, drawn }, PresetFns::new(source_rows).thumb(paint_swatch)) +} + +fn source_rows(inputs: &SwatchInputs<'_>, env: &Env) -> Vec> { + swatch_rows(inputs.groups, &env.words::()) +} + +/// The rows the Swatches panel lists for `groups`: each group's header, then its swatches, each named by its name and +/// colour value. pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec> { let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::()); for group in groups { @@ -570,6 +596,14 @@ pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>) { + if let SwatchKey::Swatch(name) = info.key + && let Some(color) = inputs.drawn.get(name.as_str()) + { + SwatchFace::new(*color).selected(info.selected).paint(cx, rect); + } +} + #[cfg(test)] pub(crate) mod tests { use super::*; diff --git a/crates/color-ui/src/ui/swatches/panel.rs b/crates/color-ui/src/ui/swatches/panel.rs index f0bef8ce9..1347ece3d 100644 --- a/crates/color-ui/src/ui/swatches/panel.rs +++ b/crates/color-ui/src/ui/swatches/panel.rs @@ -1,24 +1,20 @@ //! `SwatchesPanel`: the panel body, its state and what it reports. -use std::collections::HashMap; - use craft_cms::convert::CmykConverter; use craft_i18n::Format; use craft_theme::Srgba; use craft_theme::variant::Tone; use craft_ui::bars::StatusMessage; -use craft_ui::choice::SwatchFace; use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _, request_rename}; use craft_ui::layout_components::Stack; -use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords, ThumbInfo}; -use craft_ui::primitives::ContentPainterCx; +use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords}; use craft_ui::runtime::env::{Count, Env}; -use egui::{Rect, Response, Ui}; +use egui::{Response, Ui}; use super::library::{find_swatch, has}; use super::menu::event_edits; -use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_rows}; -use crate::palette::{SwatchColor, SwatchGroup, SwatchNote, SwatchReport}; +use super::{SWATCH_ZOOM, SwatchAt, SwatchEdit, SwatchKey, SwatchesFileOutput, SwatchesState, SwatchesWords, swatch_source}; +use crate::palette::{SwatchGroup, SwatchNote, SwatchReport}; /// What [`SwatchesPanel::show`] reports. #[derive(Debug)] @@ -99,21 +95,13 @@ impl<'a> SwatchesPanel<'a> { if st.selected.as_ref().is_some_and(|k| !has(groups, k)) { st.selected = None; } - let rows = swatch_rows(groups, &words); + let source = swatch_source(groups, cmyk); let out = { - let colors: HashMap<&str, &SwatchColor> = groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); - let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &rows) + let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source) .thumb_range(SWATCH_ZOOM) .toolbar(true) .reorder(PresetReorder::items_and_groups()) - .footer(PresetFooterOptions::new().can_delete(st.selected.is_some())) - .thumb(|cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { - if let SwatchKey::Swatch(name) = info.key - && let Some(color) = colors.get(name.as_str()) - { - SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(cx, rect); - } - }); + .footer(PresetFooterOptions::new().can_delete(st.selected.is_some())); if let Some(key) = &st.selected { browser = browser.selected(key.clone()); } diff --git a/crates/draw/src/ui/gradient/map/mod.rs b/crates/draw/src/ui/gradient/map/mod.rs index e7c9c0e48..273ba5eb9 100644 --- a/crates/draw/src/ui/gradient/map/mod.rs +++ b/crates/draw/src/ui/gradient/map/mod.rs @@ -14,7 +14,7 @@ use craft_ui::contract::{Bind, Pattern, Props as _, Remember as _, Show as _, Sh use craft_ui::display::{Shade, Text}; use craft_ui::form::Field; use craft_ui::layout_components::Stack; -use craft_ui::patterns::presets::{PickerField, PresetPicker, PresetRow}; +use craft_ui::patterns::presets::{PickerField, PresetFns, PresetPicker, PresetRow, PresetSource}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::style::TypeRole; use egui::{Response, Ui}; @@ -136,26 +136,18 @@ impl<'a> GradientMapEditor<'a> { (words.preset.clone(), words.custom.clone(), words.import_presets.clone(), words.stops.clone()); let (reverse_label, dither_label) = (words.reverse.clone(), words.dither.clone()); let shown = Stack::new().label(self.label.clone()).show(ui, |ui, cx| { - let rows: Vec> = self - .presets - .iter() - .enumerate() - .flat_map(|(group, g)| { - let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0); - let items = - g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1)); - std::iter::once(header).chain(items) - }) - .collect(); + let source = PresetSource::new(self.presets, PresetFns::new(preset_rows)); // Stop tags identify host data, so they do not determine which preset's colours match. let matches = |&key: &GradientRef| { self.preset_colors(key).is_some_and(|colors| colors.map(|s| s.with_tag(0)).eq(base.stops.color.iter().map(|s| s.with_tag(0)))) }; let preferred = cx.keep::().0.filter(matches); - let current = preferred.or_else(|| rows.iter().map(|row| row.key).find(matches)); + let mut items = + self.presets.iter().enumerate().flat_map(|(group, g)| (0..g.items.len()).map(move |item| GradientRef::Item { group, item })); + let current = preferred.or_else(|| items.find(matches)); let picked = Field::new(preset_label.clone()) .show(ui, |ui, _| { - PresetPicker::new(preset_label.clone(), Bind::given(current), &rows, Bind::kept()) + PresetPicker::new(preset_label.clone(), Bind::given(current), &source, Bind::kept()) .field(PickerField::Name) .placeholder(custom.clone()) .show(ui) @@ -200,3 +192,16 @@ impl<'a> GradientMapEditor<'a> { GradientMapOutput { response: shown.output, event, color_requested, import } } } + +/// The picker's rows: each group's header, then its presets. A header's key names no preset (`item == usize::MAX`). +fn preset_rows(presets: &&[GradientGroup], _: &Env) -> Vec> { + presets + .iter() + .enumerate() + .flat_map(|(group, g)| { + let header = PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0); + let items = g.items.iter().enumerate().map(move |(item, p)| PresetRow::item(GradientRef::Item { group, item }, p.name.clone(), 1)); + std::iter::once(header).chain(items) + }) + .collect() +} diff --git a/crates/draw/src/ui/gradient/mod.rs b/crates/draw/src/ui/gradient/mod.rs index b7eb01b2f..311d029f5 100644 --- a/crates/draw/src/ui/gradient/mod.rs +++ b/crates/draw/src/ui/gradient/mod.rs @@ -21,6 +21,6 @@ pub use fill_editor::{GradientFillEditor, GradientFillEditorOutput, GradientFill pub use gradient_line::{GradientLine, LineGradient, LinePart}; pub use gradient_overlay::{GradientLineWords, GradientOverlay, GradientOverlayOutput, GradientOverlayStyle}; pub use map::{GradientMap, GradientMapEditor, GradientMapOutput}; -pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef}; +pub use palette::{GradientGroup, GradientItem, GradientPalette, GradientPaletteOutput, GradientRef, RampSampler}; pub use swatch::{GradientSwatch, GradientSwatchOutput}; pub use tile::{FocusOutline, GradientTile}; diff --git a/crates/draw/src/ui/gradient/palette/mod.rs b/crates/draw/src/ui/gradient/palette/mod.rs index b50b68cec..8e1cbd103 100644 --- a/crates/draw/src/ui/gradient/palette/mod.rs +++ b/crates/draw/src/ui/gradient/palette/mod.rs @@ -2,10 +2,12 @@ //! family's [`PresetBrowser`]: the browser owns the grid, the list, the roving focus, the keys and the accessible tree; //! the palette supplies the rows and paints each preset's thumbnail as a gradient ramp. +use craft_theme::Srgba; use craft_ui::contract::{Bind, NoValue, Outcome, Pattern}; -use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetRow, PresetState, PresetTiles}; +use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetEvent, PresetFns, PresetRow, PresetSource, PresetState, PresetTiles, ThumbInfo}; +use craft_ui::primitives::ContentPainterCx; use craft_ui::runtime::env::{Env, Label}; -use egui::{Response, Ui}; +use egui::{Rect, Response, Ui}; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -18,7 +20,7 @@ use super::GradientTile; const MAX_ROWS: f32 = 6.0; /// A named group of gradient presets. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct GradientGroup { /// The group's heading. @@ -35,7 +37,7 @@ impl GradientGroup { } /// A named gradient preset. -#[derive(Clone, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct GradientItem { /// The preset's name. @@ -62,7 +64,7 @@ impl GradientItem { /// The preset a pick names: a recent gradient by its place in the list the host passed, or an /// item of a group. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum GradientRef { /// Place in the Recent list. @@ -163,9 +165,10 @@ pub struct GradientPalette<'a> { /// The row layout the ramps are sampled with. #[prop] rows: StopRows, - /// Samples a ramp; the default sampler of the rows by default. + /// Samples a ramp; the default sampler of the rows by default. A `fn`, which captures nothing, so the palette's + /// presets key it by its address. #[prop] - sampler: Option<&'a Sampler>, + sampler: Option, /// The selected preset. #[prop] selected: Option, @@ -186,55 +189,17 @@ impl<'a> GradientPalette<'a> { } } - /// The rows of the groups: the header of each group, then its presets. A header's key names no preset - /// (`item == usize::MAX`). - fn preset_rows(&self) -> Vec> { - let mut rows = Vec::new(); - if !self.recent.is_empty() { - rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), self.recent_label.clone(), 0)); - for i in 0..self.recent.len() { - rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", self.recent_label, i + 1), 1)); - } - } - for (group, g) in self.groups.iter().enumerate() { - rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0)); - for (item, preset) in g.items.iter().enumerate() { - rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1)); - } - } - rows - } - /// Shows the palette across the available width. pub fn show(self, ui: &mut Ui) -> GradientPaletteOutput { - let rows = self.preset_rows(); - let default = default_sampler(self.rows); - let sampler: &Sampler = self.sampler.unwrap_or(&default); let (groups, recent) = (self.groups, self.recent); let (wide, high) = GradientRamp::CHIP_ASPECT; // The browser has one cell shape for the grid and the list, so any tile makes every cell square. let square = groups.iter().flat_map(|g| &g.items).any(|item| item.tile != GradientTile::Ramp); - let thumb = - move |cx: &craft_ui::primitives::ContentPainterCx, rect: egui::Rect, info: craft_ui::patterns::presets::ThumbInfo<'_, GradientRef>| { - if let Some(stops) = stops_of(groups, recent, *info.key) { - let (radius, edge) = GradientRamp::chip_look(&cx.style_cx()); - let tile = item_of(groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile); - if tile != GradientTile::Ramp { - tile.paint(cx, rect, radius, stops, sampler, edge); - return; - } - let chip = if square { - egui::Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide))) - } else { - rect - }; - GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge); - } - }; + let inputs = PaletteInputs { groups, recent, recent_label: self.recent_label, rows: self.rows, sampler: self.sampler, square }; + let source = PresetSource::new(inputs, PresetFns::new(preset_rows).thumb(paint_thumb)); let most = Env::of(ui).tokens.size.control.sm * MAX_ROWS; let shape = if square { CellShape::Square } else { CellShape::ratio(wide, high) }; - let mut browser = - PresetBrowser::new(self.label, self.state, &rows).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most).thumb(thumb); + let mut browser = PresetBrowser::new(self.label, self.state, &source).cell_shape(shape).tiles(PresetTiles::Chips).room_height(most); if let Some(selected) = self.selected { browser = browser.selected(selected); } @@ -251,6 +216,64 @@ impl<'a> GradientPalette<'a> { } } +/// Samples a gradient's ramp at a location 0..=1. +pub type RampSampler = fn(&GradientStops, f32) -> Srgba; + +/// What the palette's presets are built from. +#[derive(craft_ui::contract::MemoProps)] +struct PaletteInputs<'a> { + groups: &'a [GradientGroup], + recent: &'a [GradientStops], + recent_label: String, + rows: StopRows, + #[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")] + sampler: Option, + /// Whether every cell is square: some preset has a tile other than the ramp. + square: bool, +} + +/// The rows of the groups: the header of each group, then its presets. A header's key names no preset +/// (`item == usize::MAX`). +fn preset_rows(inputs: &PaletteInputs<'_>, _: &Env) -> Vec> { + let mut rows = Vec::new(); + if !inputs.recent.is_empty() { + rows.push(PresetRow::group(GradientRef::Recent(usize::MAX), inputs.recent_label.clone(), 0)); + for i in 0..inputs.recent.len() { + rows.push(PresetRow::item(GradientRef::Recent(i), format!("{} {}", inputs.recent_label, i + 1), 1)); + } + } + for (group, g) in inputs.groups.iter().enumerate() { + rows.push(PresetRow::group(GradientRef::Item { group, item: usize::MAX }, g.name.clone(), 0)); + for (item, preset) in g.items.iter().enumerate() { + rows.push(PresetRow::item(GradientRef::Item { group, item }, preset.name.clone(), 1)); + } + } + rows +} + +/// Paints a preset's thumbnail: its tile, or its ramp chip, which keeps the chip's aspect in a square cell. +fn paint_thumb(inputs: &PaletteInputs<'_>, cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, GradientRef>) { + let Some(stops) = stops_of(inputs.groups, inputs.recent, *info.key) else { return }; + let (radius, edge) = GradientRamp::chip_look(&cx.style_cx()); + let default = default_sampler(inputs.rows); + let sampler: &Sampler = match &inputs.sampler { + Some(sampler) => sampler, + None => &default, + }; + let tile = item_of(inputs.groups, *info.key).map_or(GradientTile::Ramp, |item| item.tile); + if tile != GradientTile::Ramp { + tile.paint(cx, rect, radius, stops, sampler, edge); + return; + } + let (wide, high) = GradientRamp::CHIP_ASPECT; + let chip = if inputs.square { + Rect::from_center_size(rect.center(), egui::vec2(rect.width(), rect.width() * f32::from(high) / f32::from(wide))) + } else { + rect + }; + GradientRamp::paint_chip(cx, chip, radius, &GradientRamp::colors(stops, sampler), edge); +} + /// The stops of the preset `key` names; none for a group header. pub(super) fn stops_of<'a>(groups: &'a [GradientGroup], recent: &'a [GradientStops], key: GradientRef) -> Option<&'a GradientStops> { match key { diff --git a/crates/draw/src/ui/mod.rs b/crates/draw/src/ui/mod.rs index f81c4c9d9..3b392dd2f 100644 --- a/crates/draw/src/ui/mod.rs +++ b/crates/draw/src/ui/mod.rs @@ -79,7 +79,7 @@ pub use crop::{ pub use crop::{PerspectiveCropQuad, PerspectiveQuad}; pub use gradient::{ FocusOutline, GradientGroup, GradientItem, GradientLine, GradientMap, GradientMapEditor, GradientMapOutput, GradientOverlay, GradientPalette, - GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart, + GradientRef, GradientSwatch, GradientTile, LineGradient, LinePart, RampSampler, }; pub use gradient::{GradientFill, GradientFillEditor, GradientFillEditorOutput, GradientFillWords, GradientStyle}; pub use measure::{ diff --git a/crates/draw/src/ui/pattern/dialog.rs b/crates/draw/src/ui/pattern/dialog.rs index 3e4f8e007..5fe71528b 100644 --- a/crates/draw/src/ui/pattern/dialog.rs +++ b/crates/draw/src/ui/pattern/dialog.rs @@ -7,9 +7,8 @@ use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _}; use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id}; use craft_ui::layout_components::Stack; use craft_ui::patterns::form_dialogs::FormDialog; -use craft_ui::primitives::ContentPainterCx; use craft_ui::runtime::env::Env; -use egui::{Rect, Ui}; +use egui::Ui; use serde_json::{Value, json}; /// Photoshop's Pattern Fill dialog (Layer, New Fill Layer, Pattern...; a Pattern Fill layer's thumbnail; Layer Content @@ -49,8 +48,8 @@ impl PatternFillDialog { /// Paints a swatch's tile (see [`PatternFillEditor::thumbnails`]). #[must_use] - pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self { - self.thumbnails = Some(SwatchPainter::new(paint)); + pub fn thumbnails(mut self, paint: SwatchPainter) -> Self { + self.thumbnails = Some(paint); self } @@ -160,8 +159,8 @@ impl StackDialog for PatternFillDialog { cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY); } let mut editor = PatternFillEditor::new(words.pattern.clone(), Bind::bound(&mut *value), swatches); - if let Some(painter) = thumbnails.clone() { - editor = editor.thumbnails(move |cx, rect, swatch| painter.paint(cx, rect, swatch)); + if let Some(paint) = *thumbnails { + editor = editor.thumbnails(paint); } editor.show(ui); }); diff --git a/crates/draw/src/ui/pattern/editor.rs b/crates/draw/src/ui/pattern/editor.rs index f9ba6d74f..e9e7f29fa 100644 --- a/crates/draw/src/ui/pattern/editor.rs +++ b/crates/draw/src/ui/pattern/editor.rs @@ -11,7 +11,7 @@ use craft_ui::contract::{Bind, FieldLayout, Outcome, Props as _, Remember as _, use craft_ui::display::{Shade, Text}; use craft_ui::form::{Field, FieldGroup}; use craft_ui::layout_components::Row; -use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetPicker, PresetRow, PresetState, PresetView, ThumbInfo}; +use craft_ui::patterns::presets::{CellShape, PresetBrowser, PresetFns, PresetPicker, PresetRow, PresetSource, PresetState, PresetView}; use craft_ui::primitives::ContentPainterCx; use craft_ui::runtime::env::{Env, Label, UnitKind}; use craft_ui::text::NumberField; @@ -21,20 +21,16 @@ use egui::{Rect, Response, Ui}; /// The angle of the dial runs over half a turn each way. pub(super) const ANGLE_RANGE: std::ops::RangeInclusive = -180.0..=180.0; -type SwatchPaintFn = Arc, Rect, &PatternSwatch) + Send + Sync>; +/// The host's painter of a swatch's tile. A `fn`, which captures nothing, so the presets that paint it key it by its +/// address. +pub type SwatchPainter = fn(&ContentPainterCx<'_>, Rect, &PatternSwatch); -/// The host's painter of a swatch's tile, shared with the preset rows that paint it. -#[derive(Clone)] -pub struct SwatchPainter(SwatchPaintFn); - -impl SwatchPainter { - pub(super) fn new(paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self { - SwatchPainter(Arc::new(paint)) - } - - pub(super) fn paint(&self, cx: &ContentPainterCx<'_>, rect: Rect, swatch: &PatternSwatch) { - (self.0)(cx, rect, swatch); - } +/// What the editor's presets are built from. +#[derive(craft_ui::contract::MemoProps)] +struct TileInputs<'a> { + swatches: &'a [PatternSwatch], + #[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")] + thumbnails: Option, } /// What [`PatternFillEditor`] reports. @@ -86,8 +82,8 @@ impl<'a> PatternFillEditor<'a> { } /// Paints a swatch's tile into a rect (the picker's field and cells, the preset grid). - pub fn thumbnails(mut self, paint: impl Fn(&ContentPainterCx<'_>, Rect, &PatternSwatch) + Send + Sync + 'static) -> Self { - self.thumbnails = Some(SwatchPainter::new(paint)); + pub fn thumbnails(mut self, paint: SwatchPainter) -> Self { + self.thumbnails = Some(paint); self } @@ -98,7 +94,7 @@ impl<'a> PatternFillEditor<'a> { let words = env.words::(); let units = env.units(); let name: Arc = label.as_str().into(); - let rows: Vec> = swatches.iter().map(|swatch| tile_row(swatch, thumbnails.as_ref())).collect(); + let rows = PresetSource::new(TileInputs { swatches, thumbnails }, PresetFns::new(tile_rows)); let mut events = EditEvents::new(); let shown = FieldGroup::new(label).show(ui, |ui, cx| { events = EditEvents::new(); @@ -108,20 +104,13 @@ impl<'a> PatternFillEditor<'a> { let mut take = |edits: EditEvents| next.extend(edits); if let Some(colors) = current.colors { let browser = Field::new(words.pattern.clone()).id_salt("grid").show(ui, |ui, _| { - let thumbs = thumbnails.clone(); - let mut browser = PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows) + PresetBrowser::new(words.pattern.clone(), Bind::bound(&mut state), &rows) .selected(current.pattern.clone()) .cell_shape(CellShape::Square) .view_lock(PresetView::Grid) - .row_menu(false); - if let Some(thumbs) = thumbs { - browser = browser.thumb(move |cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, String>| { - if let Some(swatch) = swatches.iter().find(|swatch| swatch.id == *info.key) { - thumbs.paint(cx, rect, swatch); - } - }); - } - browser.show(ui).events + .row_menu(false) + .show(ui) + .events }); for picked in browser.inner.into_iter().flatten().filter_map(selected_key) { if picked != current.pattern { @@ -206,16 +195,19 @@ impl<'a> PatternFillEditor<'a> { /// The most decimals the Scale field shows. const SCALE_DECIMALS: usize = 2; -/// The preset row of `swatch`: its name, with the tile painter when the host gave one. -fn tile_row(swatch: &PatternSwatch, thumbnails: Option<&SwatchPainter>) -> PresetRow { - let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0); - match thumbnails { - Some(painter) => { - let (painter, swatch) = (painter.clone(), swatch.clone()); - row.preview(CellShape::Square.aspect(), move |cx, rect| painter.paint(cx, rect, &swatch)) +/// The preset row of each swatch: its name, with the tile painter when the host gave one. +fn tile_rows(inputs: &TileInputs<'_>, _: &Env) -> Vec> { + let tile_row = |swatch: &PatternSwatch| { + let row = PresetRow::item(swatch.id.clone(), swatch.name.clone(), 0); + match inputs.thumbnails { + Some(paint) => { + let swatch = swatch.clone(); + row.preview(CellShape::Square.aspect(), move |cx, rect| paint(cx, rect, &swatch)) + } + None => row, } - None => row, - } + }; + inputs.swatches.iter().map(tile_row).collect() } /// The key a browser event picked: a click or Enter on a tile. diff --git a/crates/draw/src/ui/pattern/mod.rs b/crates/draw/src/ui/pattern/mod.rs index 18f81b6a2..9c93705ac 100644 --- a/crates/draw/src/ui/pattern/mod.rs +++ b/crates/draw/src/ui/pattern/mod.rs @@ -17,7 +17,7 @@ pub use words::PatternWords; /// A pattern the editor offers: the app's pattern library (PhotoCraft's Patterns, a bitmap each) /// or its preset patterns (PowerPoint's "pct25", "dkHorz", …). The app paints each swatch's tile /// ([`PatternFillEditor::thumbnails`]). -#[derive(Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub struct PatternSwatch { /// The app's id, which [`PatternFillOptions::pattern`] holds. diff --git a/crates/draw/tests/it/brush_presets.rs b/crates/draw/tests/it/brush_presets.rs index 55a1fc813..348d7bfc4 100644 --- a/crates/draw/tests/it/brush_presets.rs +++ b/crates/draw/tests/it/brush_presets.rs @@ -7,7 +7,8 @@ use craft_draw::ui::brush_settings::TipAngle; use craft_ui::contract::{Bind, Role, SaveKey}; use craft_ui::patterns::presets::{PresetEvent, PresetFns, PresetRow, PresetSource}; use craft_ui::runtime::env::Env; -use craft_ui::testing::{Fixture, trial}; +use craft_ui::testing::pointer::{moved, press, release}; +use craft_ui::testing::{Fixture, MemoRun, last_frame_memo_runs, trial}; use egui::{Key, Modifiers, Pos2, Rect, Vec2}; use std::cell::RefCell; use std::rc::Rc; @@ -222,3 +223,35 @@ fn escape_reverts_size_hardness_angle_and_roundness() { fixture.idle(3); assert_eq!(host.borrow().values, OPENED, "Escape puts all four back"); } + +/// The memoized views of `props` that ran in the last frame. +fn views_ran(fixture: &Fixture, props: &str) -> usize { + last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Ran).count() +} + +/// The memoized views of `props` that replayed in the last frame. +fn views_replayed(fixture: &Fixture, props: &str) -> usize { + last_frame_memo_runs(fixture.ctx()).into_iter().filter(|(name, _, run)| name.contains(props) && *run == MemoRun::Replayed).count() +} + +/// While nothing changes the open picker's head and preset list replay; each move of a Size drag runs the head's view +/// and replays the list. +#[trial] +fn a_size_drag_runs_the_head_and_replays_the_preset_list() { + let (mut fixture, host) = opened_rig(true, false); + fixture.frame(vec![]); + assert_eq!((views_ran(&fixture, "HeadProps"), views_ran(&fixture, "ListProps")), (0, 0), "an idle frame runs neither view"); + let slider = fixture.by_role(Role::SLIDER).into_iter().find(|target| fixture.tree().name_of(target.node) == Some("Size")); + let slider = slider.expect("the Size slider shows").rect; + let from = slider.left_center() + Vec2::new(slider.width() * 0.3, 0.0); + fixture.frame(vec![moved(from)]); + fixture.frame(vec![press(from)]); + for step in 1..=4 { + fixture.frame(vec![moved(from + Vec2::new(8.0 * step as f32, 0.0))]); + assert!(views_ran(&fixture, "HeadProps") > 0, "move {step} runs the head"); + assert_eq!(views_ran(&fixture, "ListProps"), 0, "move {step} runs no list view"); + assert!(views_replayed(&fixture, "ListProps") > 0, "move {step} replays the list"); + } + fixture.frame(vec![release(from + Vec2::new(32.0, 0.0))]); + assert_ne!(host.borrow().values.diameter, OPENED.diameter, "the drag edited the size"); +} diff --git a/crates/imaging/src/layer_style/contour.rs b/crates/imaging/src/layer_style/contour.rs index c1e1e3c3b..f26c95dd6 100644 --- a/crates/imaging/src/layer_style/contour.rs +++ b/crates/imaging/src/layer_style/contour.rs @@ -2,6 +2,7 @@ /// A contour point, input and output in 0..=1. #[derive(Clone, Copy, Debug, PartialEq)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct ContourPoint { /// Input value, 0..=1 (the horizontal axis). pub input: f32, @@ -15,6 +16,7 @@ pub struct ContourPoint { /// Built-in presets carry their preset name; an edited preset is named "Custom"; imported /// contours keep their own name and points. #[derive(Clone, Debug, PartialEq)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] pub struct Contour { #[allow(missing_docs)] pub name: String, diff --git a/crates/imaging/src/ui/layer_style/contour/editor.rs b/crates/imaging/src/ui/layer_style/contour/editor.rs index 50b2b3ca6..e83c78d03 100644 --- a/crates/imaging/src/ui/layer_style/contour/editor.rs +++ b/crates/imaging/src/ui/layer_style/contour/editor.rs @@ -15,7 +15,7 @@ use craft_ui::sections::{DialogRole, FooterButton}; use craft_ui::text::TextField; use egui::Ui; -use super::{ContourAction, ContourRequest, ContourWords, SharedSampler, from_curve, to_curve}; +use super::{ContourAction, ContourRequest, ContourSampler, ContourWords, from_curve, to_curve}; use crate::layer_style::Contour; use crate::ui::curve::CurveEditor; @@ -49,7 +49,7 @@ pub struct ContourEditorDialog { key: String, initial: Contour, draft: Draft, - sampler: Option, + sampler: Option, changed: bool, action: Option, focus_name: bool, @@ -72,8 +72,8 @@ impl ContourEditorDialog { /// The interpolation of the points, as the engine does it. Without it the curve is a monotone cubic. #[must_use] - pub fn sampler(mut self, sampler: impl Fn(&[[f32; 2]]) -> Vec + Send + Sync + 'static) -> Self { - self.sampler = Some(std::sync::Arc::new(sampler)); + pub fn sampler(mut self, sampler: ContourSampler) -> Self { + self.sampler = Some(sampler); self } @@ -121,7 +121,7 @@ impl StackDialog for ContourEditorDialog { let extras = [(Extra::Load, &words.load), (Extra::Save, &words.save), (Extra::New, &words.new)]; let named = Cell::new(false); let focus_name = std::mem::take(&mut self.focus_name); - let sampler = self.sampler.clone(); + let sampler = self.sampler; let shown = FormDialog::new(words.editor.clone(), Bind::bound(&mut self.draft)) .outer_gesture(true) .history(true) @@ -171,8 +171,8 @@ impl StackDialog for ContourEditorDialog { .percent() .corners() .between(between); - if let Some(sampler) = sampler.clone() { - editor = editor.sampler(move |points| sampler(points)); + if let Some(sampler) = sampler { + editor = editor.sampler(sampler); } let edit = editor.show(ui); if let Some(next) = edit.events.value().and_then(|curve| from_curve(curve, &draft.contour.name)) { diff --git a/crates/imaging/src/ui/layer_style/contour/mod.rs b/crates/imaging/src/ui/layer_style/contour/mod.rs index c2f410b15..6ee2d4ed1 100644 --- a/crates/imaging/src/ui/layer_style/contour/mod.rs +++ b/crates/imaging/src/ui/layer_style/contour/mod.rs @@ -5,14 +5,12 @@ mod editor; #[cfg(feature = "suite")] pub(crate) mod stories; -use std::sync::Arc; - use craft_behavior::{EditEvents, Mixed}; use craft_ui::choice::Checkbox; use craft_ui::contract::{Bind, EditResponse, NoValue, Outcome, Pattern, Props as _, Show as _, ShowContainer as _}; use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::ThumbAspect; -use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFooterEvent, PresetPicker, PresetRow, PresetState}; +use craft_ui::patterns::presets::{PickerField, PresetEvent, PresetFns, PresetFooterEvent, PresetPicker, PresetRow, PresetSource, PresetState}; use craft_ui::primitives::ContentPainterCx; use craft_ui::runtime::env::{Env, Label}; use egui::{Rect, Response, Ui}; @@ -78,14 +76,15 @@ impl ContourWords { } } -/// A host's interpolation of a contour's points, shared with the thumbnails' painters. -pub(crate) type SharedSampler = Arc Vec + Send + Sync>; +/// A host's interpolation of a contour's points (levels in, levels out), shared with the thumbnails' painters. A `fn`, +/// which captures nothing, so the contour presets key it by its address. +pub type ContourSampler = fn(&[[f32; 2]]) -> Vec; /// The levels of a contour as a curve: input and output run `0..=255`. const LEVELS: f32 = 255.0; /// A contour a picker lists: one of the built-in contours or one of the user's. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::MemoProps)] #[non_exhaustive] pub enum ContourKey { /// The built-in contour at this place of [`Contour::presets`]. @@ -153,24 +152,39 @@ impl Outcome for ContourFieldOutput { } } -/// The rows of the contour picker: the built-in contours, then the user's, named by `words`, with a thumbnail of each -/// curve. `sampler` interpolates the points as the engine does; without it the thumbnails use a monotone cubic. -pub fn contour_rows(presets: &[Contour], user: &[Contour], words: &ContourWords, sampler: Option) -> Vec> { +/// What the contour presets are built from. +#[derive(craft_ui::contract::MemoProps)] +struct ContourInputs<'a> { + presets: &'a [Contour], + user: &'a [Contour], + #[memo_props(hash = "a fn pointer: its address names the code, which captures nothing")] + sampler: Option, +} + +/// The presets of the contour picker: the built-in contours, then the user's, with a thumbnail of each curve; the +/// user's may be deleted. `sampler` interpolates the points as the engine does; without it the thumbnails use a +/// monotone cubic. +pub fn contour_source<'a>(presets: &'a [Contour], user: &'a [Contour], sampler: Option) -> PresetSource<'a, ContourKey> { + let fns = PresetFns::new(contour_rows).can_delete(|_, key| matches!(key, ContourKey::User(_))); + PresetSource::new(ContourInputs { presets, user, sampler }, fns) +} + +/// The rows of the contour picker, named by the scope's words. +fn contour_rows(inputs: &ContourInputs<'_>, env: &Env) -> Vec> { + let words = env.words::(); + let sampler = inputs.sampler; let row = |key: ContourKey, contour: &Contour| { let name = words.contour_name(&contour.name).to_owned(); - let curve = Arc::new(to_curve(contour)); - let sampler = sampler.clone(); - PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler.as_deref())) + let curve = to_curve(contour); + PresetRow::item(key, name, 0).preview(ThumbAspect::SQUARE, move |painter, rect| paint_thumbnail(painter, rect, &curve, sampler)) }; - let presets = presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour)); - let user = user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour)); + let presets = inputs.presets.iter().enumerate().map(|(i, contour)| row(ContourKey::Preset(i), contour)); + let user = inputs.user.iter().enumerate().map(|(i, contour)| row(ContourKey::User(i), contour)); presets.chain(user).collect() } -type SamplerFn = dyn Fn(&[[f32; 2]]) -> Vec + Send + Sync; - /// A thumbnail of a contour: its curve in the curve preview's look (plot, quarter grid, diagonal). -fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option<&SamplerFn>) { +fn paint_thumbnail(painter: &ContentPainterCx<'_>, rect: Rect, curve: &Curve, sampler: Option) { let Curve::Points { points, corners } = curve else { return }; let outputs = Curve::through(points, corners, |points| match sampler { Some(sampler) => sampler(points), @@ -206,21 +220,22 @@ pub fn from_curve(curve: &Curve, name: &str) -> Option { pub struct ContourField<'a> { label: Label, contour: Bind<'a, Contour>, - rows: &'a [PresetRow], + source: &'a PresetSource<'a, ContourKey>, state: Bind<'a, PresetState>, user: &'a [Contour], anti_alias: Option>>, } impl<'a> ContourField<'a> { - /// A field named `label` over `contour`, choosing among `rows` ([`contour_rows`]); `state` is the browser's view. + /// A field named `label` over `contour`, choosing among `source` ([`contour_source`]); `state` is the browser's + /// view. pub fn new( label: impl Into