From 4bfb5c756797f4c9400779b32ee910a9eb402fb7 Mon Sep 17 00:00:00 2001 From: aiongg Date: Fri, 20 Nov 2026 22:58:53 +0000 Subject: [PATCH] Preset lists as sources: brush picker, Brushes panel, tip grid, preset panels and pickers, Fill, Pattern Fill, Layer Style and the Preset Manager build their rows from MemoProps inputs; brush picker count trials --- .../ui-egui/src/brush_picker_memo_trials.rs | 119 +++++++ crates/ui-egui/src/dialogs/fill_ui.rs | 6 +- crates/ui-egui/src/dialogs/layer_style.rs | 69 ++-- .../src/dialogs/layer_style/contour.rs | 22 +- crates/ui-egui/src/dialogs/pattern_fill_ui.rs | 19 +- crates/ui-egui/src/lib.rs | 2 + .../ui-egui/src/panels/brush_panel/brushes.rs | 29 +- crates/ui-egui/src/panels/brush_sections.rs | 8 +- crates/ui-egui/src/panels/preset_browser.rs | 320 ++++++++++++------ crates/ui-egui/src/prefs/prefs_ui/presets.rs | 20 +- crates/ui-egui/src/tools/brush_picker.rs | 86 ++--- 11 files changed, 479 insertions(+), 221 deletions(-) create mode 100644 crates/ui-egui/src/brush_picker_memo_trials.rs diff --git a/crates/ui-egui/src/brush_picker_memo_trials.rs b/crates/ui-egui/src/brush_picker_memo_trials.rs new file mode 100644 index 0000000000..83e09d8560 --- /dev/null +++ b/crates/ui-egui/src/brush_picker_memo_trials.rs @@ -0,0 +1,119 @@ +//! The canvas Brush Preset picker runs only what changes: open with nothing changing, its head and preset list replay +//! and no list row runs; a Size drag runs the head and replays the list on every move; a preset rename or a new preset +//! builds the rows once, and the lists settle. + +use craft::ui::runtime::measure::{MemoRun, last_frame_derived_builds, last_frame_memo_runs, last_pass_memo_runs, last_pass_runs}; +use egui::accesskit::Role; +use egui::{Event, Pos2, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +type H = Harness<'static, Box>; + +/// The app with a document and the Brush tool, its canvas picker open and settled. +fn opened() -> H { + let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).with_step_dt(1.0 / 60.0).build_eframe(|cc| { + PhotocraftApp::setup_context(&cc.egui_ctx, Default::default()); + let mut session = photocraft_engine::Session::new(); + session.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + let mut app = PhotocraftApp::with_context(cc.egui_ctx.clone(), session, crate::Services::default()); + app.ui.tool = Tool::Brush; + app + }); + h.run_steps(8); + let at = h.state().last_canvas_rect.center(); + crate::brush_picker::open(h.state_mut(), [at.x, at.y]); + h.run_steps(8); + h +} + +/// The memoized views whose props type is named `props` that took part in the last frame as `how`, by id. +fn views(h: &H, props: &str, how: MemoRun) -> Vec { + last_frame_memo_runs(&h.ctx).into_iter().filter(|(name, _, run)| name.contains(props) && *run == how).map(|(_, id, _)| id).collect() +} + +/// The list rows that ran in the last pass. +fn list_rows(h: &H) -> u32 { + last_pass_runs(&h.ctx).iter().filter(|(ty, _)| ty.ends_with("::ListRow")).map(|(_, runs)| runs).sum() +} + +/// The picker's Size slider. +fn size_slider(h: &H) -> egui::Rect { + let slider = h.query_all_by_role(Role::Slider).find(|n| n.accesskit_node().label().is_some_and(|label| label.starts_with("Size"))); + slider.expect("the picker's Size slider shows").rect() +} + +fn press(h: &mut H, at: Pos2, pressed: bool) { + h.event(Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); +} + +#[test] +fn an_open_picker_with_nothing_changing_runs_no_list_row_and_no_head() { + let mut h = opened(); + assert!(crate::brush_picker::opened_at(h.state()).is_some(), "the picker is open"); + for frame in 0..3 { + h.run_steps(1); + assert_eq!(list_rows(&h), 0, "idle frame {frame} runs no list row"); + assert!(views(&h, "HeadProps", MemoRun::Ran).is_empty(), "idle frame {frame} runs no head"); + assert!(!views(&h, "HeadProps", MemoRun::Replayed).is_empty(), "idle frame {frame} replays the head"); + assert!(views(&h, "ListProps", MemoRun::Ran).is_empty(), "idle frame {frame} runs no preset list"); + } +} + +#[test] +fn a_picker_size_drag_runs_the_head_and_replays_the_preset_list_on_every_move() { + let mut h = opened(); + let size = size_slider(&h); + let from = egui::pos2(size.left() + size.width() * 0.2, size.center().y); + let before = h.state().session.tools.brush.size; + h.event(Event::PointerMoved(from)); + h.run_steps(1); + press(&mut h, from, true); + h.run_steps(1); + let mut at = from; + for step in 1..=5 { + at += vec2(3.0, 0.0); + h.event(Event::PointerMoved(at)); + h.run_steps(1); + assert!(!views(&h, "HeadProps", MemoRun::Ran).is_empty(), "move {step} runs the head"); + assert!(views(&h, "ListProps", MemoRun::Ran).is_empty(), "move {step} runs no preset list"); + assert!(!views(&h, "ListProps", MemoRun::Replayed).is_empty(), "move {step} replays the preset list"); + assert_eq!(list_rows(&h), 0, "move {step} runs no list row"); + } + press(&mut h, at, false); + h.run_steps(1); + assert_ne!(h.state().session.tools.brush.size, before, "the drag set the brush size"); +} + +#[test] +fn renaming_or_adding_a_brush_preset_builds_the_rows_once_and_settles() { + let mut h = opened(); + let name = h.state().session.tools.presets.first().expect("a preset").name.clone(); + // The frames each edit takes to settle: an added row grows the popover in the frame after it, and the views whose + // room that changes run once more. + let edits = [("brush.presets.rename", json!({"name": name, "newName": "Renamed Brush"}), 1), ("brush.presets.save", json!({"name": "Added Brush"}), 2)]; + for (command, params, settle) in edits { + h.state_mut().run(command, params).unwrap_or_else(|e| panic!("{command}: {e}")); + h.run_steps(1); + assert!(!views(&h, "ListProps", MemoRun::Ran).is_empty(), "{command}: the frame after it runs the picker's list"); + // The real runs of the last pass: a popover's sizing calls its list's view again when the rows change. + let ran: Vec = + last_pass_memo_runs(&h.ctx).into_iter().filter(|(name, _, run)| name.contains("ListProps") && *run == MemoRun::Ran).map(|(_, id, _)| id).collect(); + let mut once = ran.clone(); + once.sort_by_key(|id| id.value()); + once.dedup(); + assert_eq!(once.len(), ran.len(), "{command}: each list runs once in the pass"); + let built = last_frame_derived_builds(&h.ctx); + assert!(built.iter().all(|(_, n)| *n == 1), "{command}: each derived value is built once in the frame: {built:?}"); + for frame in 1..=settle { + h.run_steps(1); + let again: Vec<_> = last_frame_derived_builds(&h.ctx).into_iter().filter(|(id, _)| built.iter().any(|(b, _)| b == id)).collect(); + assert!(again.is_empty(), "{command}: frame {frame} after it builds none of them again: {again:?}"); + } + assert!(views(&h, "ListProps", MemoRun::Ran).is_empty(), "{command}: {settle} frames after it every list replays"); + } +} diff --git a/crates/ui-egui/src/dialogs/fill_ui.rs b/crates/ui-egui/src/dialogs/fill_ui.rs index 1e197df020..d823352e3a 100644 --- a/crates/ui-egui/src/dialogs/fill_ui.rs +++ b/crates/ui-egui/src/dialogs/fill_ui.rs @@ -4,8 +4,6 @@ //! White) with the content's own options, then Blending: Mode, Opacity and Preserve //! Transparency. OK remembers the choices in the saved tier. -use std::borrow::Cow; - use craft::ui::contract::Bind; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamDialog, ParamKind, ParamResult}; @@ -85,7 +83,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId { let [r, g, b, _] = app.session.tools.foreground; let first = app.session.patterns.items.first().map(|p| p.id.clone()); let ctx = app.ctx().clone(); - let patterns = crate::panels::preset_browser::pattern_rows(app, &ctx); + let patterns = crate::panels::preset_browser::pattern_swatches(app, &ctx); let rows = rows([r, g, b], first.clone()); let reset = defaults([r, g, b], first); let title = Label::from(tl!("Fill")); @@ -94,7 +92,7 @@ pub fn open(app: &mut PhotocraftApp) -> DialogId { .values(Bind::bound(fields)) .remember(SaveKey::named(REMEMBER)) .reset_to(reset.clone()) - .patterns(Cow::Owned(patterns.clone())) + .patterns(crate::panels::preset_browser::pattern_source(patterns.clone())) }) } diff --git a/crates/ui-egui/src/dialogs/layer_style.rs b/crates/ui-egui/src/dialogs/layer_style.rs index 4a5aa47dd8..37b99623d5 100644 --- a/crates/ui-egui/src/dialogs/layer_style.rs +++ b/crates/ui-egui/src/dialogs/layer_style.rs @@ -19,10 +19,12 @@ use craft::imaging::layer_style::{ use craft::imaging::ui::layer_style::{ContourEditorDialog, HostedLayerStyle, LayerStyleAsk}; use craft::theme::Srgba; use craft::ui::contract::Entry; +use craft::ui::contract::Tracked; use craft::ui::dialog::{DialogId, DialogResult}; -use craft::ui::patterns::presets::{PresetRow, ThumbInfo}; +use craft::ui::patterns::presets::{PresetFns, PresetRow, PresetSource, ThumbInfo}; use craft::ui::primitives::ContentPainterCx; use craft::ui::primitives::textures::TextureCache; +use craft::ui::runtime::env::Env; use egui::{ColorImage, Pos2, Rect, pos2}; use photocraft_doc::effects::{FxPaint, GlowSource, GlowTechnique, StrokePosition}; use photocraft_doc::{Document, Effect, Layer, LayerId}; @@ -31,6 +33,7 @@ use photocraft_engine::pattern_cmds::PatternLibrary; use photocraft_engine::presets::styles::StylePreset; use serde_json::{Map, Value, json}; +use crate::panels::preset_browser::StyleLibrary; use crate::{PhotocraftApp, color_picker_ui}; #[cfg(test)] @@ -507,10 +510,10 @@ pub fn open(app: &mut PhotocraftApp, select: Option<&str>) -> Option { .specs(specs) .blend_keys(keys) .blend_modes(blend_modes(&layer)) - .patterns(pattern_list(app)) + .patterns(PresetSource::new(pattern_list(app), PresetFns::new(pattern_rows))) .user_contours(contour::user_contours(app)) - .sampler(contour::sampler()) - .style_presets(style_rows(app), style_thumb(app)) + .sampler(contour::sampler) + .style_presets(style_presets(app)) .gradient_presets(gradient_presets(app)) .preview_thumb(preview_thumb(app)) .canvas(crate::canvas::document_display::CanvasHost::primary(app, idx).canvas_id()); @@ -571,18 +574,23 @@ fn blend_keys() -> HashMap { photocraft_color::BlendMode::LAYER_MODES.into_iter().map(|m| (m.label().to_string(), m.label().to_string())).collect() } -/// The patterns a style can use (document's, then the library's). -pub fn pattern_list(app: &PhotocraftApp) -> Vec> { +/// The patterns a style can use (document's, then the library's), as (id, name). +pub fn pattern_list(app: &PhotocraftApp) -> Vec<(String, String)> { let mut seen = HashSet::new(); - let doc_pats = app.session.active().map(|d| d.doc.patterns.clone()).unwrap_or_default(); + let doc_pats = app.session.active().map(|d| d.doc.patterns.as_slice()).unwrap_or_default(); doc_pats .iter() .chain(app.session.patterns.items.iter()) .filter(|p| seen.insert(p.id.clone())) - .map(|p| PresetRow::item(p.id.clone(), p.display_name(), 0)) + .map(|p| (p.id.clone(), p.display_name().to_string())) .collect() } +/// One row per pattern of [`pattern_list`], keyed by its id. +fn pattern_rows(patterns: &Vec<(String, String)>, _: &Env) -> Vec> { + patterns.iter().map(|(id, name)| PresetRow::item(id.clone(), name.clone(), 0)).collect() +} + /// The Gradients panel's presets resolved with the tool colours, for the Gradient field's select. fn gradient_presets(app: &PhotocraftApp) -> Vec<(String, GradientStops)> { let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); @@ -598,38 +606,41 @@ fn gradient_presets(app: &PhotocraftApp) -> Vec<(String, GradientStops)> { .collect() } +/// What the Styles page's presets are built from: each style group's name and its styles' names, and the library the +/// thumbnails draw from, as the app held them when the dialog opened. +#[derive(craft::ui::contract::MemoProps)] +struct StylePresets { + groups: Vec<(String, Vec)>, + library: Tracked, +} + +/// The Styles page's presets. +fn style_presets(app: &PhotocraftApp) -> PresetSource<'static, String> { + let groups = app.session.presets.styles.iter().map(|group| (group.name.clone(), group.items.iter().map(|st| st.name.clone()).collect())).collect(); + let inputs = StylePresets { groups, library: StyleLibrary::of(&app.session) }; + PresetSource::new(inputs, PresetFns::new(style_rows).thumb(style_thumb)) +} + /// The Styles page's rows: each group with its presets, presets keyed by name and groups by `group/`. -fn style_rows(app: &PhotocraftApp) -> Vec> { +fn style_rows(inputs: &StylePresets, _: &Env) -> Vec> { let mut rows = Vec::new(); - for group in &app.session.presets.styles { - rows.push(PresetRow::group(format!("group/{}", group.name), group.name.clone(), 0).count(group.items.len())); - rows.extend(group.items.iter().map(|st| PresetRow::item(st.name.clone(), st.name.clone(), 1))); + for (group, styles) in &inputs.groups { + rows.push(PresetRow::group(format!("group/{group}"), group.clone(), 0).count(styles.len())); + rows.extend(styles.iter().map(|name| PresetRow::item(name.clone(), name.clone(), 1))); } rows } +/// Paints a style preset's thumbnail; the Styles panel shares the textures. +fn style_thumb(inputs: &StylePresets, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, String>) { + inputs.library.paint(cx, rect, info.key); +} + fn paint_picture(cx: &ContentPainterCx, rect: Rect, key: impl std::hash::Hash + 'static, image: impl FnOnce() -> ColorImage) { let texture = TextureCache::texture(cx.painter.ctx(), key, image); cx.picture(texture, rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); } -/// Paints a style preset's thumbnail. The dialog's painter cannot read the app, so it owns the -/// presets and patterns; a picture is rendered on a texture miss only, under the key the Styles -/// panel uses, so both share the textures. -fn style_thumb(app: &PhotocraftApp) -> impl Fn(&ContentPainterCx, Rect, ThumbInfo<'_, String>) + Send + 'static { - let presets: Vec = app.session.presets.styles.iter().flat_map(|g| g.items.iter().cloned()).collect(); - let patterns = app.session.patterns.clone(); - move |cx, rect, info| { - let Some(style) = presets.iter().find(|s| &s.name == info.key) else { return }; - let key = ("style", style.name.clone(), style.effects.len(), format!("{:?}{:?}", style.blend, style.fill_opacity)); - paint_picture(cx, rect, key, || { - let mut scratch = Session::new(); - scratch.patterns = patterns.clone(); - crate::panels::preset_browser::style_image(&scratch, style) - }); - } -} - /// Paints the preview swatch: the draft's style on a sample square, rebuilt when its render hash changes. fn preview_thumb(app: &PhotocraftApp) -> impl Fn(&ContentPainterCx, Rect, &LayerStyleDraft) + Send + Sync + 'static { let patterns = app.session.patterns.clone(); diff --git a/crates/ui-egui/src/dialogs/layer_style/contour.rs b/crates/ui-egui/src/dialogs/layer_style/contour.rs index a8390d9def..70bfe13762 100644 --- a/crates/ui-egui/src/dialogs/layer_style/contour.rs +++ b/crates/ui-egui/src/dialogs/layer_style/contour.rs @@ -60,23 +60,21 @@ pub(super) fn user_contours(app: &PhotocraftApp) -> Vec { /// The engine's interpolation of a contour's points (levels `0..=255` on both axes) as one output /// level per input level. -pub(super) fn sampler() -> impl Fn(&[[f32; 2]]) -> Vec + Send + Sync + 'static { - |points| { - let points: Vec = points.iter().map(|p| CurvePoint { input: p[0] / LEVELS, output: p[1] / LEVELS }).collect(); - let lut = photocraft_compose::adjust::contour_curve_lut(&points, &[]); - (0..=LEVELS as usize) - .map(|level| { - let at = (level as f32 / LEVELS * lut.len().saturating_sub(1) as f32).round() as usize; - lut.get(at).copied().unwrap_or(0.0) * LEVELS - }) - .collect() - } +pub(super) fn sampler(points: &[[f32; 2]]) -> Vec { + let points: Vec = points.iter().map(|p| CurvePoint { input: p[0] / LEVELS, output: p[1] / LEVELS }).collect(); + let lut = photocraft_compose::adjust::contour_curve_lut(&points, &[]); + (0..=LEVELS as usize) + .map(|level| { + let at = (level as f32 / LEVELS * lut.len().saturating_sub(1) as f32).round() as usize; + lut.get(at).copied().unwrap_or(0.0) * LEVELS + }) + .collect() } /// Opens the Contour Editor on `request` as a child of the Layer Style dialog `parent`. pub(super) fn open_editor(app: &mut PhotocraftApp, parent: DialogId, request: ContourRequest) { let (key, initial) = (request.key.clone(), request.contour.clone()); - let id = app.framework.dialogs.open_child(ContourEditorDialog::new(request).sampler(sampler()), parent); + let id = app.framework.dialogs.open_child(ContourEditorDialog::new(request).sampler(sampler), parent); app.layer_style_child = Some((parent, Child::Editor { id, key, initial })); } diff --git a/crates/ui-egui/src/dialogs/pattern_fill_ui.rs b/crates/ui-egui/src/dialogs/pattern_fill_ui.rs index 60cb822c0d..9885075e23 100644 --- a/crates/ui-egui/src/dialogs/pattern_fill_ui.rs +++ b/crates/ui-egui/src/dialogs/pattern_fill_ui.rs @@ -72,17 +72,14 @@ fn start(app: &mut PhotocraftApp, idx: usize, document: DocId, target: Target, o app.pattern_fill.opens += 1; let serial = app.pattern_fill.opens; let ctx = app.ctx().clone(); - let swatches: Vec = app.session.patterns.items.iter().map(|p| PatternSwatch::new(p.id.clone(), p.display_name())).collect(); - // The painter outlives this call, so it holds the textures made now. - let tiles: Vec<(String, egui::TextureId)> = - app.session.patterns.items.iter().map(|p| (p.id.clone(), crate::panels::preset_browser::pattern_texture(&ctx, p))).collect(); - let dialog = PatternFillDialog::new(options.clone(), swatches) - .thumbnails(move |cx, rect, swatch| { - if let Some((_, texture)) = tiles.iter().find(|(id, _)| *id == swatch.id) { - cx.picture(*texture, rect, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), 0.0); - } - }) - .canvas(CanvasHost::primary(app, idx).canvas_id()); + let swatches: Vec = app + .session + .patterns + .items + .iter() + .map(|p| PatternSwatch::new(p.id.clone(), p.display_name()).with_picture(crate::panels::preset_browser::pattern_texture(&ctx, p))) + .collect(); + let dialog = PatternFillDialog::new(options.clone(), swatches).canvas(CanvasHost::primary(app, idx).canvas_id()); let id = app.framework.dialogs.open(dialog); app.pattern_fill.session = Some(Session { serial, document, target, opened: options, preview: None }); id diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c611e6d177..43089ad114 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -940,6 +940,8 @@ mod move_outline_tests; #[cfg(test)] mod move_bar_distribute_gear_tests; +#[cfg(test)] +mod brush_picker_memo_trials; #[cfg(test)] mod brush_settle_trials; #[cfg(test)] diff --git a/crates/ui-egui/src/panels/brush_panel/brushes.rs b/crates/ui-egui/src/panels/brush_panel/brushes.rs index f1c498a485..ec64083f3f 100644 --- a/crates/ui-egui/src/panels/brush_panel/brushes.rs +++ b/crates/ui-egui/src/panels/brush_panel/brushes.rs @@ -9,7 +9,7 @@ use craft::behavior::{EditEvent, EditEvents, GesturePhase}; use craft::draw::ui::brush_presets::{BrushCardParts, BrushPick, BrushRowPaint, BrushesPanel, brush_row}; use craft::keymap::Mods; use craft::ui::contract::{Bind, MemoProps, MemoView, Outbox, PlainData, ReorderMove, Tracked, bind_tracked}; -use craft::ui::patterns::presets::{PresetEvent, PresetRow, PresetState, PresetView}; +use craft::ui::patterns::presets::{PresetEvent, PresetFns, PresetRow, PresetSource, PresetState, PresetView}; use craft::ui::primitives::ContentPainterCx; use craft::ui::primitives::textures::TextureCache; use craft::ui::runtime::env::Env; @@ -84,15 +84,14 @@ fn picture(cx: &ContentPainterCx, rect: Rect, key: impl Hash + 'static, image: i cx.picture(texture, rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); } -/// How one preset paints its tip and its stroke; the framework texture store caches both by signature. A signature -/// is taken when the row paints: rows built and never painted (the closed Brush Preset chip's, a measuring run's, -/// rows out of view) take none. +/// How one preset paints its tip and its stroke; the framework texture store caches both by signature. Both +/// signatures are taken here, once per build of the rows, so a paint only reads them. fn paint_of(b: &BrushSettings) -> BrushRowPaint { let brush = b.clone(); + let stroke_sig = brush_preview::preview_sig(b); BrushRowPaint::new(tip_paint(&b.tip, (b.hardness, b.angle, b.roundness)), move |cx, rect| { let color = Tokens::get(cx.painter.ctx()).text; let size = [rect.width().round().clamp(1.0, 1024.0) as usize, rect.height().round().clamp(1.0, 1024.0) as usize]; - let stroke_sig = brush_preview::preview_sig(&brush); picture(cx, rect, ("brushes-stroke", stroke_sig, size, color), || brush_preview::stroke_image(&brush, size, color)); }) } @@ -101,13 +100,24 @@ fn paint_of(b: &BrushSettings) -> BrushRowPaint { /// colour: a preset's thumbnail and the Brush Preset chip's current tip. pub(crate) fn tip_paint(tip: &TipShape, shape: (f32, f32, f32)) -> impl Fn(&ContentPainterCx, Rect) + Send + Sync + 'static { let tip = tip.clone(); + let tip_key = brush_preview::tip_sig(&tip, shape.0, shape.1, shape.2, (false, false)); move |cx, rect| { let color = Tokens::get(cx.painter.ctx()).text; - let tip_key = brush_preview::tip_sig(&tip, shape.0, shape.1, shape.2, (false, false)); picture(cx, rect, ("brushes-tip", tip_key, color), || brush_preview::tip_image(&tip, shape, 36, color)); } } +/// The presets of the brush lists: every preset of `presets` in the engine's panel order, each row showing the card +/// `parts`. The rows are built once per presets revision and parts. +pub(crate) fn brush_source(presets: &Tracked>>, parts: BrushCardParts) -> PresetSource<'_, BrushKey> { + PresetSource::new((presets, parts), PresetFns::new(brush_rows)) +} + +/// The rows of [`brush_source`]. +fn brush_rows(input: &(&Tracked>>, BrushCardParts), env: &Env) -> Vec> { + preset_rows(input.0.as_slice(), env, input.1) +} + /// The rows of every preset in the engine's panel order (the order `,` and `.` step through): a /// group row before the first preset of each group and each folder, with its count. pub(crate) fn preset_rows(presets: &[BrushPreset], env: &Env, parts: BrushCardParts) -> Vec> { @@ -194,17 +204,16 @@ pub(crate) fn panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// The Brushes panel's view. fn show_panel(props: &mut BrushesProps<'_>, ui: &mut egui::Ui) { - let env = Env::of(ui); - let rows = preset_rows(props.presets.as_slice(), &env, parts_of(props.state.view)); + let source = brush_source(props.presets, parts_of(props.state.view)); let mut panel = - BrushesPanel::new(tl!("Brushes"), &rows, bind_tracked!(props.state), Bind::bound(&mut props.diameter), f64::from(MAX_BRUSH_SIZE)).import(true); + BrushesPanel::new(tl!("Brushes"), &source, bind_tracked!(props.state), Bind::bound(&mut props.diameter), f64::from(MAX_BRUSH_SIZE)).import(true); if let Some(current) = props.current.clone() { panel = panel.selected(current); } let out = panel.show(ui); props.out.send(BrushesEvent::Size(out.diameter.events)); if !out.picks.is_empty() { - let keys = rows.iter().map(|row| row.key.clone()).collect(); + let keys = source.rows(ui.ctx(), &Env::of(ui)).iter().map(|row| row.key.clone()).collect(); props.out.send(BrushesEvent::Picks(out.picks, keys)); } } diff --git a/crates/ui-egui/src/panels/brush_sections.rs b/crates/ui-egui/src/panels/brush_sections.rs index 49c182b619..16ec4671e5 100644 --- a/crates/ui-egui/src/panels/brush_sections.rs +++ b/crates/ui-egui/src/panels/brush_sections.rs @@ -15,12 +15,12 @@ use craft::ui::form::{Field, SliderField, SliderFieldLayout}; use craft::ui::layout_components::{Row, Stack}; use craft::ui::patterns::presets::{PresetBrowser, PresetEvent, PresetState, PresetView}; use craft::ui::pickers::Select; -use craft::ui::runtime::env::{Env, UnitKind}; +use craft::ui::runtime::env::UnitKind; use egui::Ui; use photocraft_engine::BrushSettings; use photocraft_engine::paint::{self, BrushPreset, Control, Dynamic, MAX_BRUSH_SIZE, MaskMode, Pattern, PatternStyle, TipShape}; -use super::brush_panel::brushes::{BrushKey, preset_rows}; +use super::brush_panel::brushes::{BrushKey, brush_source}; use super::preset_browser::pattern_picker; use crate::PhotocraftApp; use crate::history_keys; @@ -194,9 +194,9 @@ impl Pane<'_> { /// name. fn tip_grid(&mut self, ui: &mut Ui, id: &'static str, selected: Option) -> Option { let parts = BrushCardParts::ALL.set(BrushCardPart::Name, false).set(BrushCardPart::Stroke, false); - let rows = preset_rows(self.app.session.tools.presets.as_slice(), &Env::of(ui), parts); + let source = brush_source(&self.app.session.tools.presets, parts); let mut state = PresetState::::new(); - let mut browser = PresetBrowser::new(tl!("Brush tips"), Bind::bound(&mut state), &rows) + let mut browser = PresetBrowser::new(tl!("Brush tips"), Bind::bound(&mut state), &source) .browser_id(egui::Id::unique(id)) .view_lock(PresetView::Grid) .toolbar(false) diff --git a/crates/ui-egui/src/panels/preset_browser.rs b/crates/ui-egui/src/panels/preset_browser.rs index aa56cbc6bd..4b4936cc5c 100644 --- a/crates/ui-egui/src/panels/preset_browser.rs +++ b/crates/ui-egui/src/panels/preset_browser.rs @@ -6,18 +6,21 @@ use craft::color_ui::ui::gradient::GradientRamp; use craft::keymap::CommandRef; use craft::theme::Srgba; use craft::ui::choice::Checkbox; -use craft::ui::contract::{Bind, DropZone, Props as _, Show as _}; +use craft::ui::contract::{Bind, DropZone, MemoProps, PlainData, Props as _, Show as _, Tracked}; use craft::ui::list::ThumbAspect; use craft::ui::menu::PanelRow; use craft::ui::patterns::presets::{ - CellShape, DefaultOpen, PresetBrowser, PresetCommands, PresetEvent, PresetExport, PresetFileRequest, PresetFiles, PresetFooterEvent, PresetFooterOptions, - PresetMenuAction, PresetPanelMenu, PresetPicker, PresetReorder, PresetRow, PresetState, PresetView, + CellShape, DefaultOpen, PresetBrowser, PresetCommands, PresetEvent, PresetExport, PresetFileRequest, PresetFiles, PresetFns, PresetFooterEvent, + PresetFooterOptions, PresetMenuAction, PresetPanelMenu, PresetPicker, PresetReorder, PresetRow, PresetSource, PresetState, PresetView, ThumbFn, ThumbInfo, }; use craft::ui::primitives::ContentPainterCx; use craft::ui::primitives::textures::TextureCache; use craft::ui::runtime::commands::{CommandSet as _, CommandState}; +use craft::ui::runtime::env::Env; use craft::ui::tile_grid::TileZoom; -use egui::{Color32, ColorImage, Pos2, Rect, pos2}; +use egui::{Color32, ColorImage, Pos2, Rect, TextureId, pos2}; +use photocraft_engine::pattern_cmds::PatternLibrary; +use photocraft_engine::presets::styles::StylePreset; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -26,7 +29,7 @@ use crate::PhotocraftApp; use crate::state::Tool; /// A row of a preset browser: a folder by name, or a preset by its key in the panel (a pattern id, a style name). -#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, MemoProps)] pub enum PresetKey { Group(String), Item(String), @@ -60,24 +63,56 @@ pub(crate) const TOOL_PRESETS: PresetPanel = PresetPanel { id: "toolPresets", label: "Tool Presets", prefix: "tool.presets", new_params: || json!({}), rename_new: true }; /// A folder of a panel: its name and its presets as (key, name). +#[derive(MemoProps)] pub(crate) struct Folder { pub(crate) name: String, pub(crate) items: Vec<(String, String)>, } -/// The browser's rows: the folders in `order` (library indices), each followed by its presets. -fn rows(folders: &[Folder], order: &[usize]) -> Vec> { +/// What a panel's presets are built from: its folders, their display order (library indices) and what its +/// thumbnails paint from. +#[derive(MemoProps)] +struct PanelInputs { + folders: Vec, + order: Vec, + thumbs: T, +} + +impl PanelInputs { + /// `panel`'s `folders` in the panel's folder order, with `thumbs`. + fn new(presets: &PresetUi, panel: PresetPanel, folders: Vec, thumbs: T) -> Self { + let order = presets.display_order(panel.id, &names_of(&folders)); + PanelInputs { folders, order, thumbs } + } +} + +/// The browser's rows: the folders in their order, each followed by its presets. +fn panel_rows(inputs: &PanelInputs, _: &Env) -> Vec> { let mut rows = Vec::new(); - for folder in order.iter().filter_map(|&at| folders.get(at)) { + for folder in inputs.order.iter().filter_map(|&at| inputs.folders.get(at)) { rows.push(PresetRow::group(PresetKey::Group(folder.name.clone()), folder.name.clone(), 0)); rows.extend(folder.items.iter().map(|(key, name)| PresetRow::item(PresetKey::Item(key.clone()), name.clone(), 1))); } rows } -/// The rows of `panel`'s `folders` in the panel's folder order. -fn panel_rows(presets: &PresetUi, panel: PresetPanel, folders: &[Folder]) -> Vec> { - rows(folders, &presets.display_order(panel.id, &names_of(folders))) +/// The source of a panel's presets over `inputs`, its thumbnails painted by `thumb`. +fn panel_source(inputs: PanelInputs, thumb: ThumbFn, PresetKey>) -> PresetSource<'static, PresetKey> { + PresetSource::new(inputs, PresetFns::new(panel_rows).thumb(thumb)) +} + +/// A thumbnail held in the framework's texture store: the preset's key and name, and the texture. +#[derive(Clone, MemoProps)] +pub(crate) struct Swatch { + key: String, + name: String, + #[memo_props(hash = "a texture handle: the texture store keeps one picture under it")] + texture: TextureId, +} + +/// The swatch of `key` among `swatches`. +fn swatch_of<'a>(swatches: &'a [Swatch], key: &str) -> Option<&'a Swatch> { + swatches.iter().find(|swatch| swatch.key == key) } /// The thumbnail sizes of every preset panel, as factors of the grid's large thumbnail (48 pt): 20 to 96 pt in 6 pt @@ -114,15 +149,14 @@ struct Look<'a> { flat: bool, } -/// Shows `panel`'s browser over `rows` with `thumb` painting a preset's thumbnail, and returns its events with the -/// keys of the rows it showed, in order. `presets` is the panel state, `zone` the canvas. +/// Shows `panel`'s browser over the presets of `source`, and returns its events with the keys of the rows it showed, +/// in order. `presets` is the panel state, `zone` the canvas. fn show( presets: &mut PresetUi, zone: DropZone, ui: &mut egui::Ui, panel: PresetPanel, - rows: Vec>, - thumb: &dyn Fn(&ContentPainterCx, Rect, &str), + source: &PresetSource<'_, PresetKey>, look: Look<'_>, ) -> (Vec>, Vec) { let selected = presets.selected.get(panel.id).cloned().map(PresetKey::Item); @@ -135,7 +169,7 @@ fn show( if let Some(leading) = look.leading { footer = footer.leading(leading); } - let mut browser = PresetBrowser::new(tl!(panel.label), Bind::bound(&mut state), &rows); + let mut browser = PresetBrowser::new(tl!(panel.label), Bind::bound(&mut state), source); if let Some(key) = selected.clone() { browser = browser.selected(key); } @@ -154,20 +188,10 @@ fn show( if !look.flat { browser = browser.reorder(PresetReorder::items_and_groups()); } - let out = browser - .browser_id(browser_id(panel)) - .default_open(DefaultOpen::First) - .thumb_range(THUMB_RANGE) - .drop_zone(zone) - .footer(footer) - .thumb(|cx, rect, info| { - if let PresetKey::Item(key) = info.key { - thumb(cx, rect, key); - } - }) - .show(ui); + let out = browser.browser_id(browser_id(panel)).default_open(DefaultOpen::First).thumb_range(THUMB_RANGE).drop_zone(zone).footer(footer).show(ui); presets.browsers.insert(panel.id.to_string(), state); - (out.events, rows.into_iter().map(|row| row.key).collect()) + let keys = if out.events.is_empty() { Vec::new() } else { source.rows(ui.ctx(), &Env::of(ui)).iter().map(|row| row.key.clone()).collect() }; + (out.events, keys) } pub(crate) fn browser_id(panel: PresetPanel) -> egui::Id { @@ -210,8 +234,23 @@ pub(crate) fn pattern_texture(ctx: &egui::Context, pattern: &photocraft_doc::Pat TextureCache::texture(ctx, ("pattern", pattern.id.clone()), || pattern_image(pattern)) } -fn paint_pattern(cx: &ContentPainterCx, rect: Rect, pattern: &photocraft_doc::Pattern) { - cx.picture(pattern_texture(cx.painter.ctx(), pattern), rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); +/// The swatch of `pattern`, keyed by its id and named by its display name. +fn pattern_swatch(ctx: &egui::Context, pattern: &photocraft_doc::Pattern) -> Swatch { + Swatch { key: pattern.id.clone(), name: pattern.display_name().to_string(), texture: pattern_texture(ctx, pattern) } +} + +/// Paints the whole of `texture` into `rect`. +fn paint_texture(cx: &ContentPainterCx, rect: Rect, texture: TextureId) { + cx.picture(texture, rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); +} + +/// A pattern panel thumbnail: the preset's swatch. +fn swatch_thumb(inputs: &PanelInputs>, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, PresetKey>) { + if let PresetKey::Item(key) = info.key + && let Some(swatch) = swatch_of(&inputs.thumbs, key) + { + paint_texture(cx, rect, swatch.texture); + } } // ------------------------------------------------------------------ Gradients @@ -227,22 +266,29 @@ fn paint_gradient(cx: &ContentPainterCx, rect: Rect, stops: &[(f32, [f32; 4])]) /// applies it. pub fn gradients_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let groups = app.session.presets.gradients.clone(); + let groups = &app.session.presets.gradients; // PLAN: the current-gradient strip above the browser needs a painter component; the browser's selected row shows it. let folders: Vec = groups .iter() .map(|group| Folder { name: group.name.clone(), items: group.items.iter().map(|preset| (preset.name.clone(), preset.name.clone())).collect() }) .collect(); - let rows = panel_rows(&app.ui.presets_ui, GRADIENTS, &folders); - let thumb = |cx: &ContentPainterCx, rect: Rect, name: &str| { - if let Some(preset) = groups.iter().flat_map(|group| &group.items).find(|preset| preset.name == name) { - paint_gradient(cx, rect, &preset.resolve(fg, bg)); - } - }; + let names = names_of(&folders); + let stops: Vec<(String, Vec<(f32, [f32; 4])>)> = + groups.iter().flat_map(|group| &group.items).map(|preset| (preset.name.clone(), preset.resolve(fg, bg))).collect(); + let source = panel_source(PanelInputs::new(&app.ui.presets_ui, GRADIENTS, folders, stops), gradient_thumb); let zone = canvas_zone(app); let look = Look { cell: Some(CellShape::ratio(32, 18)), ..Look::default() }; - let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, GRADIENTS, rows, &thumb, look); - apply(app, ui.ctx(), GRADIENTS, &names_of(&folders), &keys, events); + let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, GRADIENTS, &source, look); + apply(app, ui.ctx(), GRADIENTS, &names, &keys, events); +} + +/// A gradient panel thumbnail: the preset's stops, resolved against the current colours. +fn gradient_thumb(inputs: &PanelInputs)>>, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, PresetKey>) { + if let PresetKey::Item(name) = info.key + && let Some((_, stops)) = inputs.thumbs.iter().find(|(preset, _)| preset == name) + { + paint_gradient(cx, rect, stops); + } } // ------------------------------------------------------------------ Patterns @@ -255,7 +301,7 @@ pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { if app.services.preset_store.is_none() { photocraft_engine::presets::patterns::sync(&mut app.session); } - let library = app.session.patterns.items.clone(); + let library = &app.session.patterns.items; let folders: Vec = app .session .presets @@ -271,15 +317,17 @@ pub fn patterns_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { .collect(), }) .collect(); - let rows = panel_rows(&app.ui.presets_ui, PATTERNS, &folders); - let thumb = |cx: &ContentPainterCx, rect: Rect, id: &str| { - if let Some(pattern) = library.iter().find(|pattern| pattern.id == id) { - paint_pattern(cx, rect, pattern); - } - }; + let names = names_of(&folders); + let swatches: Vec = folders + .iter() + .flat_map(|folder| &folder.items) + .filter_map(|(id, _)| library.iter().find(|pattern| &pattern.id == id)) + .map(|pattern| pattern_swatch(ui.ctx(), pattern)) + .collect(); + let source = panel_source(PanelInputs::new(&app.ui.presets_ui, PATTERNS, folders, swatches), swatch_thumb); let zone = canvas_zone(app); - let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, PATTERNS, rows, &thumb, Look::default()); - apply(app, ui.ctx(), PATTERNS, &names_of(&folders), &keys, events); + let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, PATTERNS, &source, Look::default()); + apply(app, ui.ctx(), PATTERNS, &names, &keys, events); } // ------------------------------------------------------------------ Styles @@ -294,22 +342,53 @@ pub(crate) fn style_image(session: &photocraft_engine::Session, preset: &photocr ColorImage::from_rgba_unmultiplied([S as usize, S as usize], &px) } +/// What the style thumbnails draw from: every style and the patterns their effects use, as the app holds them when the +/// thumbnails' presets are built. +#[derive(PlainData)] +pub(crate) struct StyleLibrary { + #[plain_data(assume = "engine presets: owned values with no interior mutability")] + styles: Vec, + #[plain_data(assume = "the engine's pattern library: owned patterns with no interior mutability")] + patterns: PatternLibrary, +} + +impl StyleLibrary { + /// The app's styles and patterns now. + pub(crate) fn of(session: &photocraft_engine::Session) -> Tracked { + let styles = session.presets.styles.iter().flat_map(|group| group.items.iter().cloned()).collect(); + Tracked::new(StyleLibrary { styles, patterns: session.patterns.clone() }) + } + + /// Paints the thumbnail of the style `name`. A picture is rendered on a texture miss only, under one key for + /// every place that shows the style, so they share the textures. + pub(crate) fn paint(&self, cx: &ContentPainterCx, rect: Rect, name: &str) { + let Some(style) = self.styles.iter().find(|style| style.name == name) else { return }; + let key = ("style", style.name.clone(), style.effects.len(), format!("{:?}{:?}", style.blend, style.fill_opacity)); + picture(cx, rect, key, || { + let mut scratch = photocraft_engine::Session::new(); + scratch.patterns = self.patterns.clone(); + style_image(&scratch, style) + }); + } +} + +/// A Styles panel thumbnail. +fn style_thumb(inputs: &PanelInputs>, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, PresetKey>) { + if let PresetKey::Item(name) = info.key { + inputs.thumbs.paint(cx, rect, name); + } +} + /// Window › Styles: a click applies the style to the selected layers (Shift adds its effects), a drop on the canvas /// applies it to the active layer. pub fn styles_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { - let groups = app.session.presets.styles.clone(); let folders = style_folders(app); - let rows = panel_rows(&app.ui.presets_ui, STYLES, &folders); + let names = names_of(&folders); + let source = panel_source(PanelInputs::new(&app.ui.presets_ui, STYLES, folders, StyleLibrary::of(&app.session)), style_thumb); let zone = canvas_zone(app); - let session = &app.session; - let thumb = |cx: &ContentPainterCx, rect: Rect, name: &str| { - let Some(style) = groups.iter().flat_map(|group| &group.items).find(|style| style.name == name) else { return }; - let key = ("style", style.name.clone(), style.effects.len(), format!("{:?}{:?}", style.blend, style.fill_opacity)); - picture(cx, rect, key, || style_image(session, style)); - }; let look = Look { room_height: Some(STYLES_HEIGHT), ..Look::default() }; - let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, STYLES, rows, &thumb, look); - apply(app, ui.ctx(), STYLES, &names_of(&folders), &keys, events); + let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, STYLES, &source, look); + apply(app, ui.ctx(), STYLES, &names, &keys, events); } /// The Styles folders: each style group with its styles, keyed and named by the style's name. @@ -464,6 +543,20 @@ fn shape_texture(ctx: &egui::Context, shape: &photocraft_engine::presets::shapes TextureCache::texture(ctx, shape_key(shape), || shape_image(shape)) } +/// The swatch of `shape`, keyed and named by its name. +fn shape_swatch(ctx: &egui::Context, shape: &photocraft_engine::presets::shapes::ShapePreset) -> Swatch { + Swatch { key: shape.name.clone(), name: shape.name.clone(), texture: shape_texture(ctx, shape) } +} + +/// A Shapes panel thumbnail: the shape's raster, inset from the tile's edge. +fn shape_thumb(inputs: &PanelInputs>, cx: &ContentPainterCx, rect: Rect, info: ThumbInfo<'_, PresetKey>) { + if let PresetKey::Item(key) = info.key + && let Some(swatch) = swatch_of(&inputs.thumbs, key) + { + paint_texture(cx, rect.shrink(2.0), swatch.texture); + } +} + /// Window › Shapes: a click picks the shape for the Custom Shape tool, a double click places it, and a drop on the /// canvas places it where it lands. pub fn shapes_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -472,15 +565,12 @@ pub fn shapes_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { .iter() .map(|group| Folder { name: group.name.clone(), items: group.items.iter().map(|shape| (shape.name.clone(), shape.name.clone())).collect() }) .collect(); - let rows = panel_rows(&app.ui.presets_ui, SHAPES, &folders); - let thumb = |cx: &ContentPainterCx, rect: Rect, name: &str| { - if let Some(shape) = groups.iter().flat_map(|group| &group.items).find(|shape| shape.name == name) { - picture(cx, rect.shrink(2.0), shape_key(shape), || shape_image(shape)); - } - }; + let names = names_of(&folders); + let swatches: Vec = groups.iter().flat_map(|group| &group.items).map(|shape| shape_swatch(ui.ctx(), shape)).collect(); + let source = panel_source(PanelInputs::new(&app.ui.presets_ui, SHAPES, folders, swatches), shape_thumb); let zone = canvas_zone(app); - let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, SHAPES, rows, &thumb, Look::default()); - apply(app, ui.ctx(), SHAPES, &names_of(&folders), &keys, events); + let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, SHAPES, &source, Look::default()); + apply(app, ui.ctx(), SHAPES, &names, &keys, events); } fn shape_fill(app: &PhotocraftApp) -> Value { @@ -524,30 +614,40 @@ fn keep_picker_state(presets: &mut PresetUi, id: &str, state: PresetState> = Vec::new(); - for group in &groups { - rows.push(PresetRow::group(format!("{GROUP}{}", group.name), group.name.clone(), 0)); - for shape in &group.items { - let texture = shape_texture(&ctx, shape); - rows.push(PresetRow::item(shape.name.clone(), shape.name.clone(), 1).tooltip(shape.name.clone()).preview(ThumbAspect::SQUARE, move |cx, rect| { - cx.picture(texture, rect.shrink(2.0), Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); - })); - } - } + let groups: Vec<(String, Vec)> = photocraft_engine::presets::shapes::all_groups(&app.session) + .iter() + .map(|group| (group.name.clone(), group.items.iter().map(|shape| shape_swatch(ui.ctx(), shape)).collect())) + .collect(); + let source = PresetSource::new(groups, PresetFns::new(shape_rows)); let mut value = Some(app.ui.presets_ui.shape().to_string()); let before = value.clone(); let mut state = picker_state(&app.ui.presets_ui, ID); - let _ = PresetPicker::new(tl!("Shape"), Bind::bound(&mut value), &rows, Bind::bound(&mut state)).columns(7).show(ui); // the picked value comes back through `value` + let _ = PresetPicker::new(tl!("Shape"), Bind::bound(&mut value), &source, Bind::bound(&mut state)).columns(7).show(ui); // the picked value comes back through `value` keep_picker_state(&mut app.ui.presets_ui, ID, state); - if let Some(picked) = value.filter(|picked| before.as_ref() != Some(picked) && !picked.starts_with(GROUP)) { + if let Some(picked) = value.filter(|picked| before.as_ref() != Some(picked) && !picked.starts_with(SHAPE_GROUP)) { app.ui.presets_ui.custom_shape = picked; } } +/// The key prefix of a shape group's row in the shape picker. +const SHAPE_GROUP: &str = "group:"; + +/// The shape picker's rows: each group, then its shapes with their rasters, named in their tooltips. +fn shape_rows(groups: &Vec<(String, Vec)>, _: &Env) -> Vec> { + let mut rows = Vec::new(); + for (group, shapes) in groups { + rows.push(PresetRow::group(format!("{SHAPE_GROUP}{group}"), group.clone(), 0)); + for shape in shapes { + let texture = shape.texture; + rows.push(PresetRow::item(shape.key.clone(), shape.name.clone(), 1).tooltip(shape.name.clone()).preview(ThumbAspect::SQUARE, move |cx, rect| { + paint_texture(cx, rect.shrink(2.0), texture); + })); + } + } + rows +} + /// Custom Shape tool drag: places the selected shape in the dragged rect (⇧ keeps proportions). pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool, fill: Value, stroke: Value) { let name = app.ui.presets_ui.shape().to_string(); @@ -565,17 +665,15 @@ pub fn finish_custom_shape(app: &mut PhotocraftApp, rect: [f64; 4], keep: bool, pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { let only = app.ui.presets_ui.current_tool_only; let current = app.ui.tool; - let rows: Vec> = app + let presets: Vec<(String, String)> = app .session .presets .tool_presets .iter() .filter(|preset| !only || Tool::from_name(&preset.tool) == Some(current)) - .map(|preset| { - let icon = Tool::from_name(&preset.tool).map_or_else(|| craft::behavior::IconId::new("settings"), crate::icons::tool_icon); - PresetRow::item(PresetKey::Item(preset.name.clone()), preset.name.clone(), 0).icon(icon) - }) + .map(|preset| (preset.name.clone(), preset.tool.clone())) .collect(); + let source = PresetSource::new(presets, PresetFns::new(tool_preset_rows)); // The footer's closure is `Fn`, so the check box's value goes through a cell. let flag = std::cell::Cell::new(only); let leading = |ui: &mut egui::Ui| { @@ -591,11 +689,22 @@ pub fn tool_presets_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) { leading: Some(Box::new(leading)), ..Look::default() }; - let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, TOOL_PRESETS, rows, &|_, _, _| {}, look); + let (events, keys) = show(&mut app.ui.presets_ui, zone, ui, TOOL_PRESETS, &source, look); app.ui.presets_ui.current_tool_only = flag.get(); apply(app, ui.ctx(), TOOL_PRESETS, &[], &keys, events); } +/// The Tool Presets rows: each preset, as (name, tool name), with its tool's icon. +fn tool_preset_rows(presets: &Vec<(String, String)>, _: &Env) -> Vec> { + presets + .iter() + .map(|(name, tool)| { + let icon = Tool::from_name(tool).map_or_else(|| craft::behavior::IconId::new("settings"), crate::icons::tool_icon); + PresetRow::item(PresetKey::Item(name.clone()), name.clone(), 0).icon(icon) + }) + .collect() +} + // ------------------------------------------------------------------ events /// What an event does: an engine command, a change of the panel's folder order (app UI state, no command), or a @@ -746,19 +855,26 @@ fn after(app: &mut PhotocraftApp, ctx: &egui::Context, panel: PresetPanel, event // ------------------------------------------------------------------ pattern picker -/// The library's patterns as picker rows, each with its swatch and its name as the tooltip. The pattern picker and the -/// dialogs' pattern lists show these. -pub(crate) fn pattern_rows(app: &PhotocraftApp, ctx: &egui::Context) -> Vec> { - app.session - .patterns - .items +/// The library's patterns as swatches, in library order. The pattern picker and the dialogs' pattern lists show these +/// through [`pattern_source`]. +pub(crate) fn pattern_swatches(app: &PhotocraftApp, ctx: &egui::Context) -> Vec { + app.session.patterns.items.iter().map(|pattern| pattern_swatch(ctx, pattern)).collect() +} + +/// The presets of `swatches`: one row per pattern, keyed by its id, with its swatch and its name as the tooltip. +pub(crate) fn pattern_source(swatches: Vec) -> PresetSource<'static, String> { + PresetSource::new(swatches, PresetFns::new(swatch_rows)) +} + +/// The rows of [`pattern_source`]. +fn swatch_rows(swatches: &Vec, _: &Env) -> Vec> { + swatches .iter() - .map(|pattern| { - let texture = pattern_texture(ctx, pattern); - let name = pattern.display_name().to_string(); - PresetRow::item(pattern.id.clone(), name.clone(), 0).tooltip(name).preview(ThumbAspect::SQUARE, move |cx, rect| { - cx.picture(texture, rect, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), 0.0); - }) + .map(|swatch| { + let texture = swatch.texture; + PresetRow::item(swatch.key.clone(), swatch.name.clone(), 0) + .tooltip(swatch.name.clone()) + .preview(ThumbAspect::SQUARE, move |cx, rect| paint_texture(cx, rect, texture)) }) .collect() } @@ -767,11 +883,11 @@ pub(crate) fn pattern_rows(app: &PhotocraftApp, ctx: &egui::Context) -> Vec Option { const ID: &str = "patternPicker"; - let rows = pattern_rows(app, ui.ctx()); + let source = pattern_source(pattern_swatches(app, ui.ctx())); let mut value = Some(selected.to_string()).filter(|id| app.session.patterns.items.iter().any(|pattern| &pattern.id == id)); let before = value.clone(); let mut state = picker_state(&app.ui.presets_ui, ID); - let _ = PresetPicker::new(tl!("Patterns"), Bind::bound(&mut value), &rows, Bind::bound(&mut state)).show(ui); + let _ = PresetPicker::new(tl!("Patterns"), Bind::bound(&mut value), &source, Bind::bound(&mut state)).show(ui); keep_picker_state(&mut app.ui.presets_ui, ID, state); value.filter(|picked| before.as_ref() != Some(picked)) } diff --git a/crates/ui-egui/src/prefs/prefs_ui/presets.rs b/crates/ui-egui/src/prefs/prefs_ui/presets.rs index 91c82d0745..bd00ceecda 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/presets.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/presets.rs @@ -3,7 +3,7 @@ use craft::ui::contract::{Bind, Entry}; use craft::ui::dialog::DialogId; use craft::ui::patterns::form_dialogs::{DialogFields, FieldValue, HostedParamDialog, Param, ParamDialog, ParamKind, ParamResult}; -use craft::ui::patterns::presets::{HostedPresetManager, PresetEvent, PresetRow}; +use craft::ui::patterns::presets::{HostedPresetManager, PresetEvent}; use craft::ui::runtime::env::Label; use serde_json::{Value, json}; @@ -11,7 +11,7 @@ use crate::PhotocraftApp; use crate::dialogs::params::ParamFamily; /// The Preset Manager: the preset kind picked by its id, and the preset by its index in that kind's list. -type Manager = HostedPresetManager; +type Manager = HostedPresetManager; /// The command and dialog key of Export/Import Presets. const IO: &str = "edit.presets.exportImportPresets"; @@ -30,22 +30,20 @@ fn actions_for(kind: &str) -> Vec<(Label, Option