PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fill and adjustment layers take the active path as their vector mask (#1419)
David Mann99b6aff26b92
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 202d62a59..5eba60aab 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -220,12 +220,36 @@ pub(crate) fn selection_mask(doc: &Document) -> Option<LayerMask> {doc.selection.as_ref().map(|sel| LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() })}-fn new_adjustment(s: &mut Session, adj: Adjustment) -> Result<Value> {+/// Mask a fill or adjustment layer being created, as Photoshop does: the path selected in the+/// Paths panel (`"path"`: `"work"`, a saved path's name or a path object) becomes its vector+/// mask, which makes a Solid Color fill a shape (#1419); without one, the selection becomes its+/// layer mask ([`selection_mask`]). A path that isn't there is an error.+pub(crate) fn mask_new_layer(doc: &Document, l: &mut Layer, p: &Value, cmd: &str) -> Result<()> {+ let path = match p.get("path") {+ None | Some(Value::Null) => None,+ Some(Value::String(n)) if crate::vector_cmds::is_work(Some(n)) => Some(doc.work_path.clone().ok_or_else(|| bad(cmd, "no work path"))?),+ Some(Value::String(n)) => {+ Some(doc.paths.iter().find(|sp| sp.name == *n).map(|sp| sp.path.clone()).ok_or_else(|| bad(cmd, format!("no path named \"{n}\"")))?)+ }+ Some(v) => Some(crate::vector_cmds::parse_path(v).map_err(|e| bad(cmd, e))?),+ };+ match path {+ Some(path) => l.vector_mask = Some(photocraft_doc::VectorMask::new(path)),+ None => l.mask = selection_mask(doc),+ }+ Ok(())+}++/// The `"path"` param of the new fill and adjustment layer commands ([`mask_new_layer`]).+pub(crate) const NEW_LAYER_PATH: &str =+ r##""path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)"##;++fn new_adjustment(s: &mut Session, adj: Adjustment, p: &Value, cmd: &str) -> Result<Value> {let label = format!("New {} Layer", adj.label());let name = adj.label().to_string();let id = s.edit(&label, |doc, active| {let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj));- l.mask = selection_mask(doc);+ mask_new_layer(doc, &mut l, p, cmd)?;let id = doc.insert_above(*active, l);*active = Some(id);Ok(id)@@ -678,23 +702,31 @@ fn build() -> Vec<CommandSpec> {})?;Ok(Value::Null)}),- cmd!("layer.newFillLayer.solidColor", "Solid Color…", ["Layer", "New Fill Layer"], None, r##"{"color":"#rrggbb"=foreground}"##, has_doc, |s, p| {- let c = color_param(p, "color", s.tools.foreground);- let id = s.edit("New Color Fill Layer", |doc, active| {- let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3]))));- l.mask = selection_mask(doc);- let id = doc.insert_above(*active, l);- *active = Some(id);- Ok(id)- })?;- Ok(json!({ "layer": id.0 }))- }),+ cmd!(+ "layer.newFillLayer.solidColor",+ "Solid Color…",+ ["Layer", "New Fill Layer"],+ None,+ r##"{"color":"#rrggbb"=foreground,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask, making a shape; else the selection is the layer mask)}"##,+ has_doc,+ |s, p| {+ let c = color_param(p, "color", s.tools.foreground);+ let id = s.edit("New Color Fill Layer", |doc, active| {+ let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3]))));+ mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor")?;+ let id = doc.insert_above(*active, l);+ *active = Some(id);+ Ok(id)+ })?;+ Ok(json!({ "layer": id.0 }))+ }+ ),cmd!("layer.newFillLayer.gradient","Gradient…",["Layer", "New Fill Layer"],None,- r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool}"##,+ r##"{"from":"#rrggbb","to":"#rrggbb","angle":deg=90,"style":"linear|radial|angle|reflected|diamond","reverse":bool,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,has_doc,|s, p| {let a = color_param(p, "from", s.tools.foreground);@@ -711,7 +743,7 @@ fn build() -> Vec<CommandSpec> {reverse,);let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));- l.mask = selection_mask(doc);+ mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient")?;let id = doc.insert_above(*active, l);*active = Some(id);Ok(id)@@ -976,7 +1008,7 @@ fn build() -> Vec<CommandSpec> {label,menu: &["Layer", "New Adjustment Layer"],shortcut: None,- params,+ params: Box::leak(format!("{params} + {{{NEW_LAYER_PATH}}}").into_boxed_str()),enabled: has_doc,run: |s, p| {let kind = p.get("__kind").and_then(Value::as_str).unwrap_or("invert").to_string();@@ -985,7 +1017,7 @@ fn build() -> Vec<CommandSpec> {Some(adj) => adj,None => crate::adjust_params::from_params(&kind, p, None, doc_mode(s))?,};- new_adjustment(s, adj)+ new_adjustment(s, adj, p, &format!("layer.newAdjustmentLayer.{kind}"))},journal: true,});diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rsindex e8e537b8c..5ddd35969 100644--- a/crates/engine/src/pattern_cmds.rs+++ b/crates/engine/src/pattern_cmds.rs@@ -308,7 +308,7 @@ fn new_fill_layer(s: &mut Session, p: &Value) -> Result<Value> {ensure_in_doc(doc, &pat);let fill = Fill::Pattern { name: pat.name.clone(), scale, id: pat.id.clone(), angle, link, phase };let mut l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill));- l.mask = crate::commands::selection_mask(doc);+ crate::commands::mask_new_layer(doc, &mut l, p, "layer.newFillLayer.pattern")?;let id = doc.insert_above(*active, l);*active = Some(id);Ok(id)@@ -414,7 +414,7 @@ pub fn specs() -> Vec<CommandSpec> {label: "Pattern…",menu: &["Layer", "New Fill Layer"],shortcut: None,- params: r##"{"pattern":id|name?=first library pattern,"scale":1..1000=100,"angle":deg=0,"link":bool=true,"phase":[x,y]?}"##,+ params: r##"{"pattern":id|name?=first library pattern,"scale":1..1000=100,"angle":deg=0,"link":bool=true,"phase":[x,y]?,"path":"work"|saved path name|{…path}? (the active path: becomes the vector mask; else the selection is the layer mask)}"##,enabled: has_doc,journal: true,run: new_fill_layer,diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex cbaf6d41e..1a616eb0e 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -171,6 +171,64 @@ fn new_adjustment_and_fill_layers_have_no_mask_without_a_selection() {}}+#[test]+fn new_fill_and_adjustment_layers_take_the_active_path_as_their_vector_mask() {+ // #1419: as in Photoshop, the path selected in the Paths panel becomes the vector mask of a+ // new fill or adjustment layer (a Solid Color fill becomes a shape) and wins over a selection.+ let square = json!({"subpaths": [{"closed": true, "knots": [[8, 8], [24, 8], [24, 24], [8, 24]]}]});+ for depth in [8, 16, 32] {+ for (id, params, blackens) in [+ ("layer.newFillLayer.solidColor", json!({"color": "#000000"}), true),+ ("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#000000"}), true),+ ("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"}), false),+ ("layer.newAdjustmentLayer.invert", json!({}), true),+ ] {+ for (path_name, setup) in [("work", "work"), ("Saved", "Saved")] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap();+ s.execute("path.set", json!({"name": setup, "path": square})).unwrap();+ // A selection elsewhere: the path wins, as in Photoshop.+ s.execute("select.rect", json!({"x": 40, "y": 30, "width": 8, "height": 8})).unwrap();+ let mut p = params.clone();+ p["path"] = json!(path_name);+ let layer = LayerId(s.execute(id, p).unwrap()["layer"].as_u64().unwrap());+ let d = s.active().unwrap();+ let l = d.doc.layer(layer).unwrap();+ let vm = l.vector_mask.as_ref().unwrap_or_else(|| panic!("{id} ({path_name}) at {depth}-bit: no vector mask"));+ let want = if path_name == "work" { d.doc.work_path.clone().unwrap() } else { d.doc.paths[0].path.clone() };+ assert_eq!(vm.path, want, "{id}: the vector mask is the path");+ assert!(l.mask.is_none(), "{id}: the path wins over the selection");+ for (x, y) in [(2, 2), (42, 32), (30, 30)] {+ assert_eq!(px(&mut s, x, y), vec![1.0, 1.0, 1.0, 1.0], "{id} ({path_name}) at {depth}-bit changed pixels outside the path at ({x}, {y})");+ }+ if blackens {+ assert_eq!(px(&mut s, 16, 16)[..3], [0.0, 0.0, 0.0][..], "{id} ({path_name}) at {depth}-bit: no effect inside the path");+ }+ s.execute("edit.undo", json!({})).unwrap();+ assert!(s.active().unwrap().doc.layer(layer).is_none(), "{id}: undo keeps the layer");+ }+ }+ }+}++#[test]+fn new_fill_layer_with_a_missing_path_fails_without_a_layer() {+ let mut s = session_with_doc();+ let before = s.active().unwrap().doc.layers.len();+ for (id, params) in [+ ("layer.newFillLayer.solidColor", json!({"path": "work"})),+ ("layer.newFillLayer.solidColor", json!({"path": "Nope"})),+ ("layer.newFillLayer.gradient", json!({"path": "Nope"})),+ ("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard", "path": "Nope"})),+ ("layer.newAdjustmentLayer.invert", json!({"path": "Nope"})),+ ("layer.newFillLayer.solidColor", json!({"path": 42})),+ ("layer.newFillLayer.solidColor", json!({"path": {"subpaths": "x"}})),+ ] {+ assert!(s.execute(id, params.clone()).is_err(), "{id} {params}: no error");+ assert_eq!(s.active().unwrap().doc.layers.len(), before, "{id} {params}: added a layer");+ }+}+#[test]fn every_adjustment_command_runs() {let mut s = session_with_doc();diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rsindex 14ce043b2..a7e4f41c7 100644--- a/crates/engine/src/vector_cmds.rs+++ b/crates/engine/src/vector_cmds.rs@@ -674,7 +674,7 @@ fn shape_rasterize(s: &mut Session, p: &Value) -> Result<Value> {// Document paths// ----------------------------------------------------------------------------fn is_work(name: Option<&str>) -> bool {+pub(crate) fn is_work(name: Option<&str>) -> bool {name.is_none_or(|n| n.is_empty() || n.eq_ignore_ascii_case("work") || n == "Work Path")}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 371f9d8c8..037858b44 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -672,7 +672,18 @@ impl PhotocraftApp {}// Long commands become background jobs when enabled (`jobs_ui`); the rest run inline.let params = self.with_mask_target(id, params);+ let params = vector_ui::with_active_path(self, id, params);+ let path_mask = vector_ui::takes_path_mask(id) && params.get("path").is_some_and(|v| !v.is_null());let r = jobs_ui::run(self, id, params);+ if r.is_ok() && id == "select.toWorkPath" {+ // Make Work Path selects the new work path in the Paths panel, as in Photoshop.+ self.ui.selected_path = Some("work".into());+ }+ if r.is_ok() && path_mask {+ // The new layer's vector mask becomes the active path, as in Photoshop: the path it+ // was made from is no longer selected, so the next fill layer isn't masked by it too.+ self.ui.selected_path = Some("layer".into());+ }if r.is_ok() && matches!(id, "edit.copy" | "edit.cut" | "edit.copyMerged") {self.clip_external = false;self.export_os_clipboard();diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rsindex f6d258a9c..78769c828 100644--- a/crates/ui-egui/src/vector_ui.rs+++ b/crates/ui-egui/src/vector_ui.rs@@ -175,7 +175,8 @@ pub fn pen_commit(app: &mut PhotocraftApp, closed: bool) {}app.run("layer.vectorMask.edit", json!({"layer": id, "path": p}))} else {- app.run("path.set", json!({"name": "work", "path": path}))+ // The drawn work path is selected in the Paths panel, as in Photoshop.+ app.run("path.set", json!({"name": "work", "path": path})).inspect(|_| app.ui.selected_path = Some("work".into()))};if let Err(e) = r {app.ui.status = e;@@ -197,6 +198,38 @@ pub fn active_path_name(app: &PhotocraftApp) -> Option<String> {selected.or_else(|| rows.iter().find(|r| r.kind == PathRow::Work).map(key)).or_else(|| rows.iter().find(|r| r.kind == PathRow::Layer).map(key))}+/// The commands that create a fill or adjustment layer and take a `"path"` as its vector mask.+pub fn takes_path_mask(id: &str) -> bool {+ id.starts_with("layer.newFillLayer.") || id.starts_with("layer.newAdjustmentLayer.")+}++/// New fill and adjustment layers take the path selected in the Paths panel as their vector mask,+/// as in Photoshop (#1419): the command gets it as `"path"` unless the caller set one (`null`+/// opts out). Only an explicitly selected work or saved path counts; deselect it by clicking the+/// panel's empty area.+pub fn with_active_path(app: &PhotocraftApp, id: &str, params: Value) -> Value {+ if !takes_path_mask(id) || params.get("path").is_some() {+ return params;+ }+ let Some(st) = app.session.active() else { return params };+ let Some(sel) = app.ui.selected_path.as_deref() else { return params };+ let listed = path_rows(&st.doc, st.active_layer).iter().any(|r| match r.kind {+ PathRow::Work => sel == "work",+ PathRow::Saved => r.name == sel,+ PathRow::Layer => false,+ });+ if !listed {+ return params;+ }+ match params {+ Value::Object(mut m) => {+ m.insert("path".into(), json!(sel));+ Value::Object(m)+ }+ _ => json!({ "path": sel }),+ }+}+/// ⌘↩ / Ctrl+Enter (#306): load a path as a selection, like Photoshop with a Pen or Path/// Selection tool or a path selected in the Paths panel. A path being drawn with the Pen is/// finished first and loads; otherwise [`active_path_name`]. `params` may set feather, mode…@@ -825,6 +858,13 @@ pub fn paths_panel(app: &mut PhotocraftApp, ui: &mut egui::Ui) {});ui.painter().line_segment([r.left_bottom(), r.right_bottom()], Stroke::new(1.0, t.separator));}+ // Clicking the empty area deselects the path, as in Photoshop: new fill and+ // adjustment layers then take the selection as their mask instead (#1419).+ let rest = ui.available_rect_before_wrap();+ let rest = rest.intersect(Rect::from_min_size(rest.min, vec2(rest.width(), rest.height().min(4000.0))));+ if rest.is_positive() && ui.interact(rest, ui.id().with("paths-empty"), Sense::click()).clicked() {+ app.ui.selected_path = None;+ }},);ui.add_space(4.0);@@ -1004,6 +1044,59 @@ mod tests {assert_eq!((wp.subpaths[0].knots[0].anchor.x, wp.subpaths[0].knots[0].anchor.y), (30.0, 25.0));}+ /// #1419: Solid Color (and every new fill or adjustment layer) made while a path is selected+ /// in the Paths panel takes it as its vector mask; with the path deselected, the selection+ /// is its layer mask again.+ #[test]+ fn new_fill_layer_takes_the_selected_path_as_its_vector_mask() {+ let mut app = app();+ let layer = |app: &PhotocraftApp, r: Result<Value, String>| {+ let id = photocraft_doc::LayerId(r.unwrap()["layer"].as_u64().unwrap());+ app.session.active().unwrap().doc.layer(id).unwrap().clone()+ };+ // Drawing a work path with the Pen selects it.+ app.ui.tool = Tool::Pen;+ for (x, y) in [(20.0, 20.0), (120.0, 20.0), (120.0, 120.0)] {+ pen_down(&mut app, x, y);+ pen_up(&mut app);+ }+ pen_down(&mut app, 20.5, 20.5);+ assert_eq!(app.ui.selected_path.as_deref(), Some("work"));+ let wp = app.session.active().unwrap().doc.work_path.clone().unwrap();+ app.run("select.rect", json!({"x": 150, "y": 150, "width": 20, "height": 20})).unwrap();+ for id in ["layer.newFillLayer.solidColor", "layer.newFillLayer.gradient", "layer.newAdjustmentLayer.invert"] {+ app.ui.selected_path = Some("work".into());+ let r = app.run(id, json!({}));+ let l = layer(&app, r);+ assert_eq!(l.vector_mask.as_ref().map(|v| &v.path), Some(&wp), "{id}: the work path is the vector mask");+ assert!(l.mask.is_none(), "{id}: the path wins over the selection");+ // The new layer's vector mask is now the active path, not the work path.+ assert_eq!(app.ui.selected_path.as_deref(), Some("layer"), "{id}");+ }+ // So the next fill layer isn't masked by the work path again.+ let r = app.run("layer.newFillLayer.solidColor", json!({}));+ assert!(layer(&app, r).vector_mask.is_none());+ // A caller can opt out.+ let r = app.run("layer.newFillLayer.solidColor", json!({"path": null}));+ assert!(layer(&app, r).vector_mask.is_none());+ // A selected saved path is used.+ app.run("path.set", json!({"name": "Saved", "path": {"subpaths": [{"closed": true, "knots": [[0, 0], [9, 0], [9, 9]]}]}})).unwrap();+ app.ui.selected_path = Some("Saved".into());+ let saved = app.session.active().unwrap().doc.paths[0].path.clone();+ let r = app.run("layer.newFillLayer.solidColor", json!({}));+ assert_eq!(layer(&app, r).vector_mask.map(|v| v.path), Some(saved));+ // Deselected (or a stale name): the selection is the layer mask, no vector mask.+ for sel in [None, Some("Gone".to_string())] {+ app.ui.selected_path = sel;+ let r = app.run("layer.newFillLayer.solidColor", json!({}));+ let l = layer(&app, r);+ assert!(l.vector_mask.is_none() && l.mask.is_some());+ }+ // Make Work Path selects the new work path.+ app.run("select.toWorkPath", json!({"tolerance": 2.0})).unwrap();+ assert_eq!(app.ui.selected_path.as_deref(), Some("work"));+ }+/// #534: dragging in a shape's fill picker, opened from the Properties panel at the right edge/// of the window, keeps the picker in place (it flipped from side to side as its width/// followed the colour readouts, which moved it under the pointer).