PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Shapes: the Color panel, Swatches and Gradients fill the selected shape (#5568)
jackn942a581c0ca8
diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rsindex 7c92dfba9..31e7561c3 100644--- a/crates/engine/src/presets/gradients.rs+++ b/crates/engine/src/presets/gradients.rs@@ -441,15 +441,47 @@ fn active_gradient_fill(s: &Session) -> Option<photocraft_doc::LayerId> {matches!(d.doc.layer(id)?.content, LayerContent::Fill(Fill::Gradient { .. })).then_some(id)}+fn active_shape(s: &Session) -> Option<photocraft_doc::LayerId> {+ let d = s.active()?;+ let id = d.active_layer?;+ matches!(d.doc.layer(id)?.content, LayerContent::Shape(_)).then_some(id)+}+fn select(s: &mut Session, p: &Value) -> Result<Value> {let g = preset_param(s, p, CMD_SELECT)?;+ let apply = p.get("applyToLayer").and_then(Value::as_bool).unwrap_or(true);+ let shape = active_shape(s).filter(|_| apply);+ // A locked shape refuses before anything changes, the Gradient tool's gradient included.+ if let (Some(id), Some(d)) = (shape, s.active()) {+ let locks = d.doc.effective_locks(id);+ if locks.all || locks.pixels {+ return Err(bad(CMD_SELECT, "the selected shape layer is locked"));+ }+ }s.presets.gradient = g.clone();s.presets_changed();let mut out = json!({"current": g.to_json()});+ // Clicking a preset with a shape layer selected fills the shape with it (Photoshop, #5568);+ // a gradient fill keeps its angle, style, scale and reverse.+ if let Some(id) = shape {+ let (stops_new, opacity_new) = g.fill_stops(s.tools.foreground, s.tools.background);+ crate::vector_cmds::with_shape(s, id, "Edit Shape", |sh, _| {+ let (angle, scale, style, reverse) = match &sh.fill {+ Some(Fill::Gradient { angle, scale, style, reverse, .. }) => (*angle, *scale, *style, *reverse),+ _ => (90.0, 1.0, photocraft_doc::GradientStyle::Linear, false),+ };+ let mut fill = Fill::gradient(stops_new, angle, scale, style, reverse);+ if let Fill::Gradient { opacity_stops, .. } = &mut fill {+ *opacity_stops = opacity_new;+ }+ sh.fill = Some(fill);+ Ok(())+ })?;+ out["layer"] = json!(id.0);+ return Ok(out);+ }// Clicking a preset with a Gradient Fill layer selected changes that layer (Photoshop).- if p.get("applyToLayer").and_then(Value::as_bool).unwrap_or(true)- && let Some(id) = active_gradient_fill(s)- {+ if apply && let Some(id) = active_gradient_fill(s) {let (stops_new, opacity_new) = g.fill_stops(s.tools.foreground, s.tools.background);s.edit("Change Gradient Fill", |doc, _| {let mode = doc.mode;@@ -674,7 +706,7 @@ pub fn specs() -> Vec<CommandSpec> {menu: &[],shortcut: None,params: leak(format!(- r##"{{"preset":name|{stops},"group":name?,"applyToLayer":bool=true (also recolours a selected Gradient Fill layer)}} → {{current,layer?}}. The Gradient tool paints with it."##+ r##"{{"preset":name|{stops},"group":name?,"applyToLayer":bool=true (also recolours a selected Gradient Fill layer, or fills a selected shape layer with it)}} → {{current,layer?}}. The Gradient tool paints with it."##)),enabled: always,run: select,diff --git a/crates/engine/src/presets/tests.rs b/crates/engine/src/presets/tests.rsindex dcfc4e94d..0b714245d 100644--- a/crates/engine/src/presets/tests.rs+++ b/crates/engine/src/presets/tests.rs@@ -748,3 +748,45 @@ fn clone_source_errors_and_overlay() {assert_eq!(v["width"], json!(1000.0));assert_eq!(v["rotation"], json!(-90.0));}++fn shape_fill(s: &Session, id: LayerId) -> Option<Fill> {+ match &s.active().unwrap().doc.layer(id).unwrap().content {+ LayerContent::Shape(sh) => sh.fill.clone(),+ _ => panic!("not a shape layer"),+ }+}++/// #5568: clicking a gradient with a shape layer selected fills the shape with it in one undo+/// step; a gradient fill keeps its angle, style, scale and reverse.+#[test]+fn gradient_preset_click_fills_the_selected_shape_layer() {+ let mut s = session(8);+ let id = LayerId(s.execute("shape.create", json!({"rect": [8, 8, 40, 30], "fill": "#336699"})).unwrap()["layer"].as_u64().unwrap());+ let before = shape_fill(&s, id);+ let r = s.execute("gradient.presets.select", json!({"preset": "Red 01"})).unwrap();+ assert_eq!(r["layer"], json!(id.0));+ let Some(Fill::Gradient { stops, angle, style, .. }) = shape_fill(&s, id) else { panic!("not a gradient") };+ // Red 01 starts at #7f0000; a new gradient fill is linear at 90°.+ assert_eq!(stops[0].1.to_rgba8(), [0x7f, 0, 0, 0xff]);+ assert_eq!((angle, style), (90.0, photocraft_doc::GradientStyle::Linear));+ s.execute("edit.undo", json!({})).unwrap();+ assert_eq!(shape_fill(&s, id), before);++ s.execute("shape.edit", json!({"layer": id.0, "fill": {"gradient": {"angle": 30, "style": "radial", "scale": 80, "reverse": true}}})).unwrap();+ s.execute("gradient.presets.select", json!({"preset": "Green 01"})).unwrap();+ let Some(Fill::Gradient { angle, style, scale, reverse, .. }) = shape_fill(&s, id) else { panic!("not a gradient") };+ assert_eq!((angle, style, scale, reverse), (30.0, photocraft_doc::GradientStyle::Radial, 0.8, true));+}++/// A locked shape refuses the click before anything changes, the Gradient tool's gradient included.+#[test]+fn gradient_preset_click_on_a_locked_shape_changes_nothing() {+ let mut s = session(8);+ let id = LayerId(s.execute("shape.create", json!({"rect": [8, 8, 40, 30], "fill": "#336699"})).unwrap()["layer"].as_u64().unwrap());+ let (before, gradient) = (shape_fill(&s, id), s.presets.gradient.name.clone());+ s.execute("layer.lockLayers", json!({"all": true})).unwrap();+ let err = s.execute("gradient.presets.select", json!({"preset": "Red 01"})).unwrap_err().to_string();+ assert!(err.contains("locked"), "{err}");+ assert_eq!(shape_fill(&s, id), before);+ assert_eq!(s.presets.gradient.name, gradient);+}diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rsindex 09a3ce8d4..9d61e3b98 100644--- a/crates/ui-egui/src/color_picker_ui.rs+++ b/crates/ui-egui/src/color_picker_ui.rs@@ -825,6 +825,7 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,let r = app.run("tools.setColors", params)?;if target == "foreground" {crate::type_tool::foreground_changed(app);+ crate::shape_fill_ui::foreground_changed(app, None);}Ok(r)}diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 479355415..6367cf26f 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -2152,6 +2152,7 @@ fn hsb_sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui) {app.session.tools.foreground = hsva_srgb(hsva);ui.data_mut(|d| d.insert_temp(key, hsva));crate::type_tool::foreground_changed(app);+ crate::shape_fill_ui::foreground_changed(app, crate::shape_fill_ui::gesture(ui));}}@@ -3739,6 +3740,7 @@ fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) {} else {app.session.tools.foreground = hsva_srgb(hsva);crate::type_tool::foreground_changed(app);+ crate::shape_fill_ui::foreground_changed(app, crate::shape_fill_ui::gesture(ui));}ui.data_mut(|d| d.insert_temp(key, (hsva.h, hsva.s)));}@@ -3752,6 +3754,7 @@ fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) {} else {app.session.tools.foreground = c;crate::type_tool::foreground_changed(app);+ crate::shape_fill_ui::foreground_changed(app, crate::shape_fill_ui::gesture(ui));}// Keep the hue for greys, so the field marker doesn't jump to red; the saturation with// it, so a later black lands on the corner it was last dragged to (#3228).@@ -4588,6 +4591,33 @@ mod color_tests {}}+ /// #5568: with a shape layer selected, the Color panel recolours its fill (keeping the fill's+ /// opacity): a click is one undo step and a whole drag across the field is one more.+ #[test]+ fn color_panel_recolours_the_selected_shape_fill() {+ use photocraft_doc::{Fill, LayerContent, LayerId};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap();+ let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": [0.2, 0.4, 0.6, 0.5]})).unwrap()["layer"].as_u64().unwrap());+ let mut h = field_harness(app);+ let fill = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content {+ LayerContent::Shape(sh) => sh.fill.clone(),+ _ => panic!("not a shape layer"),+ };+ let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len();+ let before = steps(h.state());+ let min = h.ctx.input(|i| i.viewport_rect()).min;+ // The field's top-left: no saturation, full brightness.+ click(&mut h, min + vec2(60.0, 10.0));+ let fg = h.state().session.tools.foreground;+ assert_eq!(fill(h.state()), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 0.5))));+ assert_eq!(steps(h.state()), before + 1);+ drag(&mut h, min + vec2(120.0, 40.0), min + vec2(250.0, 120.0));+ let fg = h.state().session.tools.foreground;+ assert_eq!(fill(h.state()), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 0.5))));+ assert_eq!(steps(h.state()), before + 2, "the whole drag is one undo step");+ }+/// Press at `from`, move to `to` in six steps and release, as egui sees a drag.fn drag(h: &mut egui_kittest::Harness<'_, PhotocraftApp>, from: egui::Pos2, to: egui::Pos2) {h.hover_at(from);diff --git a/crates/ui-egui/src/shape_fill_ui.rs b/crates/ui-egui/src/shape_fill_ui.rsindex 37731ce24..20d297d72 100644--- a/crates/ui-egui/src/shape_fill_ui.rs+++ b/crates/ui-egui/src/shape_fill_ui.rs@@ -82,6 +82,41 @@ pub(crate) fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Resultapp.run(COMMAND, json!({"layer": layer.0, "fill": [color.c[0], color.c[1], color.c[2], color.alpha]}))}+/// A new foreground colour from the Color panel, a swatch or the Color Picker fills the selected+/// shape layer, keeping the fill's own opacity, as in Photoshop (#5568). Edits sharing `coalesce`+/// (one Color panel drag) are one undo step. Locked shapes and other layers are left alone.+pub(crate) fn foreground_changed(app: &mut PhotocraftApp, coalesce: Option<String>) {+ let Some(st) = app.session.active() else { return };+ let Some(layer) = st.active_layer else { return };+ let Some(LayerContent::Shape(sh)) = st.doc.layer(layer).map(|l| &l.content) else { return };+ let locks = st.doc.effective_locks(layer);+ if locks.all || locks.pixels {+ return;+ }+ let fg = app.session.tools.foreground;+ let alpha = match &sh.fill {+ Some(Fill::Solid(c)) => c.alpha,+ _ => 1.0,+ };+ if sh.fill == Some(Fill::Solid(Color::rgba(fg[0], fg[1], fg[2], alpha))) {+ return;+ }+ let mut p = json!({"layer": layer.0, "fill": [fg[0], fg[1], fg[2], alpha]});+ if let Some(key) = coalesce {+ p["coalesce"] = json!(key);+ }+ if let Err(e) = app.run(COMMAND, p) {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}++/// The coalesce key of the pointer gesture under way (its press time), so one Color panel drag+/// is one undo step; `None` for clicks and typed values.+pub(crate) fn gesture(ui: &egui::Ui) -> Option<String> {+ ui.input(|i| i.pointer.press_start_time()).map(|t| format!("color-panel-fill:{}", t.to_bits()))+}+/// The canvas preview while the picker is open: the document with the shape re-rendered in the/// picked colour, cached per dialog, revision and colour.pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc<Document>, u64)> {diff --git a/crates/ui-egui/src/swatches_ui.rs b/crates/ui-egui/src/swatches_ui.rsindex a18ddee64..d1fe7ef7c 100644--- a/crates/ui-egui/src/swatches_ui.rs+++ b/crates/ui-egui/src/swatches_ui.rs@@ -2,7 +2,8 @@//! preset browser: groups with disclosure triangles, a colour grid with name tooltips, a context//! menu (Rename, Delete, Move to), and the footer (size · New Group · New Swatch · Delete).//!-//! As in Photoshop, clicking a swatch sets the foreground colour (and recolours selected type);+//! As in Photoshop, clicking a swatch sets the foreground colour (and recolours selected type or+//! fills the selected shape layer);//! Alt- or Ctrl/Cmd-clicking sets the background colour; double-clicking renames it. The//! panel menu (the group's "…" button) adds New Swatch, New Group, Import/Replace (`.aco`,//! `.ase`), Export (`.aco`) and Export for Exchange (`.ase`) and Reset. Every action is a@@ -51,8 +52,10 @@ fn colors(app: &PhotocraftApp, ctx: &egui::Context) -> Arc<Vec<Vec<Color32>>> {pub fn use_swatch(app: &mut PhotocraftApp, name: &str, background: bool) {let target = if background { "background" } else { "foreground" };if run(app, "swatches.use", json!({"swatch": name, "target": target})).is_some() && !background {- // Clicking a swatch while characters are selected recolours them (#364).+ // Clicking a swatch while characters are selected recolours them (#364), and with a+ // shape layer selected fills the shape (#5568).crate::type_tool::foreground_changed(app);+ crate::shape_fill_ui::foreground_changed(app, None);}}@@ -273,6 +276,31 @@ mod tests {use egui::{Modifiers, vec2};use egui_kittest::Harness;+ /// #5568: clicking a swatch with a shape layer selected fills the shape with it, one undo+ /// step each, a gradient fill included.+ #[test]+ fn swatch_click_fills_the_selected_shape() {+ use photocraft_doc::{Fill, LayerContent, LayerId};+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", json!({"width": 64, "height": 48})).unwrap();+ let id = LayerId(app.run("shape.create", json!({"rect": [8, 8, 40, 30], "fill": {"gradient": {}}})).unwrap()["layer"].as_u64().unwrap());+ let fill = |app: &PhotocraftApp| match &app.session.active().unwrap().doc.layer(id).unwrap().content {+ LayerContent::Shape(sh) => sh.fill.clone(),+ _ => panic!("not a shape layer"),+ };+ let steps = |app: &PhotocraftApp| app.session.active().unwrap().history.entries().len();+ let before = steps(&app);+ let names: Vec<String> = app.session.presets.swatches[0].items.iter().take(2).map(|s| s.name.clone()).collect();+ use_swatch(&mut app, &names[0], false);+ let fg = app.session.tools.foreground;+ assert_eq!(fill(&app), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 1.0))), "{} filled the shape", names[0]);+ assert_eq!(steps(&app), before + 1);+ use_swatch(&mut app, &names[1], false);+ let fg = app.session.tools.foreground;+ assert_eq!(fill(&app), Some(Fill::Solid(photocraft_doc::Color::rgba(fg[0], fg[1], fg[2], 1.0))), "{} filled the shape", names[1]);+ assert_eq!(steps(&app), before + 2, "each swatch click is its own undo step");+ }+fn click(h: &mut Harness<'_, PhotocraftApp>, p: egui::Pos2, modifiers: Modifiers) {h.hover_at(p);// Held modifiers, as when the user holds Alt while clicking.