PhotoCraft: An open-source, photo editor written by scratch in pure Rust
convert the background and match mask depth where they were missed
Omar Saidahmed2b5e857d924f
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex 2f0418712..041691367 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -339,7 +339,7 @@ pub(crate) fn selection_mask(doc: &Document) -> Result<Option<LayerMask>> {/// 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> {+pub(crate) 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)?;diff --git a/crates/engine/src/cutout_cmds.rs b/crates/engine/src/cutout_cmds.rsindex 2f6e2b70b..e7368dcc9 100644--- a/crates/engine/src/cutout_cmds.rs+++ b/crates/engine/src/cutout_cmds.rs@@ -66,7 +66,8 @@ fn run(s: &mut Session, p: &Value) -> Result<Value> {}}crate::extra_cmds::background_to_layer_for_mask(doc, id);- doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(LayerMask { surface: matting::region_surface(®ion), ..LayerMask::reveal_all() });+ let mask = crate::commands::mask_at_depth(LayerMask { surface: matting::region_surface(®ion), ..LayerMask::reveal_all() }, doc.depth)?;+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.mask = Some(mask);doc.selection = None;let b = region.bbox;Ok([b.x0, b.y0, b.width() as i32, b.height() as i32])diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rsindex c29186216..2ff3b48ed 100644--- a/crates/engine/src/extra_cmds.rs+++ b/crates/engine/src/extra_cmds.rs@@ -928,6 +928,7 @@ pub fn specs() -> Vec<CommandSpec> {gray};for id in ids {+ background_to_layer(doc, id);let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;l.effects = fx.clone();// Pass Through is a group's mode: a group's style pastes onto other layers asdiff --git a/crates/engine/src/frame_cmds.rs b/crates/engine/src/frame_cmds.rsindex 7a401594f..2ea953609 100644--- a/crates/engine/src/frame_cmds.rs+++ b/crates/engine/src/frame_cmds.rs@@ -72,8 +72,8 @@ fn frame_group(s: &mut Session, grouped: &Value) -> Result<Value> {crate::layer_multi_cmds::layer_bounds(d.doc.layer(gid).ok_or(EngineError::NoLayer(gid))?).filter(|r| !r.is_empty()).unwrap_or_else(|| d.doc.bounds());s.edit("Frame from Layers", |doc, _| {- let g = doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?;- g.mask = Some(clip_mask(rect));+ let mask = crate::commands::mask_at_depth(clip_mask(rect), doc.depth)?;+ doc.layer_mut(gid).ok_or(EngineError::NoLayer(gid))?.mask = Some(mask);Ok(())})?;Ok(json!({"layer": gid.0, "frame": [rect.x0, rect.y0, rect.width(), rect.height()]}))@@ -133,7 +133,8 @@ fn new_frame(s: &mut Session, p: &Value) -> Result<Value> {};let name = p.get("name").and_then(Value::as_str).map(str::to_string);let gid = s.edit("New Frame", |doc, active| {- let mask = if ellipse { ellipse_mask(rect, doc.bounds()) } else { clip_mask(rect.intersect(&doc.bounds())) };+ let mask =+ crate::commands::mask_at_depth(if ellipse { ellipse_mask(rect, doc.bounds()) } else { clip_mask(rect.intersect(&doc.bounds())) }, doc.depth)?;let name = name.unwrap_or_else(|| doc.next_layer_name("Frame"));let gid = match content {Some(id) => {diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rsindex 95b547685..6aea9d634 100644--- a/crates/engine/src/layer_style.rs+++ b/crates/engine/src/layer_style.rs@@ -894,6 +894,9 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result<Value> {crate::pattern_cmds::ensure_in_doc(doc, pat);}let mode = doc.mode;+ if !list.is_empty() {+ crate::extra_cmds::background_to_layer(doc, id);+ }let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;// The list's master switch (`layer.setEffectsVisible`, the Layers panel's "Effects" eye)// survives the edit: the dialog models per-effect state, not the switch (#3648). A layer@@ -916,6 +919,7 @@ fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {}// Colours in the document's mode, as Image › Mode keeps them.let fx = fx.in_mode(doc.mode);+ crate::extra_cmds::background_to_layer(doc, id);let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;// Adding or replacing one effect leaves the list's master switch alone (#3648); a fresh// effects list already has the default `enabled: true`, so a first effect still shows.diff --git a/crates/engine/src/vector_cmds.rs b/crates/engine/src/vector_cmds.rsindex 14579e595..6b0bc6495 100644--- a/crates/engine/src/vector_cmds.rs+++ b/crates/engine/src/vector_cmds.rs@@ -1405,7 +1405,8 @@ fn vector_mask_add(s: &mut Session, p: &Value, from_path: bool) -> Result<Value>if locked {return Err(EngineError::Other(format!("layer \"{}\" is locked", l.name)));}- l.vector_mask = Some(VectorMask::new(path));+ crate::extra_cmds::background_to_layer(doc, id);+ doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?.vector_mask = Some(VectorMask::new(path));Ok(())})?;vector_mask_info(s, id)diff --git a/crates/engine/tests/background_and_mask_depth.rs b/crates/engine/tests/background_and_mask_depth.rsnew file mode 100644index 000000000..2011205e6--- /dev/null+++ b/crates/engine/tests/background_and_mask_depth.rs@@ -0,0 +1,73 @@+use photocraft_color::SampleType;+use photocraft_engine::Session;+use serde_json::{Value, json};++const STYLES: [&str; 10] =+ ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay", "bevelEmboss", "satin"];+const VECTOR_MASKS: [&str; 3] = ["layer.vectorMask.add", "layer.vectorMask.revealAll", "layer.vectorMask.hideAll"];++fn background_only() -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 30})).unwrap();+ s+}++fn has_background(s: &Session) -> bool {+ s.active().unwrap().doc.background().is_some()+}++fn converts_and_undoes(cmd: &str, params: Value) {+ let mut s = background_only();+ s.execute(cmd, params).unwrap_or_else(|e| panic!("{cmd}: {e}"));+ assert!(!has_background(&s), "{cmd} left a Background carrying the change");+ s.execute("edit.undo", json!({})).unwrap();+ assert!(has_background(&s), "{cmd}: one undo restores the Background");+}++#[test]+fn layer_styles_and_vector_masks_turn_the_background_into_a_layer() {+ for kind in STYLES {+ converts_and_undoes(&format!("layer.layerStyle.{kind}"), json!({}));+ }+ for cmd in VECTOR_MASKS {+ converts_and_undoes(cmd, json!({}));+ }+ converts_and_undoes("layer.layerStyle.replace", json!({"effects": [{"kind": "stroke"}]}));+}++#[test]+fn clearing_a_style_keeps_the_background() {+ let mut s = background_only();+ s.execute("layer.layerStyle.replace", json!({"effects": []})).unwrap();+ assert!(has_background(&s));+}++fn mask_sample(s: &Session) -> SampleType {+ let st = s.active().unwrap();+ st.doc.walk().into_iter().find_map(|(_, _, l)| l.mask.as_ref().map(|m| m.surface.format().sample)).expect("a layer mask")+}++fn painted(depth: u32) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 40, "height": 30, "depth": depth})).unwrap();+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("paint.stroke", json!({"points": [[5, 10], [30, 10]], "size": 8, "hardness": 1.0, "color": "#ff0000"})).unwrap();+ s+}++#[test]+fn frame_and_remove_background_masks_match_the_document_depth() {+ for depth in [16, 32] {+ let want = if depth == 16 { SampleType::U16 } else { SampleType::F32 };+ for (cmd, params) in [+ ("layer.new.frameFromLayers", json!({})),+ ("layer.new.frame", json!({"x": 4, "y": 4, "width": 16, "height": 12})),+ ("layer.new.frame", json!({"x": 4, "y": 4, "width": 16, "height": 12, "shape": "ellipse"})),+ ("layer.removeBackground", json!({})),+ ] {+ let mut s = painted(depth);+ s.execute(cmd, params.clone()).unwrap_or_else(|e| panic!("{cmd} {params}: {e}"));+ assert_eq!(mask_sample(&s), want, "{cmd} {params} in a {depth}-bit document");+ }+ }+}