PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Brushes: a New Brush Preset dialog for every way of making a preset (#4490) (#4563)
F4LCON8c135457b4ae
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rsindex e66e18b94..1fd186f93 100644--- a/crates/engine/src/brush_cmds.rs+++ b/crates/engine/src/brush_cmds.rs@@ -10,7 +10,7 @@ use photocraft_doc::LayerContent;use photocraft_geom::Rect;use photocraft_paint::mixer::{MixerSettings, apply_mixer_stroke};use photocraft_paint::replace::{Limits, ReplaceMode, ReplaceSettings, Sampling, apply_color_replacement, color_replacement_effect};-use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke};+use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, PresetCaptures, Stroke, StrokePoint, StrokeRenderer, TipShape, render_stroke};use photocraft_raster::Surface;use serde_json::{Value, json};@@ -177,7 +177,7 @@ fn find_preset<'a>(s: &'a Session, name: &str, cmd: &str) -> Result<&'a BrushPrepub fn resolve_brush(s: &Session, p: &Value, cmd: &str) -> Result<BrushSettings> {let mut b = s.tools.brush.clone();if let Some(name) = p.get("preset").and_then(Value::as_str) {- b = find_preset(s, name, cmd)?.brush.clone().picked_over(&s.tools.brush);+ b = find_preset(s, name, cmd)?.picked_over(&s.tools.brush);}if let Some(patch) = p.get("brush").filter(|v| v.is_object()) {b = merge_brush(&b, patch, cmd)?;@@ -761,11 +761,16 @@ fn upsert(s: &mut Session, preset: BrushPreset) {fn presets_save(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "brush.presets.save";let name = name_param(p, cmd)?;- let brush = match p.get("brush").filter(|v| v.is_object()) {+ let mut brush = match p.get("brush").filter(|v| v.is_object()) {Some(patch) => merge_brush(&s.tools.brush, patch, cmd)?,None => s.tools.brush.clone(),};- upsert(s, BrushPreset { name: name.clone(), brush, builtin: false, group: String::new(), folder: Vec::new() });+ // The New Brush Preset dialog's boxes; without them the preset captures what it always did.+ let captures = PresetCaptures { size: flag(p, "captureSize", true), tool_settings: flag(p, "toolSettings", true), color: flag(p, "color", false) };+ if captures.color {+ brush.color = s.tools.foreground;+ }+ upsert(s, BrushPreset { name: name.clone(), brush, builtin: false, group: String::new(), folder: Vec::new(), captures });// The saved brush is the current brush now (Photoshop selects the brush it just saved).s.tools.current_preset = Some(name.clone());Ok(json!({ "name": name, "count": s.tools.presets.len() }))@@ -881,7 +886,7 @@ fn define_from_selection(s: &mut Session, p: &Value) -> Result<Value> {}let tip = GrayTile::from_f32(tw, th, &data);let brush = BrushSettings { tip: TipShape::Sampled(tip), size: tw.max(th) as f32, spacing: 0.25, pressure_size: false, ..BrushSettings::default() };- upsert(s, BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, group: String::new(), folder: Vec::new() });+ upsert(s, BrushPreset { name: name.clone(), brush: brush.clone(), builtin: false, group: String::new(), folder: Vec::new(), captures: Default::default() });s.tools.brush = brush;s.tools.current_preset = Some(name.clone());Ok(json!({ "name": name, "width": tw, "height": th }))@@ -891,8 +896,11 @@ pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "tools.setBrush";let mut b = s.tools.brush.clone();let mut picked = None;+ let mut picked_color = None;if let Some(name) = p.get("preset").and_then(Value::as_str) {- b = find_preset(s, name, cmd)?.brush.clone().picked_over(&s.tools.brush);+ let preset = find_preset(s, name, cmd)?;+ b = preset.picked_over(&s.tools.brush);+ picked_color = preset.captures.color.then_some(preset.brush.color);picked = Some(name.to_string());}let reset = flag(p, "reset", false);@@ -921,6 +929,10 @@ pub(crate) fn set_brush(s: &mut Session, p: &Value) -> Result<Value> {s.tools.current_preset = None;} else if let Some(name) = picked {s.tools.current_preset = Some(name);+ // A preset saved with Include Color brings its colour as the foreground (Photoshop).+ if let Some(c) = picked_color {+ s.tools.foreground = c;+ }}// The tool's brush always paints with full tips: load a library preset's from the store.s.load_brush_tips(&mut b).map_err(|e| bad(cmd, e))?;@@ -1041,7 +1053,14 @@ pub fn specs() -> Vec<CommandSpec> {true),spec!("brush.presets.list", "List Brush Presets", r##"{"full":bool=false}"##, always, presets_list, false),- spec!("brush.presets.save", "Save Brush Preset", r##"{"name":string,"brush":{…BrushSettings}?=current brush}"##, always, presets_save, true),+ spec!(+ "brush.presets.save",+ "Save Brush Preset",+ r##"{"name":string,"brush":{…BrushSettings}?=current brush,"captureSize":bool=true (false: picking it keeps the tool's size),"toolSettings":bool=true (false: picking it keeps the tool's mode, opacity, flow and pressure buttons),"color":bool=false (picking it sets the foreground to the current foreground)}"##,+ always,+ presets_save,+ true+ ),spec!("brush.presets.update","Update Brush Preset",diff --git a/crates/engine/src/brush_cmds/tests.rs b/crates/engine/src/brush_cmds/tests.rsindex 8d718c13c..80b53fd90 100644--- a/crates/engine/src/brush_cmds/tests.rs+++ b/crates/engine/src/brush_cmds/tests.rs@@ -237,6 +237,45 @@ fn presets_save_load_delete_round_trip() {assert!(s.execute("brush.presets.save", json!({})).is_err());}+/// The New Brush Preset dialog's boxes (#4490): a preset saved without Capture Brush Size or+/// Include Tool Settings leaves the tool's size, mode, opacity, flow and pressure buttons as they+/// are when picked; one saved with Include Color brings its colour back as the foreground. A preset+/// saved without the boxes picks as it always did.+#[test]+fn presets_save_captures_size_tool_settings_and_color_as_asked() {+ let mut s = session(10, 10);+ s.execute("tools.setBrush", json!({"size": 40, "opacity": 0.5, "flow": 0.25, "mode": "Multiply", "pressureSize": false})).unwrap();+ s.tools.foreground = [1.0, 0.0, 0.0, 1.0];+ s.execute("brush.presets.save", json!({"name": "Legacy"})).unwrap();+ s.execute("brush.presets.save", json!({"name": "Bare", "captureSize": false, "toolSettings": false})).unwrap();+ s.execute("brush.presets.save", json!({"name": "Red", "color": true})).unwrap();+ let caps = |n: &str| s.tools.presets.iter().find(|p| p.name == n).unwrap().captures.clone();+ assert!(caps("Legacy").is_default(), "no boxes, the captures of any other preset");+ assert_eq!(caps("Bare"), PresetCaptures { size: false, tool_settings: false, color: false });+ assert!(caps("Red").color);++ // Change the tool, then pick each.+ let other = json!({"size": 9, "opacity": 1.0, "flow": 1.0, "mode": "Normal", "pressureSize": true});+ s.execute("tools.setBrush", other.clone()).unwrap();+ s.tools.foreground = [0.0, 0.0, 1.0, 1.0];+ s.execute("tools.setBrush", json!({"preset": "Legacy"})).unwrap();+ let b = &s.tools.brush;+ assert_eq!((b.size, b.opacity, b.flow, b.mode, b.pressure_size), (40.0, 0.5, 0.25, photocraft_color::BlendMode::Multiply, false), "everything it saved");+ assert_eq!(s.tools.foreground, [0.0, 0.0, 1.0, 1.0], "a preset without Include Color leaves the foreground");++ s.execute("tools.setBrush", other.clone()).unwrap();+ s.execute("tools.setBrush", json!({"preset": "Bare"})).unwrap();+ let b = &s.tools.brush;+ assert_eq!((b.size, b.opacity, b.flow, b.mode, b.pressure_size), (9.0, 1.0, 1.0, photocraft_color::BlendMode::Normal, true), "the tool's own");+ assert_eq!(s.tools.current_preset.as_deref(), Some("Bare"));++ s.execute("tools.setBrush", json!({"preset": "Red"})).unwrap();+ assert_eq!(s.tools.foreground, [1.0, 0.0, 0.0, 1.0], "Include Color sets the foreground");+ // A stroke naming the preset takes the same brush.+ let r = resolve_brush(&s, &json!({"preset": "Bare"}), "paint.brush").unwrap();+ assert_eq!(r.size, s.tools.brush.size);+}+#[test]fn presets_save_appends_at_the_end_and_update_overwrites_in_place() {let mut s = session(10, 10);diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rsindex 03b281433..49ee1b063 100644--- a/crates/engine/src/brush_preset_cmds.rs+++ b/crates/engine/src/brush_preset_cmds.rs@@ -486,7 +486,14 @@ mod tests {fn with_groups() -> Session {let mut s = Session::new();for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta"), ("B2", "Beta")] {- s.tools.presets.push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, group: g.into(), folder: Vec::new() });+ s.tools.presets.push(BrushPreset {+ name: n.into(),+ brush: Default::default(),+ builtin: false,+ group: g.into(),+ folder: Vec::new(),+ captures: Default::default(),+ });}s}@@ -591,7 +598,14 @@ mod tests {let mut s = Session::new();for (n, f) in [("S0", &[][..]), ("I1", &["Ink"][..]), ("F1", &["Ink", "Fine"][..]), ("I2", &["Ink"][..]), ("D1", &["Dry"][..])] {let folder = f.iter().map(|x| x.to_string()).collect();- s.tools.presets.push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, group: "Set".into(), folder });+ s.tools.presets.push(BrushPreset {+ name: n.into(),+ brush: Default::default(),+ builtin: false,+ group: "Set".into(),+ folder,+ captures: Default::default(),+ });}s}@@ -691,7 +705,14 @@ mod tests {let mut s = with_folders();for (n, f) in [("O1", &[][..]), ("B1", &["Box"][..])] {let folder = f.iter().map(|x| x.to_string()).collect();- s.tools.presets.push(BrushPreset { name: n.into(), brush: Default::default(), builtin: false, group: "Other".into(), folder });+ s.tools.presets.push(BrushPreset {+ name: n.into(),+ brush: Default::default(),+ builtin: false,+ group: "Other".into(),+ folder,+ captures: Default::default(),+ });}s}@@ -724,8 +745,22 @@ mod tests {let mut s = with_two_groups();// A chain 31 deep under Set/Deep.let deep: Vec<String> = std::iter::once("Deep".to_string()).chain((0..30).map(|i| format!("d{i}"))).collect();- s.tools.presets.push(BrushPreset { name: "Z".into(), brush: Default::default(), builtin: false, group: "Set".into(), folder: deep.clone() });- s.tools.presets.push(BrushPreset { name: "Y".into(), brush: Default::default(), builtin: false, group: "Other".into(), folder: vec!["Dry".into()] });+ s.tools.presets.push(BrushPreset {+ name: "Z".into(),+ brush: Default::default(),+ builtin: false,+ group: "Set".into(),+ folder: deep.clone(),+ captures: Default::default(),+ });+ s.tools.presets.push(BrushPreset {+ name: "Y".into(),+ brush: Default::default(),+ builtin: false,+ group: "Other".into(),+ folder: vec!["Dry".into()],+ captures: Default::default(),+ });let before = s.tools.presets.clone();let deep_json = json!(deep);for p in [@@ -758,7 +793,14 @@ mod tests {s.execute("brush.presets.moveGroup", json!({"group": "Set", "folder": ["Ink", "Fine"], "into": {"group": "Set"}})).unwrap();assert_eq!(folder_of(&s, "F1"), ["Fine"]);// An ungrouped preset's group can't move.- s.tools.presets.push(BrushPreset { name: "U".into(), brush: Default::default(), builtin: false, group: String::new(), folder: Vec::new() });+ s.tools.presets.push(BrushPreset {+ name: "U".into(),+ brush: Default::default(),+ builtin: false,+ group: String::new(),+ folder: Vec::new(),+ captures: Default::default(),+ });assert!(s.execute("brush.presets.moveGroup", json!({"group": "", "into": {"group": "Set"}})).is_err());}}diff --git a/crates/engine/src/preset_store.rs b/crates/engine/src/preset_store.rsindex 02138b637..4186c167e 100644--- a/crates/engine/src/preset_store.rs+++ b/crates/engine/src/preset_store.rs@@ -44,7 +44,7 @@ use std::io::Read;use std::sync::{Arc, Mutex, PoisonError};use photocraft_paint::tile::PREVIEW_SIDE;-use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Pattern, StoredTile, TipShape};+use photocraft_paint::{BrushPreset, BrushSettings, GrayTile, Pattern, PresetCaptures, StoredTile, TipShape};use serde::{Deserialize, Serialize};use crate::Session;@@ -333,6 +333,9 @@ struct StoredPreset {/// before #1851, which load with every preset directly in its group.#[serde(default, skip_serializing_if = "Vec::is_empty")]folder: Vec<String>,+ /// [`BrushPreset::captures`]; missing for presets saved without the New Brush Preset dialog.+ #[serde(default, skip_serializing_if = "PresetCaptures::is_default")]+ captures: PresetCaptures,}/// What a group file records about each tip it references, so loading needs only the preview.@@ -669,7 +672,14 @@ pub fn open(backend: Box<dyn PresetBackend>) -> Opened {hashes.push(i.preview.clone());}}- items.push(BrushPreset { name: sp.name, brush, builtin: false, group: g.group.clone(), folder: sanitize_folder(sp.folder) });+ items.push(BrushPreset {+ name: sp.name,+ brush,+ builtin: false,+ group: g.group.clone(),+ folder: sanitize_folder(sp.folder),+ captures: sp.captures,+ });}None => missing += 1,}@@ -1006,7 +1016,13 @@ impl PresetStore {}let key = |r: &Option<StoredTile>| r.as_ref().map(|t| t.key.clone());let tips = TipRefs { tip: key(&refs[0]), dual_tip: key(&refs[1]), texture: key(&refs[2]) };- stored.push(StoredPreset { name: p.name.clone(), brush: settings_only(&mut p.brush), tips, folder: p.folder.clone() });+ stored.push(StoredPreset {+ name: p.name.clone(),+ brush: settings_only(&mut p.brush),+ tips,+ folder: p.folder.clone(),+ captures: p.captures.clone(),+ });tiles.push(refs);}let gf = GroupFile { format: GROUP_FORMAT.into(), version: 1, group: group.to_string(), presets: stored, tips: infos };diff --git a/crates/engine/src/preset_store/tests.rs b/crates/engine/src/preset_store/tests.rsindex 513bc56c1..860ebd4fc 100644--- a/crates/engine/src/preset_store/tests.rs+++ b/crates/engine/src/preset_store/tests.rs@@ -45,7 +45,7 @@ fn tip16(w: u32, h: u32, seed: u32) -> GrayTile {fn sampled(name: &str, group: &str, tip: GrayTile) -> BrushPreset {let brush = BrushSettings { size: 42.0, spacing: 0.1, tip: TipShape::Sampled(tip), ..Default::default() };- BrushPreset { name: name.into(), brush, builtin: false, group: group.into(), folder: Vec::new() }+ BrushPreset { name: name.into(), brush, builtin: false, group: group.into(), folder: Vec::new(), captures: Default::default() }}fn user(s: &Session) -> Vec<BrushPreset> {@@ -168,6 +168,22 @@ fn commands_persist_and_delete_removes_from_disk() {assert!(photocraft_paint::presets::find(&t.tools.presets, "Doodle").is_none());}+/// The New Brush Preset dialog's boxes (#4490) are saved with the preset and come back with it;+/// a preset saved without them reloads with the default captures and writes no field for them.+#[test]+fn preset_captures_persist() {+ let dir = TempDir::new("captures");+ let (mut s, _) = session(&dir);+ s.execute("brush.presets.save", json!({"name": "Bare", "captureSize": false, "toolSettings": false, "color": true})).unwrap();+ s.execute("brush.presets.save", json!({"name": "Plain"})).unwrap();+ let (t, _) = session(&dir);+ let find = |n: &str| photocraft_paint::presets::find(&t.tools.presets, n).expect("reloads").captures.clone();+ assert_eq!(find("Bare"), PresetCaptures { size: false, tool_settings: false, color: true });+ assert!(find("Plain").is_default());+ let written: String = dir.files().iter().filter(|f| !f.starts_with("tips/")).map(|f| std::fs::read_to_string(dir.0.join(f)).unwrap_or_default()).collect();+ assert_eq!(written.matches("\"captures\"").count(), 1, "only the preset with boxes records them");+}+#[test]fn imported_abr_group_persists() {let dir = TempDir::new("abr");diff --git a/crates/io/src/abr_map.rs b/crates/io/src/abr_map.rsindex 9338d110a..e7fd290f0 100644--- a/crates/io/src/abr_map.rs+++ b/crates/io/src/abr_map.rs@@ -86,7 +86,7 @@ pub fn map_file_with(f: &AbrFile, group: &str, ctl: &photocraft_raster::Interrup}};let name = if b.name.trim().is_empty() { default_name } else { b.name.trim().to_string() };- out.presets.push(BrushPreset { name, brush, builtin: false, group: group.to_string(), folder: Vec::new() });+ out.presets.push(BrushPreset { name, brush, builtin: false, group: group.to_string(), folder: Vec::new(), captures: Default::default() });}} else if f.presets.is_empty() {// Tips without a settings section (early v6 files): one preset per tip.@@ -94,7 +94,14 @@ pub fn map_file_with(f: &AbrFile, group: &str, ctl: &photocraft_raster::Interrupstep(i)?;let (tip, size) = m.tip(s);let brush = BrushSettings { pressure_size: false, spacing: 0.25, size, tip, ..Default::default() };- out.presets.push(BrushPreset { name: format!("Sampled Brush {}", i + 1), brush, builtin: false, group: group.to_string(), folder: Vec::new() });+ out.presets.push(BrushPreset {+ name: format!("Sampled Brush {}", i + 1),+ brush,+ builtin: false,+ group: group.to_string(),+ folder: Vec::new(),+ captures: Default::default(),+ });}} else {for (i, d) in f.presets.iter().enumerate() {@@ -105,7 +112,7 @@ pub fn map_file_with(f: &AbrFile, group: &str, ctl: &photocraft_raster::Interrup// named after the imported file.Some(brush) => {let folder = f.folders.get(i).cloned().unwrap_or_default();- out.presets.push(BrushPreset { name, brush, builtin: false, group: group.to_string(), folder });+ out.presets.push(BrushPreset { name, brush, builtin: false, group: group.to_string(), folder, captures: Default::default() });}None => {m.warnings.insert(format!("\"{name}\": its sampled tip is missing from the file; skipped"));diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rsindex bdef893fd..0dd4d21d6 100644--- a/crates/paint/src/brush.rs+++ b/crates/paint/src/brush.rs@@ -674,4 +674,55 @@ pub struct BrushPreset {/// folders of Photoshop's Brushes panel; e.g. an imported `.abr` file's own folders.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub folder: Vec<String>,+ /// What picking the preset brings besides the tip and its sections: the New Brush Preset+ /// dialog's boxes.+ #[serde(default, skip_serializing_if = "PresetCaptures::is_default")]+ pub captures: PresetCaptures,+}++/// The New Brush Preset dialog's boxes, kept with the preset. The default is a preset made+/// without the dialog (a built-in, an import, an older save): picking it brings its size and tool+/// settings, as it always did, and leaves the foreground colour alone.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+#[serde(default, rename_all = "camelCase")]+pub struct PresetCaptures {+ /// Capture Brush Size in Preset. Off: picking the preset keeps the tool's size.+ pub size: bool,+ /// Include Tool Settings: the options bar's mode, opacity, flow and pressure buttons. Off:+ /// picking the preset keeps the tool's.+ pub tool_settings: bool,+ /// Include Color: picking the preset sets the foreground colour to the brush's `color`.+ pub color: bool,+}++impl Default for PresetCaptures {+ fn default() -> Self {+ Self { size: true, tool_settings: true, color: false }+ }+}++impl PresetCaptures {+ pub fn is_default(&self) -> bool {+ *self == Self::default()+ }+}++impl BrushPreset {+ /// The tool's brush once this preset is picked while `current` is the tool's brush: the+ /// preset's brush ([`BrushSettings::picked_over`]), with the size and tool settings it didn't+ /// capture left as they were.+ pub fn picked_over(&self, current: &BrushSettings) -> BrushSettings {+ let mut b = self.brush.clone().picked_over(current);+ if !self.captures.size {+ b.size = current.size;+ }+ if !self.captures.tool_settings {+ b.mode = current.mode;+ b.opacity = current.opacity;+ b.flow = current.flow;+ b.pressure_size = current.pressure_size;+ b.pressure_opacity = current.pressure_opacity;+ }+ b+ }}diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rsindex c5d065249..5d181b28e 100644--- a/crates/paint/src/lib.rs+++ b/crates/paint/src/lib.rs@@ -33,8 +33,8 @@ pub mod symmetry;pub mod tile;pub use brush::{- BrushPreset, BrushSettings, ColorDynamics, Control, DualBrush, Dynamic, MAX_BRUSH_SIZE, MAX_SCATTER, MaskMode, Pattern, PatternStyle, Pose, Scattering,- SectionLocks, ShapeDynamics, Smoothing, Texture, TipShape, Transfer,+ BrushPreset, BrushSettings, ColorDynamics, Control, DualBrush, Dynamic, MAX_BRUSH_SIZE, MAX_SCATTER, MaskMode, Pattern, PatternStyle, Pose, PresetCaptures,+ Scattering, SectionLocks, ShapeDynamics, Smoothing, Texture, TipShape, Transfer,};pub use mixer::MixerSettings;pub use render::{BrushContext, StrokeRenderer, UnionLive, grid_center, grid_square, render_stroke};diff --git a/crates/paint/src/presets.rs b/crates/paint/src/presets.rsindex cbba537e1..f711d0eb5 100644--- a/crates/paint/src/presets.rs+++ b/crates/paint/src/presets.rs@@ -11,7 +11,7 @@ use crate::procedural::{bristle_tip, chalk_tip, charcoal_tip, grass_tip, leaf_tipub const GROUPS: [&str; 4] = ["General", "Dry Media", "Wet Media", "Special Effects"];fn preset(group: &str, name: &str, brush: BrushSettings) -> BrushPreset {- BrushPreset { name: name.to_string(), brush, builtin: true, group: group.to_string(), folder: Vec::new() }+ BrushPreset { name: name.to_string(), brush, builtin: true, group: group.to_string(), folder: Vec::new(), captures: Default::default() }}fn pressure() -> Dynamic {diff --git a/crates/ui-egui/src/brush_panel.rs b/crates/ui-egui/src/brush_panel.rsindex 6ea83d10e..e388b60f5 100644--- a/crates/ui-egui/src/brush_panel.rs+++ b/crates/ui-egui/src/brush_panel.rs@@ -388,9 +388,9 @@ fn settings_tab(app: &mut PhotocraftApp, ui: &mut egui::Ui) {let tex = brush_preview::stroke_texture(ui.ctx(), "settings-strip", &b, STRIP.0, STRIP.1, t.text);ui.painter().image(tex.id(), r, full_uv(), Color32::WHITE);ui.vertical(|ui| {- if icons::button(ui, "square-plus", 24.0, false, tl!("Create new brush from these settings")).clicked() {- let name = new_preset_name(&app.session.tools.presets);- run_or_status(app, "brush.presets.save", json!({ "name": name, "brush": serde_json::to_value(&b).unwrap_or(Value::Null) }));+ let new = icons::button(ui, "square-plus", 24.0, false, tl!("Create new brush from these settings"));+ if crate::brush_picker::named(new, "Create new brush from these settings").clicked() {+ crate::brush_preset_dialog::open(app, Some(&b));}if icons::button(ui, "undo-2", 24.0, false, tl!("Reset the brush to the defaults")).clicked() {b = BrushSettings { color: b.color, background: b.background, smoothing: b.smoothing.clone(), locks: b.locks.clone(), ..Default::default() };diff --git a/crates/ui-egui/src/brush_panel_tests.rs b/crates/ui-egui/src/brush_panel_tests.rsindex 2e48b2abb..7723bede1 100644--- a/crates/ui-egui/src/brush_panel_tests.rs+++ b/crates/ui-egui/src/brush_panel_tests.rs@@ -458,7 +458,14 @@ fn drop_targets_and_actions_reorder_presets() {use crate::brushes_tab::{Action, apply, drop_target, group_key};let mut app = app();for (n, g) in [("A1", "Alpha"), ("A2", "Alpha"), ("A3", "Alpha"), ("B1", "Beta")] {- app.session.tools.presets.push(paint::BrushPreset { name: n.into(), brush: Default::default(), builtin: false, group: g.into(), folder: Vec::new() });+ app.session.tools.presets.push(paint::BrushPreset {+ name: n.into(),+ brush: Default::default(),+ builtin: false,+ group: g.into(),+ folder: Vec::new(),+ captures: Default::default(),+ });}let p = &app.session.tools.presets;// Dropping A1 on A3's lower half lands after A3 (index 2 once A1 is out); on its upper half, before it.@@ -752,6 +759,7 @@ fn kit(name: &str, folder: &[&str]) -> paint::BrushPreset {builtin: false,group: "Kit".into(),folder: folder.iter().map(|s| s.to_string()).collect(),+ captures: Default::default(),}}diff --git a/crates/ui-egui/src/brush_picker.rs b/crates/ui-egui/src/brush_picker.rsindex 3cade4981..8ac5bb8c2 100644--- a/crates/ui-egui/src/brush_picker.rs+++ b/crates/ui-egui/src/brush_picker.rs@@ -24,7 +24,7 @@ use photocraft_engine::BrushSettings;use photocraft_engine::paint::{BrushPreset, MAX_BRUSH_SIZE, TipShape};use serde_json::{Value, json};-use crate::brush_panel::{BrushesPanelState, Renaming, new_preset_name, run_or_status};+use crate::brush_panel::{BrushesPanelState, Renaming};use crate::brushes_tab::{self, Action, ListLayout};use crate::theme::Tokens;use crate::{PhotocraftApp, icons, widgets};@@ -159,13 +159,11 @@ pub fn apply(app: &mut PhotocraftApp, ctx: &egui::Context, picks: Vec<Pick>) {match pick {Pick::List(a) => brushes_tab::apply(app, vec![a]),Pick::OpenSettings => open_settings(app, ctx),+ // Photoshop asks for the new preset's name and what it captures first, in a dialog that+ // takes the picker's place.Pick::NewPreset => {- let name = new_preset_name(&app.session.tools.presets);- run_or_status(app, "brush.presets.save", json!({ "name": name }));- // Photoshop asks for the new preset's name: the picker's rename bar does.- if app.session.tools.presets.iter().any(|p| p.name == name) {- app.ui.brush_picker_list.renaming = Some(Renaming { group: false, name, folder: Vec::new(), text: String::new() });- }+ close(&mut app.ui);+ crate::brush_preset_dialog::open(app, None);}Pick::Import => {let _ = app.open_dialog_file();diff --git a/crates/ui-egui/src/brush_preset_dialog.rs b/crates/ui-egui/src/brush_preset_dialog.rsnew file mode 100644index 000000000..129b9adf2--- /dev/null+++ b/crates/ui-egui/src/brush_preset_dialog.rs@@ -0,0 +1,165 @@+//! The New Brush Preset dialog (#4490), as in Photoshop: the brush's tip and size on the left, the+//! name and what the preset captures in the middle, OK and Cancel on the right. Every way of making+//! a preset opens it: the picker's [+] and its gear menu, the Brush Settings [+] and the Brushes+//! tab's [+]. Nothing is saved until OK.+use egui::{Color32, pos2, vec2};+use photocraft_paint::{BrushPreset, BrushSettings};+use serde_json::{Map, Value, json};++use crate::{PhotocraftApp, state::DialogKind, theme::Tokens, widgets};++const MARK: &str = "__newBrushPreset";+const PREVIEW: f32 = 96.0;++pub fn owns(fields: &Map<String, Value>) -> bool {+ fields.contains_key(MARK)+}++/// The name the dialog suggests: the current preset's name and the first free number after it+/// ("Soft Round 1"), so OK never overwrites a preset; "Brush N" when the brush isn't a preset's.+pub fn suggested_name(presets: &[BrushPreset], current: Option<&str>) -> String {+ match current.filter(|n| presets.iter().any(|p| p.name.eq_ignore_ascii_case(n))) {+ Some(base) => (1..).map(|n| format!("{base} {n}")).find(|n| !taken(presets, n)).unwrap_or_else(|| base.to_string()),+ None => crate::brush_panel::new_preset_name(presets),+ }+}++fn taken(presets: &[BrushPreset], name: &str) -> bool {+ presets.iter().any(|p| p.name.eq_ignore_ascii_case(name.trim()))+}++/// Open the dialog for the tool's brush, or for `brush` (the Brush Settings panel's copy, which+/// may be ahead of the tool's by a frame). Returns the dialog's id.+pub fn open(app: &mut PhotocraftApp, brush: Option<&BrushSettings>) -> u64 {+ let tools = &app.session.tools;+ let mut fields = Map::new();+ fields.insert(MARK.into(), json!(true));+ fields.insert("__label".into(), json!("New Brush Preset…"));+ fields.insert("name".into(), json!(suggested_name(&tools.presets, tools.current_preset.as_deref())));+ fields.insert("captureSize".into(), json!(true));+ fields.insert("toolSettings".into(), json!(false));+ fields.insert("color".into(), json!(false));+ if let Some(b) = brush.and_then(|b| serde_json::to_value(b).ok()) {+ fields.insert("brush".into(), b);+ }+ app.ui.open_dialog(DialogKind::Command, fields)+}++fn on(f: &Map<String, Value>, key: &str) -> bool {+ f.get(key).and_then(Value::as_bool).unwrap_or(false)+}++fn name(f: &Map<String, Value>) -> &str {+ f.get("name").and_then(Value::as_str).unwrap_or("").trim()+}++/// Why OK is greyed out, if it is.+fn problem(app: &PhotocraftApp, f: &Map<String, Value>) -> Option<&'static str> {+ if name(f).is_empty() {+ Some(tl!("Enter a name for the brush preset"))+ } else if taken(&app.session.tools.presets, name(f)) {+ Some(tl!("A brush preset with this name already exists"))+ } else {+ None+ }+}++fn check(ui: &mut egui::Ui, f: &mut Map<String, Value>, key: &str, label: &str) {+ let mut v = on(f, key);+ if widgets::checkbox(ui, &mut v, label).changed() {+ f.insert(key.into(), json!(v));+ }+}++/// The dialog's three columns; it owns its OK and Cancel, so they stand in their own column.+pub fn body(app: &PhotocraftApp, ui: &mut egui::Ui, f: &mut Map<String, Value>, interactive: bool) -> Option<bool> {+ let t = Tokens::get(ui.ctx());+ let mut outcome = None;+ let brush: BrushSettings = f.get("brush").and_then(|b| serde_json::from_value(b.clone()).ok()).unwrap_or_else(|| app.session.tools.brush.clone());+ ui.horizontal_top(|ui| {+ // The tip as the preset cards draw it, and the size under it.+ let (r, _) = ui.allocate_exact_size(vec2(PREVIEW, PREVIEW), egui::Sense::hover());+ ui.painter().rect_filled(r, t.radius_sm, t.field);+ let tip = crate::brush_preview::tip_texture(ui.ctx(), "new-preset-tip", &brush.tip, (brush.hardness, brush.angle, brush.roundness), 64, t.text);+ let side = (PREVIEW - 30.0) * crate::brush_sections::thumb_scale(brush.size);+ let tr = egui::Rect::from_center_size(pos2(r.center().x, r.top() + 8.0 + (PREVIEW - 30.0) / 2.0), vec2(side, side));+ ui.painter().image(tip.id(), tr, egui::Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);+ ui.painter().text(+ pos2(r.center().x, r.bottom() - 5.0),+ egui::Align2::CENTER_BOTTOM,+ format!("{}", brush.size.round() as i64),+ egui::FontId::proportional(11.0),+ t.text_dim,+ );+ ui.add_space(14.0);+ ui.vertical(|ui| {+ ui.horizontal(|ui| {+ ui.label(tl!("Name:"));+ let mut text = f.get("name").and_then(Value::as_str).unwrap_or("").to_string();+ let id = ui.id().with("new-brush-preset-name");+ let r = widgets::text_field(ui, id, &mut text, "", 220.0, false);+ // Photoshop opens on the name, all of it selected, so typing replaces it.+ let once = id.with("focused");+ if !ui.ctx().data(|d| d.get_temp::<bool>(once).unwrap_or(false)) {+ r.request_focus();+ if egui::TextEdit::load_state(ui.ctx(), id).is_some() {+ crate::field_tab::select_all(ui.ctx(), id, &text);+ ui.ctx().data_mut(|d| d.insert_temp(once, true));+ }+ }+ if r.changed() {+ f.insert("name".into(), json!(text));+ }+ });+ ui.add_space(6.0);+ check(ui, f, "captureSize", tl!("Capture Brush Size in Preset"));+ check(ui, f, "toolSettings", tl!("Include Tool Settings"));+ // Include Color belongs to the tool settings: only with them, as in Photoshop.+ ui.horizontal(|ui| {+ ui.add_space(20.0);+ ui.add_enabled_ui(on(f, "toolSettings"), |ui| check(ui, f, "color", tl!("Include Color")));+ });+ if let Some(why) = problem(app, f).filter(|_| !name(f).is_empty()) {+ ui.add_space(4.0);+ ui.colored_label(t.text_dim, why);+ }+ });+ ui.add_space(14.0);+ ui.vertical(|ui| {+ let ok = problem(app, f).is_none();+ if ui.add_enabled_ui(ok, |ui| widgets::primary_button(ui, tl!("OK"), 84.0)).inner.clicked() {+ outcome = Some(true);+ }+ ui.add_space(4.0);+ if widgets::secondary_button(ui, tl!("Cancel"), 84.0).clicked() {+ outcome = Some(false);+ }+ });+ });+ if outcome.is_none() && interactive && problem(app, f).is_none() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {+ outcome = Some(true);+ }+ outcome+}++/// OK: save the preset with the boxes as chosen. It becomes the current brush, as in Photoshop.+pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value, String> {+ if let Some(why) = problem(app, f) {+ return Err(why.into());+ }+ let tool_settings = on(f, "toolSettings");+ let mut p = json!({+ "name": name(f),+ "captureSize": on(f, "captureSize"),+ "toolSettings": tool_settings,+ "color": tool_settings && on(f, "color"),+ });+ if let Some(b) = f.get("brush") {+ p["brush"] = b.clone();+ }+ app.run("brush.presets.save", p)+}++#[cfg(test)]+#[path = "brush_preset_dialog_tests.rs"]+mod tests;diff --git a/crates/ui-egui/src/brush_preset_dialog_tests.rs b/crates/ui-egui/src/brush_preset_dialog_tests.rsnew file mode 100644index 000000000..3e13ebc38--- /dev/null+++ b/crates/ui-egui/src/brush_preset_dialog_tests.rs@@ -0,0 +1,138 @@+use egui::vec2;+use egui_kittest::Harness;+use egui_kittest::kittest::{NodeT, Queryable};++use super::*;++fn harness() -> Harness<'static, PhotocraftApp> {+ let mut h = Harness::builder().with_size(vec2(1440.0, 900.0)).with_max_steps(64).build_eframe(|cc| {+ PhotocraftApp::setup_context(&cc.egui_ctx, Default::default());+ PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default())+ });+ h.state_mut().run("file.new", json!({"width": 400, "height": 300})).unwrap();+ h.state_mut().ui.tool = crate::state::Tool::Brush;+ h.run_steps(4);+ h+}++/// The open New Brush Preset dialog, if there is one (and never two).+fn dialog(h: &Harness<'_, PhotocraftApp>) -> Option<u64> {+ let open: Vec<u64> = h.state().ui.dialogs.iter().filter(|d| owns(&d.fields)).map(|d| d.id).collect();+ assert!(open.len() <= 1, "one dialog at a time: {open:?}");+ open.first().copied()+}++fn field<'a>(h: &'a Harness<'_, PhotocraftApp>, id: u64, key: &str) -> &'a Value {+ &h.state().ui.dialogs.iter().find(|d| d.id == id).unwrap().fields[key]+}++/// Every way of making a preset opens the dialog, and Cancel saves nothing.+#[test]+fn every_new_preset_button_opens_the_dialog_and_cancel_saves_nothing() {+ let mut h = harness();+ let before = h.state().session.tools.presets.clone();+ let brush = h.state().session.tools.brush.clone();+ let mut opened = 0;+ let mut cancel = |h: &mut Harness<'_, PhotocraftApp>| {+ dialog(h).expect("the dialog opened");+ h.run_steps(2);+ h.get_by_label("Cancel").click();+ h.run_steps(3);+ assert!(dialog(h).is_none(), "Cancel closes it");+ assert_eq!(h.state().session.tools.presets, before, "and saves nothing");+ assert_eq!(h.state().session.tools.brush, brush, "nor touches the brush");+ opened += 1;+ };+ // The picker's [+] and its gear menu.+ h.state_mut().ui.brush_picker = Some([300.0, 120.0]);+ h.run_steps(3);+ h.get_by_label("New Brush Preset").click();+ h.run_steps(3);+ cancel(&mut h);+ h.state_mut().ui.brush_picker = Some([300.0, 120.0]);+ h.run_steps(3);+ h.get_by_label("Brush Preset Options").click();+ h.run_steps(2);+ h.get_by_label("New Brush Preset…").click();+ h.run_steps(3);+ cancel(&mut h);+ // Brush Settings' [+], then the Brushes tab's.+ h.state_mut().ui.brush_picker = None;+ h.state_mut().ui.panels.brush_settings = true;+ h.state_mut().ui.brush_tab = 0;+ h.run_steps(3);+ h.get_by_label("Create new brush from these settings").click();+ h.run_steps(3);+ cancel(&mut h);+ h.state_mut().ui.brush_tab = 1;+ h.run_steps(3);+ h.get_by_label("Create new brush from the current settings").click();+ h.run_steps(3);+ cancel(&mut h);+ assert_eq!(opened, 4);+}++/// The dialog suggests the current brush's name and the next free number, never a name in use; OK+/// saves under the typed name with the boxes as set, and the next one suggests the next number.+#[test]+fn ok_saves_under_the_name_with_the_boxes_as_set() {+ let mut h = harness();+ h.state_mut().run("tools.setBrush", json!({"preset": "Chalk"})).unwrap();+ let id = open(h.state_mut(), None);+ h.run_steps(3);+ assert_eq!(field(&h, id, "name"), "Chalk 1");+ assert_eq!((field(&h, id, "captureSize"), field(&h, id, "toolSettings"), field(&h, id, "color")), (&json!(true), &json!(false), &json!(false)));+ // Include Color waits for Include Tool Settings.+ assert!(h.get_by_label("Include Color").accesskit_node().is_disabled(), "Include Color is greyed out");+ h.get_by_label("Include Tool Settings").click();+ h.run_steps(2);+ assert!(!h.get_by_label("Include Color").accesskit_node().is_disabled());+ h.get_by_label("Include Color").click();+ h.get_by_label("Capture Brush Size in Preset").click();+ h.run_steps(2);+ h.get_by_label("OK").click();+ h.run_steps(3);+ assert!(dialog(&h).is_none());+ let p = h.state().session.tools.presets.iter().find(|p| p.name == "Chalk 1").expect("saved");+ assert_eq!(p.captures, photocraft_paint::PresetCaptures { size: false, tool_settings: true, color: true });+ assert!(h.state().session.tools.presets.iter().any(|p| p.name == "Chalk"), "the preset it came from is still there");+ assert_eq!(h.state().session.tools.current_preset.as_deref(), Some("Chalk 1"));++ // Again: the next number, and a name in use greys OK out.+ let id = open(h.state_mut(), None);+ h.run_steps(3);+ assert_eq!(field(&h, id, "name"), "Chalk 1 1", "named after the current brush, now Chalk 1");+ h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("name".into(), json!("chalk"));+ h.run_steps(2);+ assert!(h.get_by_label("OK").accesskit_node().is_disabled(), "Chalk exists");+ assert!(h.query_by_label("A brush preset with this name already exists").is_some());+ assert!(crate::dialogs::confirm(h.state_mut(), id).is_err(), "automation can't overwrite it either");+}++/// Include Color unchecked with it ticked earlier: the preset doesn't take the colour.+#[test]+fn include_color_needs_include_tool_settings() {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ let id = open(&mut app, None);+ let f = &mut app.ui.dialog_mut(id).unwrap().fields;+ f.insert("name".into(), json!("Mine"));+ f.insert("color".into(), json!(true));+ crate::dialogs::confirm(&mut app, id).unwrap();+ let p = app.session.tools.presets.iter().find(|p| p.name == "Mine").unwrap();+ assert_eq!(p.captures, photocraft_paint::PresetCaptures { size: true, tool_settings: false, color: false });+}++/// The dialog opens on the name, all of it selected: typing replaces it, and Enter is OK.+#[test]+fn typing_replaces_the_suggested_name_and_enter_is_ok() {+ let mut h = harness();+ let id = open(h.state_mut(), None);+ h.run_steps(4);+ h.event(egui::Event::Text("Inky".into()));+ h.run_steps(2);+ assert_eq!(field(&h, id, "name"), "Inky");+ h.key_press(egui::Key::Enter);+ h.run_steps(3);+ assert!(dialog(&h).is_none(), "Enter is OK");+ assert_eq!(h.state().session.tools.current_preset.as_deref(), Some("Inky"));+}diff --git a/crates/ui-egui/src/brushes_tab.rs b/crates/ui-egui/src/brushes_tab.rsindex 31c1161b9..7a8d56b3d 100644--- a/crates/ui-egui/src/brushes_tab.rs+++ b/crates/ui-egui/src/brushes_tab.rs@@ -17,9 +17,7 @@ use egui::{Color32, RichText, Sense, Stroke, pos2, vec2};use photocraft_engine::paint::{BrushPreset, MAX_BRUSH_SIZE};use serde_json::json;-use crate::brush_panel::{- BrushesPanelState, BrushesView, Renaming, UNGROUPED, WIDTH, commit_gesture, full_uv, grouped_presets, new_preset_name, run_or_status,-};+use crate::brush_panel::{BrushesPanelState, BrushesView, Renaming, UNGROUPED, WIDTH, commit_gesture, full_uv, grouped_presets, run_or_status};use crate::brush_preview;use crate::theme::{self, Tokens};use crate::{PhotocraftApp, icons, widgets};@@ -975,9 +973,9 @@ pub fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui) {{run_or_status(app, "brush.presets.delete", json!({ "name": name }));}- if icons::button(ui, "square-plus", 24.0, false, "Create new brush from the current settings").clicked() {- let name = new_preset_name(&app.session.tools.presets);- run_or_status(app, "brush.presets.save", json!({ "name": name }));+ let new = icons::button(ui, "square-plus", 24.0, false, "Create new brush from the current settings");+ if crate::brush_picker::named(new, "Create new brush from the current settings").clicked() {+ crate::brush_preset_dialog::open(app, None);}if icons::button(ui, "folder-open", 24.0, false, "Import Brushes… (.abr)").clicked() {let _ = app.open_dialog_file();diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rsindex bb39e6d02..fce28f9e4 100644--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@ -263,6 +263,9 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {about_tab_body(app, ui, chosen);}DialogKind::Command if crate::guide_layout_ui::owns(&fields) => outcome = crate::guide_layout_ui::body(app, ui, &mut fields, interactive),+ DialogKind::Command if crate::brush_preset_dialog::owns(&fields) => {+ outcome = crate::brush_preset_dialog::body(app, ui, &mut fields, interactive)+ }DialogKind::Command if crate::fill_ui::owns(&fields) => crate::fill_ui::body(app, ui, &mut fields),DialogKind::Command if crate::pattern_fill_ui::owns(&fields) => crate::pattern_fill_ui::body(app, ui, &mut fields),DialogKind::Command if crate::stroke_ui::owns(&fields) => crate::stroke_ui::body(ui, &mut fields),@@ -319,8 +322,8 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) {}}crate::field_tab::end(ui.ctx(), tab);- if crate::guide_layout_ui::owns(&fields) {- // This dialog owns its right-side actions and validates Enter itself.+ if crate::guide_layout_ui::owns(&fields) || crate::brush_preset_dialog::owns(&fields) {+ // These dialogs own their right-side actions and validate Enter themselves.} else if crate::color_picker_ui::owns(&fields) {if interactive && outcome.is_none() && ui.input(|i| i.key_pressed(egui::Key::Enter)) {outcome = Some(true);@@ -543,6 +546,7 @@ pub fn confirm(app: &mut PhotocraftApp, id: u64) -> Result<Value, String> {r}DialogKind::Command if crate::guide_layout_ui::owns(&d.fields) => crate::guide_layout_ui::confirm(app, &d.fields),+ DialogKind::Command if crate::brush_preset_dialog::owns(&d.fields) => crate::brush_preset_dialog::confirm(app, &d.fields),DialogKind::Command if crate::fill_ui::owns(&d.fields) => crate::fill_ui::confirm(app, &d.fields),DialogKind::Command if crate::pattern_fill_ui::owns(&d.fields) => crate::pattern_fill_ui::confirm(app, &d.fields),DialogKind::Command if crate::stroke_ui::owns(&d.fields) => crate::stroke_ui::confirm(app, &d.fields),diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsvindex 178f3d183..17630d87b 100644--- a/crates/ui-egui/src/i18n/cs.tsv+++ b/crates/ui-egui/src/i18n/cs.tsv@@ -2126,6 +2126,11 @@Rename Brush… Přejmenovat štětec…Delete Brush Odstranit štětecNew Brush Preset… Nová předvolba štětce…+ Capture Brush Size in Preset Zachytit velikost štětce v předvolbě+ Include Tool Settings Zahrnout nastavení nástroje+ Include Color Zahrnout barvu+ Enter a name for the brush preset Zadejte název předvolby štětce+ A brush preset with this name already exists Předvolba štětce s tímto názvem již existujeBrush Preset Options Možnosti přednastavení štětcůGroup name Název skupinyBrush name Název štětcediff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsvindex 15a8f3d53..b2882792a 100644--- a/crates/ui-egui/src/i18n/de.tsv+++ b/crates/ui-egui/src/i18n/de.tsv@@ -2094,6 +2094,11 @@Rename Brush… Pinsel umbenennen…Delete Brush Pinsel löschenNew Brush Preset… Neue Pinselvorgabe…+ Capture Brush Size in Preset Pinselgröße in Vorgabe erfassen+ Include Tool Settings Werkzeugeinstellungen einschließen+ Include Color Farbe einschließen+ Enter a name for the brush preset Geben Sie einen Namen für die Pinselvorgabe ein+ A brush preset with this name already exists Eine Pinselvorgabe mit diesem Namen ist bereits vorhandenBrush Preset Options Pinselvorgaben-OptionenGroup name GruppennameBrush name Pinselnamediff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsvindex 33ed8e158..e697582a6 100644--- a/crates/ui-egui/src/i18n/el.tsv+++ b/crates/ui-egui/src/i18n/el.tsv@@ -1476,6 +1476,11 @@Developing {name} Επεξεργασία του {name}Camera Raw ({name}) Επεξεργασία RAW ({name})New Brush Preset… Νέα προεπιλογή πινέλου…+ Capture Brush Size in Preset Αποθήκευση μεγέθους πινέλου στην προεπιλογή+ Include Tool Settings Συμπερίληψη ρυθμίσεων εργαλείου+ Include Color Συμπερίληψη χρώματος+ Enter a name for the brush preset Εισαγάγετε όνομα για την προεπιλογή πινέλου+ A brush preset with this name already exists Υπάρχει ήδη προεπιλογή πινέλου με αυτό το όνομαBrush Preset Options Επιλογές προεπιλογής πινέλουShow font names in english Εμφάνιση ονομάτων γραμματοσειρών στα αγγλικάShow menu colors Εμφάνιση χρωμάτων μενούdiff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsvindex 4982af80a..a27a6478b 100644--- a/crates/ui-egui/src/i18n/es.tsv+++ b/crates/ui-egui/src/i18n/es.tsv@@ -2111,6 +2111,11 @@Rename Brush… Cambiar el nombre del pincel…Delete Brush Eliminar pincelNew Brush Preset… Nuevo ajuste preestablecido de pincel…+ Capture Brush Size in Preset Capturar tamaño del pincel en el ajuste preestablecido+ Include Tool Settings Incluir ajustes de herramienta+ Include Color Incluir color+ Enter a name for the brush preset Escriba un nombre para el ajuste preestablecido de pincel+ A brush preset with this name already exists Ya existe un ajuste preestablecido de pincel con este nombreBrush Preset Options Opciones de ajustes preestablecidos de pincelGroup name Nombre del grupoBrush name Nombre del pinceldiff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsvindex e29496ad5..1f23a0be3 100644--- a/crates/ui-egui/src/i18n/fr.tsv+++ b/crates/ui-egui/src/i18n/fr.tsv@@ -2076,6 +2076,11 @@Rename Brush… Renommer le pinceau…Delete Brush Supprimer le pinceauNew Brush Preset… Nouveau préréglage de pinceau…+ Capture Brush Size in Preset Capturer la taille du pinceau dans le préréglage+ Include Tool Settings Inclure les paramètres de l'outil+ Include Color Inclure la couleur+ Enter a name for the brush preset Saisissez un nom pour le préréglage de pinceau+ A brush preset with this name already exists Un préréglage de pinceau porte déjà ce nomBrush Preset Options Options des préréglages de pinceauGroup name Nom du groupeBrush name Nom du pinceaudiff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsvindex 2f83eb910..c8fd0724b 100644--- a/crates/ui-egui/src/i18n/hu.tsv+++ b/crates/ui-egui/src/i18n/hu.tsv@@ -1174,6 +1174,11 @@New Brush Új ecsetNew Brush Preset Új ecset-előbeállításNew Brush Preset… Új ecset-előbeállítás…+ Capture Brush Size in Preset Ecsetméret rögzítése az előbeállításban+ Include Tool Settings Eszközbeállítások belefoglalása+ Include Color Szín belefoglalása+ Enter a name for the brush preset Adjon nevet az ecset-előbeállításnak+ A brush preset with this name already exists Már van ilyen nevű ecset-előbeállításNew Crop Preset… Új körbevágási előbeállítás…New Tool Preset Új eszköz-előbeállításNo brush presets Nincs ecset-előbeállításdiff --git a/crates/ui-egui/src/i18n/id.tsv b/crates/ui-egui/src/i18n/id.tsvindex ba8ac9667..311cd13ff 100644--- a/crates/ui-egui/src/i18n/id.tsv+++ b/crates/ui-egui/src/i18n/id.tsv@@ -2070,6 +2070,11 @@Rename Brush… Ganti Nama Kuas…Delete Brush Hapus KuasNew Brush Preset… Preset Kuas Baru…+ Capture Brush Size in Preset Simpan Ukuran Kuas di Preset+ Include Tool Settings Sertakan Pengaturan Alat+ Include Color Sertakan Warna+ Enter a name for the brush preset Masukkan nama untuk preset kuas+ A brush preset with this name already exists Preset kuas dengan nama ini sudah adaBrush Preset Options Opsi Preset KuasGroup name Nama grupBrush name Nama kuasdiff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsvindex dc52628d2..db7a98944 100644--- a/crates/ui-egui/src/i18n/it.tsv+++ b/crates/ui-egui/src/i18n/it.tsv@@ -2108,6 +2108,11 @@Rename Brush… Rinomina pennello…Delete Brush Elimina pennelloNew Brush Preset… Nuovo predefinito pennello…+ Capture Brush Size in Preset Acquisisci dimensione pennello nel predefinito+ Include Tool Settings Includi impostazioni strumento+ Include Color Includi colore+ Enter a name for the brush preset Immetti un nome per il predefinito pennello+ A brush preset with this name already exists Esiste già un predefinito pennello con questo nomeBrush Preset Options Opzioni predefiniti pennelloGroup name Nome gruppoBrush name Nome pennellodiff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsvindex 9461dd82b..9cf72823b 100644--- a/crates/ui-egui/src/i18n/ja.tsv+++ b/crates/ui-egui/src/i18n/ja.tsv@@ -2110,6 +2110,11 @@Rename Brush… ブラシの名前を変更…Delete Brush ブラシを削除New Brush Preset… 新規ブラシプリセット…+ Capture Brush Size in Preset ブラシサイズをプリセットに保存+ Include Tool Settings ツール設定を含める+ Include Color カラーを含める+ Enter a name for the brush preset ブラシプリセットの名前を入力してください+ A brush preset with this name already exists この名前のブラシプリセットは既に存在しますBrush Preset Options ブラシプリセットのオプションGroup name グループ名Brush name ブラシ名diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsvindex f33aefd40..8e80eb5bc 100644--- a/crates/ui-egui/src/i18n/ko.tsv+++ b/crates/ui-egui/src/i18n/ko.tsv@@ -2067,6 +2067,11 @@Rename Brush… 브러시 이름 바꾸기…Delete Brush 브러시 삭제New Brush Preset… 새 브러시 사전 설정…+ Capture Brush Size in Preset 사전 설정에 브러시 크기 캡처+ Include Tool Settings 도구 설정 포함+ Include Color 색상 포함+ Enter a name for the brush preset 브러시 사전 설정의 이름을 입력하십시오+ A brush preset with this name already exists 이 이름의 브러시 사전 설정이 이미 있습니다Brush Preset Options 브러시 사전 설정 옵션Group name 그룹 이름Brush name 브러시 이름diff --git a/crates/ui-egui/src/i18n/nl.tsv b/crates/ui-egui/src/i18n/nl.tsvindex e5f74527d..89d2e9053 100644--- a/crates/ui-egui/src/i18n/nl.tsv+++ b/crates/ui-egui/src/i18n/nl.tsv@@ -2076,6 +2076,11 @@Rename Brush… Penseel hernoemen…Delete Brush Penseel verwijderenNew Brush Preset… Nieuwe penseelvoorinstelling…+ Capture Brush Size in Preset Penseelgrootte vastleggen in voorinstelling+ Include Tool Settings Gereedschapsinstellingen opnemen+ Include Color Kleur opnemen+ Enter a name for the brush preset Voer een naam in voor de penseelvoorinstelling+ A brush preset with this name already exists Er bestaat al een penseelvoorinstelling met deze naamBrush Preset Options Opties penseelvoorinstellingGroup name GroepsnaamBrush name Penseelnaamdiff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsvindex 8291a0a3b..95099d354 100644--- a/crates/ui-egui/src/i18n/pl.tsv+++ b/crates/ui-egui/src/i18n/pl.tsv@@ -3390,6 +3390,11 @@ cameraRaw Roughness ChropowatośćChannels: Kanały:Knockout WycięcieNew Brush Preset… Nowe ustawienie wstępne pędzla…+ Capture Brush Size in Preset Zapisz rozmiar pędzla w ustawieniu wstępnym+ Include Tool Settings Uwzględnij ustawienia narzędzia+ Include Color Uwzględnij kolor+ Enter a name for the brush preset Wpisz nazwę ustawienia wstępnego pędzla+ A brush preset with this name already exists Ustawienie wstępne pędzla o tej nazwie już istniejeBrush Preset Options Opcje ustawień wstępnych pędzla# Fill dialog, layer style contours and Image Sizediff --git a/crates/ui-egui/src/i18n/pt-br.tsv b/crates/ui-egui/src/i18n/pt-br.tsvindex 002d26806..f5f69f9f4 100644--- a/crates/ui-egui/src/i18n/pt-br.tsv+++ b/crates/ui-egui/src/i18n/pt-br.tsv@@ -2071,6 +2071,11 @@Rename Brush… Renomear pincel…Delete Brush Excluir pincelNew Brush Preset… Nova predefinição de pincel…+ Capture Brush Size in Preset Capturar tamanho do pincel na predefinição+ Include Tool Settings Incluir configurações da ferramenta+ Include Color Incluir cor+ Enter a name for the brush preset Digite um nome para a predefinição de pincel+ A brush preset with this name already exists Já existe uma predefinição de pincel com este nomeBrush Preset Options Opções de predefinições de pincelGroup name Nome do grupoBrush name Nome do pinceldiff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsvindex 9be736f71..9ee6e311f 100644--- a/crates/ui-egui/src/i18n/ru.tsv+++ b/crates/ui-egui/src/i18n/ru.tsv@@ -1026,6 +1026,11 @@Brush Name Имя кистиBrush Stroke Мазок кистиNew Brush Preset… Новый набор параметров кисти…+ Capture Brush Size in Preset Сохранить размер кисти в наборе+ Include Tool Settings Включить настройки инструмента+ Include Color Включить цвет+ Enter a name for the brush preset Введите имя набора параметров кисти+ A brush preset with this name already exists Набор параметров кисти с таким именем уже существуетBrush Preset Options Параметры наборов кистейNew Brush Новая кистьCreate new brush from these settings Создать новую кисть из этих параметровdiff --git a/crates/ui-egui/src/i18n/sr.tsv b/crates/ui-egui/src/i18n/sr.tsvindex 412a2e958..75ceb7167 100644--- a/crates/ui-egui/src/i18n/sr.tsv+++ b/crates/ui-egui/src/i18n/sr.tsv@@ -2066,6 +2066,11 @@Rename Brush… Preimenuj četkicu…Delete Brush Obriši četkicuNew Brush Preset… Novi šablon četkice…+ Capture Brush Size in Preset Sačuvaj veličinu četkice u šablonu+ Include Tool Settings Uključi podešavanja alatke+ Include Color Uključi boju+ Enter a name for the brush preset Unesite ime šablona četkice+ A brush preset with this name already exists Šablon četkice sa ovim imenom već postojiBrush Preset Options Opcije šablona četkiceGroup name Ime grupeBrush name Ime četkicediff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsvindex 999bcc396..e912f26c2 100644--- a/crates/ui-egui/src/i18n/tr.tsv+++ b/crates/ui-egui/src/i18n/tr.tsv@@ -2058,6 +2058,11 @@Rename Brush… Fırçayı Yeniden Adlandır…Delete Brush Fırçayı SilNew Brush Preset… Yeni Fırça Ön Ayarı…+ Capture Brush Size in Preset Fırça Boyutunu Ön Ayara Kaydet+ Include Tool Settings Araç Ayarlarını Dahil Et+ Include Color Rengi Dahil Et+ Enter a name for the brush preset Fırça ön ayarı için bir ad girin+ A brush preset with this name already exists Bu adda bir fırça ön ayarı zaten varBrush Preset Options Fırça Ön Ayarı SeçenekleriGroup name Grup adıBrush name Fırça adıdiff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsvindex 72f4cffb7..0af7c871d 100644--- a/crates/ui-egui/src/i18n/uk.tsv+++ b/crates/ui-egui/src/i18n/uk.tsv@@ -1004,6 +1004,11 @@Brush Name Назва пензляBrush Stroke Мазок пензляNew Brush Preset… Новий набір пензля…+ Capture Brush Size in Preset Зберегти розмір пензля в наборі+ Include Tool Settings Включити налаштування інструмента+ Include Color Включити колір+ Enter a name for the brush preset Введіть назву набору пензля+ A brush preset with this name already exists Набір пензля з такою назвою вже існуєBrush Preset Options Параметри набору пензляNew Brush Новий пензельCreate new brush from these settings Створити новий пензель із цими параметрамиdiff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsvindex 590c4b87e..f01c25ce7 100644--- a/crates/ui-egui/src/i18n/vi.tsv+++ b/crates/ui-egui/src/i18n/vi.tsv@@ -2026,6 +2026,11 @@ layers Fill: Độ tô:Move effect layer down Di chuyển lớp hiệu ứng xuốngMove effect layer up Di chuyển lớp hiệu ứng lênNew Brush Preset… Thiết lập sẵn cọ mới…+ Capture Brush Size in Preset Lưu kích thước cọ vào thiết lập sẵn+ Include Tool Settings Bao gồm thiết lập công cụ+ Include Color Bao gồm màu+ Enter a name for the brush preset Nhập tên cho thiết lập sẵn cọ+ A brush preset with this name already exists Đã có thiết lập sẵn cọ với tên nàyNew effect layer Lớp hiệu ứng mớiNew Swatch Group… Nhóm mẫu màu mới…New Swatch… Mẫu màu mới…diff --git a/crates/ui-egui/src/i18n/zh-hans.tsv b/crates/ui-egui/src/i18n/zh-hans.tsvindex 50ba2bb7b..31ecc7b5a 100644--- a/crates/ui-egui/src/i18n/zh-hans.tsv+++ b/crates/ui-egui/src/i18n/zh-hans.tsv@@ -2173,6 +2173,11 @@ cameraRaw Blending 混合Rename Brush… 重命名画笔…Delete Brush 删除画笔New Brush Preset… 新建画笔预设…+ Capture Brush Size in Preset 在预设中存储画笔大小+ Include Tool Settings 包含工具设置+ Include Color 包含颜色+ Enter a name for the brush preset 请输入画笔预设的名称+ A brush preset with this name already exists 已存在同名的画笔预设Brush Preset Options 画笔预设选项Group name 组名称Brush name 画笔名称diff --git a/crates/ui-egui/src/i18n/zh-hant.tsv b/crates/ui-egui/src/i18n/zh-hant.tsvindex ca23a7451..3b43fff17 100644--- a/crates/ui-egui/src/i18n/zh-hant.tsv+++ b/crates/ui-egui/src/i18n/zh-hant.tsv@@ -2109,6 +2109,11 @@Rename Brush… 重新命名筆刷…Delete Brush 刪除筆刷New Brush Preset… 新增筆刷預設集…+ Capture Brush Size in Preset 在預設集中擷取筆刷尺寸+ Include Tool Settings 包含工具設定+ Include Color 包含顏色+ Enter a name for the brush preset 請輸入筆刷預設集的名稱+ A brush preset with this name already exists 已有相同名稱的筆刷預設集Brush Preset Options 筆刷預設集選項Group name 群組名稱Brush name 筆刷名稱diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex c0d64e7c0..7cda48e82 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -30,6 +30,7 @@ mod brand;pub(crate) mod brush_cursor;pub mod brush_panel;pub mod brush_picker;+pub mod brush_preset_dialog;pub mod brush_preview;pub mod brush_resize;pub mod brush_sections;diff --git a/crates/ui-egui/src/paint_mouse.rs b/crates/ui-egui/src/paint_mouse.rsindex bb2d6653d..c49055e13 100644--- a/crates/ui-egui/src/paint_mouse.rs+++ b/crates/ui-egui/src/paint_mouse.rs@@ -433,8 +433,8 @@ mod tests {assert!(h.state().ui.brush_picker.is_some());}- /// The gear menu's New Brush Preset… saves the brush and asks for its name in the picker's- /// rename bar; Enter there renames it and leaves the picker open (Enter closes it otherwise).+ /// The gear menu's New Brush Preset… opens the New Brush Preset dialog (#4490), which saves+ /// the preset under the typed name on OK.#[test]fn picker_gear_menu_saves_and_names_a_new_preset() {use egui_kittest::kittest::Queryable;@@ -444,19 +444,20 @@ mod tests {h.run_steps(2);h.get_by_label("Brush Preset Options").click();h.run_steps(2);+ let before = h.state().session.tools.presets.len();h.get_by_label("New Brush Preset…").click();h.run_steps(3);- let saved = h.state().ui.brush_picker_list.renaming.clone().expect("the rename bar asks for a name");- assert!(h.state().session.tools.presets.iter().any(|p| p.name == saved.name));- assert!(h.state().ui.brush_picker.is_some(), "the menu's click didn't close the picker");- h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);- h.event(egui::Event::Text("Inky".into()));- h.run_steps(1);- h.key_press(egui::Key::Enter);- h.run_steps(3);- assert!(h.state().session.tools.presets.iter().any(|p| p.name == "Inky"), "renamed");- assert!(h.state().ui.brush_picker_list.renaming.is_none());- assert!(h.state().ui.brush_picker.is_some(), "Enter ended the rename, not the picker");+ let dialog = h.state().ui.dialogs.iter().find(|d| crate::brush_preset_dialog::owns(&d.fields)).map(|d| d.id).expect("the dialog asks for a name");+ assert_eq!(h.state().session.tools.presets.len(), before, "nothing is saved before OK");+ assert!(h.state().ui.brush_picker.is_none(), "the dialog takes the picker's place");+ // This harness draws the canvas only: OK as automation does (the dialog's own tests type).+ h.state_mut().ui.dialog_mut(dialog).unwrap().fields.insert("name".into(), json!("Inky"));+ crate::dialogs::confirm(h.state_mut(), dialog).unwrap();+ h.run_steps(2);+ assert!(h.state().session.tools.presets.iter().any(|p| p.name == "Inky"), "saved under the typed name");+ assert_eq!(h.state().session.tools.current_preset.as_deref(), Some("Inky"));+ h.state_mut().ui.brush_picker = Some([c.x, c.y]);+ h.run_steps(2);// The gear's boxes pick the card parts; the last one on can't be turned off.h.get_by_label("Brush Preset Options").click();h.run_steps(2);