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

This commit is contained in:
aiongg committed 2026-11-21 14:07:15 +00:00
1 parent c9ebb9246d
commit 4bfb5c7567
11 files changed
+479 -221

No files matched your search

@@ -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<PhotocraftApp>>;
/// 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<egui::Id> {
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<egui::Id> =
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");
}
}
+2 -4
View File
@@ -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()))
})
}
+40 -29
View File
@@ -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<DialogId> {
.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<String, String> {
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<PresetRow<String>> {
/// 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<PresetRow<String>> {
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<String>)>,
library: Tracked<StyleLibrary>,
}
/// 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/<name>`.
fn style_rows(app: &PhotocraftApp) -> Vec<PresetRow<String>> {
fn style_rows(inputs: &StylePresets, _: &Env) -> Vec<PresetRow<String>> {
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<StylePreset> = 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();
@@ -60,23 +60,21 @@ pub(super) fn user_contours(app: &PhotocraftApp) -> Vec<Contour> {
/// 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<f32> + Send + Sync + 'static {
|points| {
let points: Vec<CurvePoint> = 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<f32> {
let points: Vec<CurvePoint> = 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 }));
}
+8 -11
View File
@@ -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<PatternSwatch> = 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<PatternSwatch> = 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
+2
View File
@@ -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)]
@@ -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<Arc<Vec<BrushPreset>>>, parts: BrushCardParts) -> PresetSource<'_, BrushKey> {
PresetSource::new((presets, parts), PresetFns::new(brush_rows))
}
/// The rows of [`brush_source`].
fn brush_rows(input: &(&Tracked<Arc<Vec<BrushPreset>>>, BrushCardParts), env: &Env) -> Vec<PresetRow<BrushKey>> {
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<PresetRow<BrushKey>> {
@@ -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));
}
}
+4 -4
View File
@@ -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<BrushKey>) -> Option<String> {
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::<BrushKey>::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)
+218 -102
View File
@@ -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<PresetRow<PresetKey>> {
/// 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<T> {
folders: Vec<Folder>,
order: Vec<usize>,
thumbs: T,
}
impl<T: MemoProps> PanelInputs<T> {
/// `panel`'s `folders` in the panel's folder order, with `thumbs`.
fn new(presets: &PresetUi, panel: PresetPanel, folders: Vec<Folder>, 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<T>(inputs: &PanelInputs<T>, _: &Env) -> Vec<PresetRow<PresetKey>> {
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<PresetRow<PresetKey>> {
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<T: MemoProps + Send + 'static>(inputs: PanelInputs<T>, thumb: ThumbFn<PanelInputs<T>, 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<PresetRow<PresetKey>>,
thumb: &dyn Fn(&ContentPainterCx, Rect, &str),
source: &PresetSource<'_, PresetKey>,
look: Look<'_>,
) -> (Vec<PresetEvent<PresetKey>>, Vec<PresetKey>) {
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<Vec<Swatch>>, 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<Folder> = 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<Vec<(String, Vec<(f32, [f32; 4])>)>>, 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<Folder> = 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<Swatch> = 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<StylePreset>,
#[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<Self> {
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<Tracked<StyleLibrary>>, 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<Vec<Swatch>>, 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<Swatch> = 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<String
/// Options-bar shape picker for the Custom Shape tool.
pub fn shape_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui) {
const GROUP: &str = "group:";
const ID: &str = "shapePicker";
let ctx = ui.ctx().clone();
let groups = photocraft_engine::presets::shapes::all_groups(&app.session);
let mut rows: Vec<PresetRow<String>> = 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<Swatch>)> = 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<Swatch>)>, _: &Env) -> Vec<PresetRow<String>> {
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<PresetRow<PresetKey>> = 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<PresetRow<PresetKey>> {
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<PresetRow<String>> {
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<Swatch> {
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<Swatch>) -> PresetSource<'static, String> {
PresetSource::new(swatches, PresetFns::new(swatch_rows))
}
/// The rows of [`pattern_source`].
fn swatch_rows(swatches: &Vec<Swatch>, _: &Env) -> Vec<PresetRow<String>> {
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<Pres
/// each named in its tooltip. Returns the id of a newly picked pattern.
pub(crate) fn pattern_picker(app: &mut PhotocraftApp, ui: &mut egui::Ui, selected: &str) -> Option<String> {
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))
}
+9 -11
View File
@@ -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<String, usize>;
type Manager = HostedPresetManager<String>;
/// 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<Label>)> {
if kind == "brushes" { vec![(tl!("Load…").into(), Some(tl!("Import brushes (.abr)").into()))] } else { Vec::new() }
}
/// The presets of `kind`, one row per name, keyed by index.
fn load_rows(app: &mut PhotocraftApp, kind: &str) -> Vec<PresetRow<usize>> {
let names = app
.session
/// The names of `kind`'s presets, in order (the manager keys each by its index).
fn load_names(app: &mut PhotocraftApp, kind: &str) -> Vec<String> {
app.session
.execute("edit.presets.presetManager", json!({"kind": kind}))
.ok()
.and_then(|v| v.get(kind).cloned())
.and_then(|v| serde_json::from_value::<Vec<String>>(v).ok())
.unwrap_or_default();
names.into_iter().enumerate().map(|(index, name)| PresetRow::item(index, name, 0)).collect()
.unwrap_or_default()
}
/// Opens the Preset Manager on Brushes.
pub(crate) fn open_manager(app: &mut PhotocraftApp) -> DialogId {
let mut manager = Manager::new(tl!("Preset Manager"), kinds(), "brushes".to_string());
manager.rows(load_rows(app, "brushes"));
manager.names(load_names(app, "brushes"));
manager.actions(actions_for("brushes"));
app.framework.dialogs.open(manager)
}
@@ -115,9 +113,9 @@ fn take_manager(app: &mut PhotocraftApp) {
if taken.actions.contains(&0) {
let _ = app.open_dialog_file();
}
let rows = load_rows(app, &kind);
let names = load_names(app, &kind);
if let Some(manager) = app.framework.dialogs.get_mut::<Manager>() {
manager.rows(rows);
manager.names(names);
if kind_changed {
manager.actions(actions_for(&kind));
}
+48 -38
View File
@@ -15,23 +15,24 @@ use craft::draw::ui::brush_settings::TipAngle;
use craft::ui::buttons::{Button, ToggleButton};
use craft::ui::choice::Checkbox;
use craft::ui::contract::{Bind, MemoProps, MemoView, Outbox, Props as _, SaveKey, Show as _, Tracked, bind_tracked};
use craft::ui::patterns::presets::PresetSource;
use craft::ui::runtime::env::Env;
use photocraft_engine::BrushSettings;
use photocraft_engine::paint::{BrushPreset, MAX_BRUSH_SIZE, TipShape};
use photocraft_engine::{BrushSettings, ToolState};
use serde_json::{Value, json};
use crate::PhotocraftApp;
use crate::brush_panel::brushes::{BrushKey, current_key, preset_rows, run_picks, tip_paint};
use crate::brush_panel::brushes::{BrushKey, brush_source, current_key, run_picks, tip_paint};
use crate::brush_panel::commit_keyed;
use crate::state::Tool;
/// Everything one pass of the picker reads from the app, built once so the canvas popup and the bar field show the same
/// thing.
pub(crate) struct PickerInput {
rows: Vec<craft::ui::patterns::presets::PresetRow<BrushKey>>,
pub(crate) struct PickerInput<'a> {
source: PresetSource<'a, BrushKey>,
current: Option<BrushKey>,
values: BrushPickerValues,
tip: TipShape,
tip: &'a TipShape,
face: BrushFace,
}
@@ -50,37 +51,45 @@ impl BrushFace {
}
}
impl PickerInput {
/// The rows, the current preset and the brush values as the app holds them now.
pub(crate) fn of(app: &PhotocraftApp, env: &Env) -> Self {
let tools = &app.session.tools;
Self::new(tools.presets.as_slice(), &tools.brush.tip, BrushFace::of(&tools.brush), current_key(tools), app.ui.brush_picker_state.parts, env)
impl<'a> PickerInput<'a> {
/// The presets with the card `parts`, the current preset and the brush values as `tools` hold them now.
pub(crate) fn of(tools: &'a ToolState, parts: BrushCardParts) -> Self {
Self::new(&tools.presets, &tools.brush.tip, BrushFace::of(&tools.brush), current_key(tools), parts)
}
/// The rows of `presets` with the card `parts`, `current` picked, and the brush's `tip` and `face`.
fn new(presets: &[BrushPreset], tip: &TipShape, face: BrushFace, current: Option<BrushKey>, parts: BrushCardParts, env: &Env) -> Self {
/// The presets of `presets` with the card `parts`, `current` picked, and the brush's `tip` and `face`.
fn new(presets: &'a Tracked<Arc<Vec<BrushPreset>>>, tip: &'a TipShape, face: BrushFace, current: Option<BrushKey>, parts: BrushCardParts) -> Self {
let round = *tip == TipShape::Round;
let values = BrushPickerValues::new(f64::from(face.size), round.then_some(f64::from(face.hardness)))
.with_tip(TipAngle::new(f64::from(face.angle), f64::from(face.roundness)));
Self { rows: preset_rows(presets, env, parts), current, values, tip: tip.clone(), face }
Self { source: brush_source(presets, parts), current, values, tip, face }
}
/// Every row's key, in list order.
fn keys(&self) -> Vec<BrushKey> {
self.rows.iter().map(|r| r.key.clone()).collect()
/// Every row's key, in list order, in the scope of `ui`.
fn keys(&self, ui: &egui::Ui) -> Vec<BrushKey> {
self.source.rows(ui.ctx(), &Env::of(ui)).iter().map(|r| r.key.clone()).collect()
}
/// The framework picker over this input and the picker's view `state`.
pub(crate) fn picker<'a>(&'a mut self, state: Bind<'a, BrushPickerState<BrushKey>>) -> BrushPresetPicker<'a, BrushKey> {
BrushPresetPicker::new(tl!("Brush Preset"), Bind::bound(&mut self.current), &self.rows, state, self.values)
pub(crate) fn picker<'p>(&'p mut self, state: Bind<'p, BrushPickerState<BrushKey>>) -> BrushPresetPicker<'p, BrushKey> {
BrushPresetPicker::new(tl!("Brush Preset"), Bind::bound(&mut self.current), &self.source, state, self.values)
.max_diameter(f64::from(MAX_BRUSH_SIZE))
.import()
.gear_rows(gear_rows)
.resizable(SaveKey::new("photocraft.brush_picker"))
.tip(std::sync::Arc::new(tip_paint(&self.tip, (self.face.hardness, self.face.angle, self.face.roundness))))
.tip(Arc::new(tip_paint(self.tip, (self.face.hardness, self.face.angle, self.face.roundness))))
}
}
/// The Background Eraser's own rows under the compact picker's head: the brush and the tolerance they edit, and the
/// brush as it was before the pass.
struct EraserRows {
before: BrushSettings,
brush: BrushSettings,
tolerance: String,
key: Option<String>,
}
/// Sends each event of a head edit as a `tools.setBrush`; the events of one gesture share the coalesce key, so the
/// gesture is one command.
fn commit_edits<T>(app: &mut PhotocraftApp, events: &EditEvents<T>, set: impl Fn(&mut BrushSettings, &T)) {
@@ -136,26 +145,28 @@ pub(crate) fn show_at(ui: &mut egui::Ui, app: &mut PhotocraftApp) {
close(app);
return;
}
let env = Env::of(ui);
let mut input = PickerInput::of(app, &env);
let mut open = true;
let background_eraser = app.ui.tool == Tool::BackgroundEraser;
let row_before = (*app.session.tools.brush).clone();
let mut row_brush = row_before.clone();
let mut tolerance = app.ui.tool_options.bg_tolerance_control.clone();
let mut key = None;
let out = {
let mut eraser = (app.ui.tool == Tool::BackgroundEraser).then(|| {
let brush = (*app.session.tools.brush).clone();
EraserRows { before: brush.clone(), brush, tolerance: app.ui.tool_options.bg_tolerance_control.clone(), key: None }
});
let (out, keys) = {
let mut input = PickerInput::of(&app.session.tools, app.ui.brush_picker_state.parts);
let picker = input.picker(bind_tracked!(app.ui.brush_picker_state)).open_at(egui::pos2(at[0], at[1]), Bind::bound(&mut open));
let picker =
if background_eraser { picker.compact(true).rows(|ui| key = crate::bg_eraser_popup::rows(ui, &mut row_brush, &mut tolerance)) } else { picker };
picker.show(ui)
let picker = match eraser.as_mut() {
Some(rows) => picker.compact(true).rows(|ui| rows.key = crate::bg_eraser_popup::rows(ui, &mut rows.brush, &mut rows.tolerance)),
None => picker,
};
let out = picker.show(ui);
let keys = if out.picks.is_empty() { Vec::new() } else { input.keys(ui) };
(out, keys)
};
let closed = !open || !out.open;
apply(app, ui.ctx(), &input.keys(), out);
if background_eraser {
commit_keyed(app, &row_before, &row_brush, key);
if app.ui.tool_options.bg_tolerance_control != tolerance {
app.ui.tool_options.bg_tolerance_control = tolerance;
apply(app, ui.ctx(), &keys, out);
if let Some(rows) = eraser {
commit_keyed(app, &rows.before, &rows.brush, rows.key);
if app.ui.tool_options.bg_tolerance_control != rows.tolerance {
app.ui.tool_options.bg_tolerance_control = rows.tolerance;
}
}
if closed {
@@ -202,10 +213,9 @@ pub(crate) fn show_field(ui: &mut egui::Ui, app: &mut PhotocraftApp, enabled: bo
/// The picker field's view.
fn field_view(props: &mut FieldProps<'_>, ui: &mut egui::Ui) {
let env = Env::of(ui);
let mut input = PickerInput::new(props.presets.as_slice(), props.tip, props.face, props.current.clone(), props.state.parts, &env);
let mut input = PickerInput::new(props.presets, props.tip, props.face, props.current.clone(), props.state.parts);
let out = input.picker(bind_tracked!(props.state)).enabled(props.enabled).show(ui);
let keys = if out.picks.is_empty() { Vec::new() } else { input.keys() };
let keys = if out.picks.is_empty() { Vec::new() } else { input.keys(ui) };
props.out.send(FieldEvent(out, keys));
}