PhotoCraft: An open-source, photo editor written by scratch in pure Rust
New adjustment and fill layers take the active selection as their mask (#1250) (#1282)
Pathos09259df3a481ee50
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex f2e350561..eec47e95e 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -179,11 +179,19 @@ pub fn blend_from_str(s: &str) -> Option<BlendMode> {std::iter::once(BlendMode::PassThrough).chain(BlendMode::LAYER_MODES).find(|m| norm(m.label()) == want || norm(&format!("{m:?}")) == want)}+/// The active selection as the mask of a layer being created, or None without a selection.+/// Photoshop masks a new adjustment or fill layer with the selection, so the adjustment acts on+/// the selected area only (#1250); the selection itself stays, as Reveal Selection leaves it.+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> {let label = format!("New {} Layer", adj.label());let name = adj.label().to_string();let id = s.edit(&label, |doc, active| {- let l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj));+ let mut l = Layer::new(doc.next_layer_name(&name), LayerContent::Adjustment(adj));+ l.mask = selection_mask(doc);let id = doc.insert_above(*active, l);*active = Some(id);Ok(id)@@ -640,7 +648,8 @@ fn build() -> Vec<CommandSpec> {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 l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3]))));+ 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)@@ -668,7 +677,9 @@ fn build() -> Vec<CommandSpec> {style,reverse,);- let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)));+ let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));+ l.mask = selection_mask(doc);+ let id = doc.insert_above(*active, l);*active = Some(id);Ok(id)})?;diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rsindex 09c18f7d5..31e7b0eb8 100644--- a/crates/engine/src/gradient_fill_cmds.rs+++ b/crates/engine/src/gradient_fill_cmds.rs@@ -13,7 +13,7 @@use photocraft_color::Color;use photocraft_compose::gradient_fill as gf;-use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId, LayerMask};+use photocraft_doc::{Document, Fill, GradientStyle, Layer, LayerContent, LayerId};use photocraft_geom::Rect;use serde_json::{Value, json};@@ -307,9 +307,7 @@ pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result<Layer> {let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));l.opacity = opacity;l.blend = blend;- if let Some(sel) = &doc.selection {- l.mask = Some(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() });- }+ l.mask = crate::commands::selection_mask(doc);Ok(l)}diff --git a/crates/engine/src/pattern_cmds.rs b/crates/engine/src/pattern_cmds.rsindex 9961dc361..e8e537b8c 100644--- a/crates/engine/src/pattern_cmds.rs+++ b/crates/engine/src/pattern_cmds.rs@@ -307,7 +307,8 @@ fn new_fill_layer(s: &mut Session, p: &Value) -> Result<Value> {let id = s.edit("New Pattern Fill Layer", |doc, active| {ensure_in_doc(doc, &pat);let fill = Fill::Pattern { name: pat.name.clone(), scale, id: pat.id.clone(), angle, link, phase };- let l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill));+ let mut l = Layer::new(doc.next_layer_name("Pattern Fill"), LayerContent::Fill(fill));+ l.mask = crate::commands::selection_mask(doc);let id = doc.insert_above(*active, l);*active = Some(id);Ok(id)diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 754ca9077..0d1460272 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -122,6 +122,55 @@ fn adjustment_layers_change_composite() {assert_eq!(px(&mut s, 3, 3), vec![1.0, 1.0, 1.0, 1.0]);}+#[test]+fn new_adjustment_and_fill_layers_are_masked_by_the_selection() {+ // #1250: as in Photoshop, a new adjustment or fill layer made while a selection is active+ // gets the selection as its layer mask, so it acts on the selected area only.+ for depth in [8, 16, 32] {+ // (command, params, whether it turns the white canvas black inside the selection)+ for (id, params, blackens) in [+ ("layer.newAdjustmentLayer.invert", json!({}), true),+ ("layer.newAdjustmentLayer.hueSaturation", json!({"hue": 40, "saturation": 20}), false),+ ("layer.newFillLayer.solidColor", json!({"color": "#000000"}), true),+ ("layer.newFillLayer.gradient", json!({"from": "#000000", "to": "#000000"}), true),+ ("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"}), false),+ ] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth})).unwrap();+ s.execute("select.rect", json!({"x": 8, "y": 8, "width": 16, "height": 16})).unwrap();+ let layer = LayerId(s.execute(id, params).unwrap()["layer"].as_u64().unwrap());+ let d = s.active().unwrap();+ let mask = d.doc.layer(layer).unwrap().mask.as_ref().unwrap_or_else(|| panic!("{id} at {depth}-bit: no layer mask"));+ assert_eq!(mask.value(10, 10), 1.0, "{id} at {depth}-bit: the mask hides the selected area");+ assert_eq!(mask.value(2, 2), 0.0, "{id} at {depth}-bit: the mask reveals outside the selection");+ assert!(mask.linked && mask.enabled, "{id}");+ // The selection stays, as after Layer › Layer Mask › Reveal Selection.+ assert!(d.doc.selection.is_some(), "{id} dropped the selection");+ // The white canvas is untouched outside the selection.+ assert_eq!(px(&mut s, 2, 2), vec![1.0, 1.0, 1.0, 1.0], "{id} at {depth}-bit changed pixels outside the selection");+ if blackens {+ assert_eq!(px(&mut s, 10, 10)[..3], [0.0, 0.0, 0.0][..], "{id} at {depth}-bit: no effect inside the selection");+ }+ s.execute("edit.undo", json!({})).unwrap();+ assert!(s.active().unwrap().doc.layer(layer).is_none(), "{id}: undo keeps the layer");+ }+ }+}++#[test]+fn new_adjustment_and_fill_layers_have_no_mask_without_a_selection() {+ let mut s = session_with_doc();+ for (id, params) in [+ ("layer.newAdjustmentLayer.invert", json!({})),+ ("layer.newFillLayer.solidColor", json!({"color": "#000000"})),+ ("layer.newFillLayer.gradient", json!({})),+ ("layer.newFillLayer.pattern", json!({"pattern": "Checkerboard"})),+ ] {+ let layer = LayerId(s.execute(id, params).unwrap()["layer"].as_u64().unwrap());+ assert!(s.active().unwrap().doc.layer(layer).unwrap().mask.is_none(), "{id} got a mask with no selection");+ }+}+#[test]fn every_adjustment_command_runs() {let mut s = session_with_doc();