Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

fix(engine): create new layer masks at the document depth (#3359)

piero-8323417a60b68c
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index f964c620c..60db05e4a 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -256,8 +256,19 @@ pub fn blend_from_str(s: &str) -> Option<BlendMode> {
/// 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() })
+pub(crate) fn selection_mask(doc: &Document) -> Result<Option<LayerMask>> {
+ doc.selection.as_ref().map(|sel| mask_at_depth(LayerMask { surface: sel.clone(), ..LayerMask::reveal_all() }, doc.depth)).transpose()
+}
+
+/// New pixel masks use the document's depth, as PSD saves/imports do. Otherwise a later soft
+/// brush stroke quantizes differently depending on whether the document reopened as PSD or
+/// native. Converting a selection keeps its coverage and does not alter the selection itself.
+fn mask_at_depth(mut mask: LayerMask, depth: SampleType) -> Result<LayerMask> {
+ let format = mask.surface.format().with_sample(depth);
+ if mask.surface.format() != format {
+ mask.surface = mask.surface.try_convert(format)?;
+ }
+ Ok(mask)
}
/// Mask a fill or adjustment layer being created, as Photoshop does: the path selected in the
@@ -276,7 +287,7 @@ pub(crate) fn mask_new_layer(doc: &Document, l: &mut Layer, p: &Value, cmd: &str
};
match path {
Some(path) => l.vector_mask = Some(photocraft_doc::VectorMask::new(path)),
- None => l.mask = Some(selection_mask(doc).unwrap_or_else(LayerMask::reveal_all)),
+ None => l.mask = Some(mask_at_depth(selection_mask(doc)?.unwrap_or_else(LayerMask::reveal_all), doc.depth)?),
}
Ok(())
}
@@ -1339,6 +1350,7 @@ fn arrange(s: &mut Session, p: &Value, delta: i32) -> Result<Value> {
fn set_mask(s: &mut Session, p: &Value, label: &str, mask: Option<LayerMask>) -> Result<Value> {
let ids = if mask.is_some() { crate::layer_multi_cmds::mask_targets(s, p)? } else { vec![layer_param(s, p)?] };
s.edit(label, |doc, _| {
+ let mask = mask.clone().map(|mask| mask_at_depth(mask, doc.depth)).transpose()?;
for id in &ids {
if mask.is_some() {
crate::extra_cmds::background_to_layer_for_mask(doc, *id);
diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rs
index ac6005e66..041d31169 100644
--- a/crates/engine/src/gradient_fill_cmds.rs
+++ b/crates/engine/src/gradient_fill_cmds.rs
@@ -308,7 +308,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;
- l.mask = crate::commands::selection_mask(doc);
+ l.mask = crate::commands::selection_mask(doc)?;
Ok(l)
}
diff --git a/crates/engine/src/vector_cmds/tests.rs b/crates/engine/src/vector_cmds/tests.rs
index dfb8205aa..00cb58d8c 100644
--- a/crates/engine/src/vector_cmds/tests.rs
+++ b/crates/engine/src/vector_cmds/tests.rs
@@ -638,8 +638,7 @@ fn rasterizing_a_vector_mask_keeps_what_the_masks_show() {
s.execute("layer.rasterize.vectorMask", json!({})).unwrap();
let l = doc(&s).layer(id).unwrap();
assert!(l.vector_mask.is_none() && l.mask.is_some(), "{what}");
- // An integer mask stores the soft values rounded to its depth (a mask made from a
- // selection is 8-bit at every document depth).
+ // An integer mask stores the soft values rounded to its depth.
let tol = match l.mask.as_ref().unwrap().surface.format().sample {
photocraft_color::SampleType::U8 => 1.5 / 255.0,
_ => 1e-3,
diff --git a/crates/engine/tests/layer_mask_depth.rs b/crates/engine/tests/layer_mask_depth.rs
new file mode 100644
index 000000000..082761286
--- /dev/null
+++ b/crates/engine/tests/layer_mask_depth.rs
@@ -0,0 +1,140 @@
+//! A native document and its PSD must quantize the same later mask edit alike.
+
+use photocraft_color::{ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{Document, LayerMask};
+use photocraft_engine::Session;
+use photocraft_raster::Surface;
+use serde_json::json;
+
+fn session(depth: u64, mode: &str) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 64, "height": 48, "depth": depth, "mode": mode})).unwrap();
+ s
+}
+
+fn mask(doc: &Document) -> &LayerMask {
+ doc.walk().into_iter().find_map(|(_, _, l)| l.mask.as_ref()).unwrap()
+}
+
+#[test]
+fn newly_created_layer_masks_follow_document_depth() {
+ for (depth, sample) in [(8, SampleType::U8), (16, SampleType::U16), (32, SampleType::F32)] {
+ for mode in ["rgb", "gray", "cmyk", "lab"] {
+ for (command, selected) in [
+ ("layer.newAdjustmentLayer.invert", false),
+ ("layer.newAdjustmentLayer.invert", true),
+ ("layer.newFillLayer.solidColor", false),
+ ("layer.newFillLayer.solidColor", true),
+ ("layer.layerMask.revealAll", false),
+ ("layer.layerMask.hideAll", false),
+ ("layer.layerMask.revealSelection", true),
+ ] {
+ let mut s = session(depth, mode);
+ if selected {
+ s.execute("select.rect", json!({"x": 8, "y": 6, "width": 40, "height": 32, "antiAlias": false})).unwrap();
+ }
+ let before = s.active().unwrap().doc.clone();
+ let history = s.active().unwrap().history.past_len();
+ s.execute(command, json!({"color": "#000000"})).unwrap();
+ let d = s.active().unwrap();
+ let m = mask(&d.doc);
+ assert_eq!(m.surface.format(), PixelFormat::new(ColorMode::Grayscale, sample, false), "{command}, {depth}-bit {mode}");
+ assert!(m.enabled && m.linked);
+ assert_eq!((m.density, m.feather), (1.0, 0.0));
+ let white = if command.ends_with("hideAll") { 0.0 } else { 1.0 };
+ assert_eq!(m.value(20, 20), white);
+ if selected {
+ assert_eq!(m.value(0, 0), 0.0);
+ assert_eq!(d.doc.selection, before.selection, "the selection is unchanged");
+ } else {
+ assert_eq!(m.surface.tile_count(), 0, "uniform masks stay sparse");
+ assert_eq!(m.value(-300_000, 300_000), white);
+ }
+ assert_eq!(d.history.past_len(), history + 1);
+ let after = d.doc.clone();
+ s.undo();
+ assert_eq!(*s.active().unwrap().doc, *before);
+ s.redo();
+ assert_eq!(*s.active().unwrap().doc, *after);
+ }
+ }
+ }
+}
+
+#[test]
+fn soft_mask_edits_match_after_native_and_psd_reopen() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth, "rgb");
+ s.execute("select.rect", json!({"x": 8, "y": 6, "width": 40, "height": 32, "antiAlias": false})).unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#000000"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let native = photocraft_format::save_to_bytes(&before, &Default::default()).unwrap();
+ let psd = photocraft_io::export(&before, "psd", &Default::default()).unwrap();
+ assert!(psd.warnings.is_empty(), "{:?}", psd.warnings);
+ let mut branches = Vec::new();
+ for reopened in [photocraft_format::load_from_bytes(&native).unwrap(), photocraft_io::import("mask.psd", &psd.bytes).unwrap().document] {
+ assert_eq!(mask(&reopened).surface.format(), mask(&before).surface.format(), "{depth}-bit mask depth survives reopening");
+ assert_eq!(mask(&reopened).surface.read_region(before.bounds()), mask(&before).surface.read_region(before.bounds()));
+ assert_eq!(photocraft_compose::flatten(&reopened), photocraft_compose::flatten(&before));
+ let layer = reopened.walk().into_iter().find_map(|(_, _, l)| l.mask.as_ref().map(|_| l.id.0)).unwrap();
+ let mut edited = Session::new();
+ edited.add_document(reopened, None);
+ let undo_doc = edited.active().unwrap().doc.clone();
+ edited
+ .execute(
+ "paint.stroke",
+ json!({"layer": layer, "target": "mask", "color": "#000000", "points": [[20,18,1], [36,30,1]], "size": 18, "hardness": 0.4, "seed": 17}),
+ )
+ .unwrap();
+ let changed = edited.active().unwrap().doc.clone();
+ let values = mask(&changed).surface.read_region(changed.bounds());
+ assert!(values.iter().any(|v| *v > 0.0 && *v < 1.0), "a soft mask was painted");
+ edited.undo();
+ assert_eq!(*edited.active().unwrap().doc, *undo_doc);
+ edited.redo();
+ assert_eq!(*edited.active().unwrap().doc, *changed);
+ branches.push(changed);
+ }
+ let a = mask(&branches[0]).surface.read_region(before.bounds());
+ let b = mask(&branches[1]).surface.read_region(before.bounds());
+ let changed = a.iter().zip(&b).filter(|(a, b)| a != b).count();
+ let worst = a.iter().zip(&b).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max);
+ assert_eq!(changed, 0, "{depth}-bit mask edit depends on the save format (worst coverage difference {worst})");
+ assert_eq!(photocraft_compose::flatten(&branches[0]), photocraft_compose::flatten(&branches[1]), "{depth}-bit composite depends on the save format");
+ if depth > 8 {
+ assert!(a.iter().any(|v| (v * 255.0 - (v * 255.0).round()).abs() > 0.01), "{depth}-bit mask edits retain sub-8-bit coverage");
+ }
+ }
+}
+
+#[test]
+fn mask_creation_preserves_selection_coverage_and_existing_masks() {
+ for depth in [8, 16, 32] {
+ for command in ["layer.newAdjustmentLayer.invert", "layer.layerMask.revealSelection", "gradient.fill.create"] {
+ let mut s = session(depth, "rgb");
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.edit("synthetic coverage", |doc, _| {
+ let mut selection = Surface::with_default(PixelFormat::GRAY8, &[1.0]);
+ selection.write_region(photocraft_geom::Rect::new(0, 0, 16, 16), &(0..256).map(|i| i as f32 / 255.0).collect::<Vec<_>>());
+ doc.selection = Some(selection);
+ let mut existing = LayerMask::reveal_all();
+ existing.surface = Surface::with_default(PixelFormat::new(ColorMode::Grayscale, SampleType::F32, false), &[0.123456]);
+ doc.layers[0].mask = Some(existing);
+ Ok(())
+ })
+ .unwrap();
+ let before = s.active().unwrap().doc.clone();
+ s.execute(command, json!({"from": [0, 0], "to": [64, 48]})).unwrap();
+ let after = &s.active().unwrap().doc;
+ let added = after.layer(s.active().unwrap().active_layer.unwrap()).unwrap().mask.as_ref().unwrap();
+ assert_eq!(
+ added.surface.read_region(after.bounds()),
+ before.selection.as_ref().unwrap().read_region(before.bounds()),
+ "{depth}-bit coverage is unchanged"
+ );
+ assert_eq!(after.selection, before.selection);
+ assert_eq!(after.layers[0].mask, before.layers[0].mask, "creating a mask does not requantize an existing mask");
+ }
+ }
+}