diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index ab2c48008bf..f5f9dd7109b 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -579,6 +579,8 @@ fn edits_mask(id: &str) -> bool { id.strip_prefix("image.adjustments.").is_some_and(|kind| crate::adjust_params::default_for(kind, ColorMode::Rgb).is_ok()) || crate::filters::params_for(id, &Value::Null).is_some() || id == "edit.fill" + // Copying a targeted mask (#2928). + || id == "edit.copy" || crate::fill_key_cmds::IDS.contains(&id) } @@ -605,8 +607,8 @@ fn routed(id: &str) -> bool { || id.starts_with("image.adjustments.") || matches!(id, "paint.stroke" | "paint.pencil" | "paint.bucket" | "paint.gradient" | "paint.mixerBrush" | "edit.fill" | "image.applyImage") || crate::fill_key_cmds::IDS.contains(&id) - // Pasting into a targeted mask or channel (#1035). - || matches!(id, "edit.paste" | "edit.pasteSpecial.pasteInPlace" | "edit.pasteSpecial.pasteInto" | "edit.pasteSpecial.pasteOutside") + // Pasting into a targeted mask or channel (#1035); Copy takes a targeted mask (#2928). + || matches!(id, "edit.copy" | "edit.paste" | "edit.pasteSpecial.pasteInPlace" | "edit.pasteSpecial.pasteInto" | "edit.pasteSpecial.pasteOutside") // Edit › Transform › Rotate/Flip turn a targeted mask or channel (#2835). || matches!( id, diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index 4fc878364ac..ce172ea2786 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -1,7 +1,7 @@ //! Everyday Photoshop commands: clipboard (Cut/Copy/Copy Merged/Paste/Paste in Place), Layer via //! Copy/Cut, Merge Visible, Auto Tone/Contrast/Color, Toggle Last State and Transform Again. -use photocraft_color::PixelFormat; +use photocraft_color::{ColorMode, PixelFormat}; use photocraft_doc::adjust::LevelsChannel; use photocraft_doc::{Adjustment, Document, Layer, LayerContent, LayerId}; use photocraft_geom::Rect; @@ -189,6 +189,48 @@ fn copy(s: &mut Session, merged: bool) -> Result { Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()]})) } +/// Copy with the layer mask targeted (`"target":"mask"`, #2928): the mask's values as a +/// grayscale clip, inside the selection or the whole canvas — an untouched mask copies at its +/// default value, so a plain Reveal All / Hide All mask transfers too. Paste then writes into +/// another layer's mask (targeted, #1035), in this or another document. +fn copy_mask(s: &mut Session) -> Result { + let d = s.active().ok_or(EngineError::NoDocument)?; + let canvas = d.doc.bounds(); + let id = d.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?; + let mask = d.doc.layer(id).ok_or(EngineError::NoLayer(id))?.mask.as_ref().ok_or_else(|| EngineError::Other("the active layer has no layer mask".into()))?; + let sel = d.doc.selection.as_ref(); + let area = sel.map_or(canvas, |m| m.content_bounds().intersect(&canvas)); + if area.is_empty() { + return Err(EngineError::Other("Could not copy: the selected area is empty".into())); + } + let n = mask.surface.format().channels().max(1); + let values = crate::allocation::read_region(&mask.surface, area, "copying the mask")?; + let len = values + .len() + .checked_div(n) + .and_then(|pixels| pixels.checked_mul(2)) + .ok_or_else(|| EngineError::Other("not enough memory for copying the mask (requested size overflowed); the document was not changed".into()))?; + let cover = sel.map(|m| (m.read_region(area), m.format().channels().max(1))); + let mut px = crate::allocation::filled(len, 0.0, "copying the mask")?; + for (i, p) in values.chunks_exact(n).enumerate() { + px[i * 2] = p.first().copied().unwrap_or(0.0); + px[i * 2 + 1] = cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)); + } + let fmt = PixelFormat::new(ColorMode::Grayscale, mask.surface.format().sample, true); + let mut surface = Surface::new(fmt); + surface + .try_write_region(area, &px) + .map_err(|e| EngineError::Other(format!("not enough memory while copying the mask ({e}); the document was not changed")))?; + surface.prune(); + let bounds = surface.content_bounds(); + if bounds.is_empty() { + return Err(EngineError::Other("Could not copy: the selected area is empty".into())); + } + let b = bounds; + s.clipboard = Some(Clip { surface, bounds: b, layers: None }); + Ok(json!({"bounds": [b.x0, b.y0, b.width(), b.height()], "target": "mask"})) +} + fn clear_selected(doc: &mut Document, id: LayerId, background: [f32; 4]) -> Result<()> { let sel = doc.selection.clone(); let canvas = doc.bounds(); @@ -650,12 +692,23 @@ pub fn specs() -> Vec { s.edit("Cut Pixels", |doc, _| clear_selected(doc, id, bg))?; Ok(r) }), - spec!("edit.copy", "Copy", &["Edit"], Some("Cmd+C"), "{} (a targeted colour or alpha channel copies that channel, as grayscale)", can_copy, |s, _| { - match crate::channel_clip::copy(s)? { - Some(r) => Ok(r), - None => copy(s, false), + spec!( + "edit.copy", + "Copy", + &["Edit"], + Some("Cmd+C"), + r##"{"target":"mask"? = the targeted mask, copied as grayscale (#2928)} (a targeted colour or alpha channel copies that channel, as grayscale)"##, + can_copy, + |s, p| { + if crate::commands::is_mask_target(p) { + return copy_mask(s); + } + match crate::channel_clip::copy(s)? { + Some(r) => Ok(r), + None => copy(s, false), + } } - }), + ), spec!("edit.copyMerged", "Copy Merged", &["Edit"], Some("Cmd+Shift+C"), "{}", has_doc, |s, _| copy(s, true)), spec!( "edit.paste", @@ -1002,6 +1055,95 @@ mod tests { } } + #[test] + fn copy_with_the_mask_targeted_takes_the_mask_as_grayscale() { + for depth in [8, 16, 32] { + let (mut s, _, m) = mask_target_session(depth); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + let steps = s.active().unwrap().history.past_len(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "{depth}-bit: a mask copies whole, as in Photoshop"); + assert_eq!(s.active().unwrap().history.past_len(), steps, "{depth}-bit: copy adds no history step"); + let clip = s.clipboard.clone().unwrap(); + let px = clip.surface.rgba(10, 10); + assert!((px[0] - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: {} vs 0.75", px[0]); + assert!(clip.surface.rgba(30, 30)[0] < 0.01, "{depth}-bit: the hidden area copies as black"); + assert!(px[3] > 0.99, "{depth}-bit: the copy is opaque"); + // Paste it into another layer's reveal-all mask: it replaces that mask (the request + // in #2928): the square, and the black around it, land. + let m2 = LayerId(s.execute("layer.new.layer", json!({"name": "m2"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, m2, 10, 10) - 0.75).abs() < 2.0 / 255.0, "{depth}-bit: the copied mask lands"); + assert!(mask_at(&s, m2, 30, 30) < 0.01, "{depth}-bit: the copied black replaces the reveal-all"); + } + } + + #[test] + fn an_untouched_mask_copies_the_whole_canvas_at_its_default() { + let (mut s, _, _) = mask_target_session(8); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([0, 0, 40, 40]), "a plain Reveal All mask still transfers"); + assert!(s.clipboard.clone().unwrap().surface.rgba(20, 20)[0] > 0.99); + } + + #[test] + fn mask_copy_takes_only_the_selection() { + let (mut s, _, m) = mask_target_session(8); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + s.execute("select.rect", json!({"x": 8, "y": 8, "width": 4, "height": 4})).unwrap(); + let r = s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + assert_eq!(r["bounds"], json!([8, 8, 4, 4])); + let clip = s.clipboard.clone().unwrap(); + assert!((clip.surface.rgba(9, 9)[0] - 0.75).abs() < 2.0 / 255.0); + assert!(clip.surface.rgba(5, 5)[3] < 0.01, "nothing outside the selection"); + } + + #[test] + fn mask_copy_needs_a_mask_and_fails_gracefully() { + let mut s = Session::new(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "no document"); + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_err(), "the layer has no mask"); + assert!(s.clipboard.is_none(), "a refused copy leaves the clipboard alone"); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(s.execute("edit.copy", json!({"target": "mask"})).is_ok()); + // An adjustment layer has no pixels of its own: Copy is only enabled while its mask is + // targeted (#2928). + s.execute("file.new", json!({"width": 20, "height": 20})).unwrap(); + let a = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].as_u64().unwrap(); + s.execute("layer.select", json!({"layer": a})).unwrap(); + assert!(!s.is_enabled("edit.copy"), "no pixels to copy"); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + assert!(s.is_enabled_with("edit.copy", &json!({"target": "mask"})), "the mask can be copied"); + } + + #[test] + fn a_copied_mask_travels_to_another_document() { + let (mut s, _, m) = mask_target_session(8); + s.edit("paint mask", |doc, _| { + doc.layer_mut(m).unwrap().mask.as_mut().unwrap().surface.fill_rect(Rect::new(6, 6, 16, 12), &[0.75]); + Ok(()) + }) + .unwrap(); + s.execute("edit.copy", json!({"target": "mask"})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 40})).unwrap(); + let n = LayerId(s.execute("layer.new.layer", json!({})).unwrap()["layer"].as_u64().unwrap()); + s.execute("layer.layerMask.revealAll", json!({})).unwrap(); + s.execute("edit.pasteSpecial.pasteInPlace", json!({"target": "mask"})).unwrap(); + assert!((mask_at(&s, n, 10, 10) - 0.75).abs() < 2.0 / 255.0, "the mask arrived in the second document"); + assert!(mask_at(&s, n, 30, 30) < 0.01, "it replaced the reveal-all mask there"); + } + #[test] fn paste_follows_the_mask_view_and_is_placed_like_a_paste() { let (mut s, src, m) = mask_target_session(8); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d3dc82a73a3..8abe332a7ac 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -2455,6 +2455,35 @@ mod clipboard_tests { assert!(h.state().session.clipboard.is_none()); } + /// #2928: with the layer mask targeted, ⌘C copies the mask's values as grayscale, not the + /// layer's pixels — so ⌘V (targeting another layer's mask, #1035) moves the mask itself. + #[test] + fn copy_with_the_mask_targeted_copies_the_mask_not_the_pixels() { + let (os, reads) = (OsClip::default(), Arc::default()); + let mut app = app_with_os_clipboard(&os, &reads); + app.run("layer.new.layer", serde_json::json!({})).unwrap(); + app.run("layer.layerMask.hideAll", serde_json::json!({})).unwrap(); + // Black pixels, a white square in the mask: the copy must carry the mask. + app.run("select.all", serde_json::json!({})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#000000"})).unwrap(); + app.run("select.rect", serde_json::json!({"x": 4, "y": 4, "width": 8, "height": 8})).unwrap(); + app.run("edit.fill", serde_json::json!({"color": "#ffffff", "target": "mask"})).unwrap(); + app.run("select.deselect", serde_json::json!({})).unwrap(); + app.ui.mask_target = true; + crate::menus::invoke(&mut app, &egui::Context::default(), "edit.copy", serde_json::json!({})).unwrap(); + let clip = app.session.clipboard.clone().expect("the mask was copied"); + let st = app.session.active().unwrap(); + let (w, h) = (st.doc.size.width as i32, st.doc.size.height as i32); + assert_eq!( + [clip.bounds.x0, clip.bounds.y0, clip.bounds.width() as i32, clip.bounds.height() as i32], + [0, 0, w, h], + "the mask, whole — not the black pixels" + ); + let px = clip.surface.rgba(6, 6); + assert!(px[0] > 0.99 && px[3] > 0.99, "white mask values: {px:?}"); + assert!(clip.surface.rgba(20, 20)[0] < 0.01, "the hidden area copies as black"); + } + /// #1035: with the layer mask targeted (its thumbnail clicked), ⌘V pastes the clipboard's /// luminosity into the mask instead of making a layer. #[test]