Skip to content

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

Copy and paste a single channel from the Channels panel (#2307) (#2695)

Fabian Ghenof96198fe49d3d
diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rs
new file mode 100644
index 000000000..a2213b454
--- /dev/null
+++ b/crates/engine/src/channel_clip.rs
@@ -0,0 +1,123 @@
+//! Copy and Paste with one channel targeted in the Channels panel (#2307), as in Photoshop.
+//!
+//! - Copy with a colour channel (Red, Green, Blue, …) or an alpha channel targeted copies that
+//! channel's values as a grayscale clip, instead of the whole layer.
+//! - Paste with a colour channel targeted writes the clip's luminosity into that channel of the
+//! active layer, instead of making a new layer. The other channels and the layer's transparency
+//! stay as they are. Pasting into an alpha channel, a layer mask or the Quick Mask goes through
+//! [`crate::edit_cmds::paste_to_target`].
+
+use photocraft_color::{ColorMode, PixelFormat};
+use photocraft_doc::Layer;
+use photocraft_raster::Surface;
+use serde_json::{Value, json};
+
+use crate::channel_cmds::ChannelTarget;
+use crate::edit_cmds::Clip;
+use crate::{EngineError, Result, Session};
+
+/// The colour channel a paste writes into: the Channels panel targets one and the params name no
+/// other target.
+pub(crate) fn paste_color_target(s: &Session, p: &Value) -> Option<usize> {
+ if p.get("target").is_some() {
+ return None;
+ }
+ match s.active()?.channel_view.target {
+ ChannelTarget::Color(k) => Some(k),
+ _ => None,
+ }
+}
+
+/// Copy the targeted colour or alpha channel as a grayscale clip, inside the selection (or the
+/// whole canvas). `Ok(None)` when no single channel is targeted: Copy copies the layer.
+pub(crate) fn copy(s: &mut Session) -> Result<Option<Value>> {
+ let Some(d) = s.active() else { return Ok(None) };
+ let doc = &d.doc;
+ let canvas = doc.bounds();
+ // The surface the values come from, and which of its samples is the channel.
+ let (src, k) = match d.channel_view.target {
+ ChannelTarget::Composite => return Ok(None),
+ ChannelTarget::Color(k) => {
+ let id = d.active_layer.ok_or_else(|| EngineError::Other("no active layer".into()))?;
+ let surf = doc.layer(id).and_then(Layer::surface).ok_or_else(|| EngineError::Other("the active layer has no pixels".into()))?;
+ (surf, k)
+ }
+ ChannelTarget::Alpha(i) => {
+ let c = doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i} (document has {})", doc.channels.len())))?;
+ (&c.surface, 0)
+ }
+ };
+ let n = src.format().channels();
+ if k >= n {
+ return Err(EngineError::Other(format!("no colour channel {k} in this layer")));
+ }
+ let sel = 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 fmt = PixelFormat::new(ColorMode::Grayscale, doc.pixel_format().sample, true);
+ let values = src.read_region(area);
+ let cover = sel.map(|m| (m.read_region(area), m.format().channels().max(1)));
+ let mut px = Vec::with_capacity(values.len() / n * 2);
+ for (i, p) in values.chunks_exact(n).enumerate() {
+ px.push(p.get(k).copied().unwrap_or(0.0));
+ px.push(cover.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0)));
+ }
+ let mut surface = Surface::new(fmt);
+ surface.write_region(area, &px);
+ surface.prune();
+ let bounds = surface.content_bounds();
+ if bounds.is_empty() {
+ return Err(EngineError::Other("Could not copy: the selected area is empty".into()));
+ }
+ s.clipboard = Some(Clip { surface, bounds });
+ Ok(Some(json!({"bounds": [bounds.x0, bounds.y0, bounds.width(), bounds.height()], "channel": k})))
+}
+
+/// Paste the clip's luminosity into colour channel `k` of the active layer, placed as a paste
+/// places it. The clip's transparency, and `limit` (Paste Into / Outside), let the old values show
+/// through. One history step.
+pub(crate) fn paste(s: &mut Session, p: &Value, k: usize, in_place: bool, limit: Option<&Surface>, label: &str) -> Result<Value> {
+ let clip = s.clipboard.clone().ok_or_else(|| EngineError::Other("the clipboard is empty".into()))?;
+ 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 (dx, dy) = crate::edit_cmds::paste_offset(&clip, canvas, p, in_place);
+ let src = crate::edit_cmds::shifted(&clip.surface, dx, dy);
+ let area = src.content_bounds().intersect(&canvas);
+ s.edit(label, |doc, _| {
+ let surf = crate::commands::paint_surface(doc, id, &Value::Null)?;
+ let n = surf.format().channels();
+ if k >= n {
+ return Err(EngineError::Other(format!("no colour channel {k} in this layer")));
+ }
+ if !area.is_empty() {
+ let mut rgba = vec![[0.0f32; 4]; area.width() as usize * area.height() as usize];
+ src.read_rgba_into(area, &mut rgba);
+ let weight = limit.map(|m| (m.read_region(area), m.format().channels().max(1)));
+ let mut px = surf.read_region(area);
+ for (i, (dst, s)) in px.chunks_exact_mut(n).zip(&rgba).enumerate() {
+ let w = s[3] * weight.as_ref().map_or(1.0, |(m, mk)| m.get(i * mk).copied().unwrap_or(0.0));
+ let v = photocraft_color::convert::rgb_to_gray([s[0], s[1], s[2]]);
+ if let Some(c) = dst.get_mut(k) {
+ *c += (v - *c) * w.clamp(0.0, 1.0);
+ }
+ }
+ surf.write_region(area, &px);
+ surf.prune();
+ }
+ doc.selection = None;
+ Ok(())
+ })?;
+ Ok(json!({"layer": id.0, "channel": k, "offset": [dx, dy]}))
+}
+
+/// Copy reads only: with an alpha channel targeted it needs no pixel layer.
+pub(crate) fn copies_alpha_channel(s: &Session) -> bool {
+ s.active().is_some_and(|st| matches!(st.channel_view.target, ChannelTarget::Alpha(i) if i < st.doc.channels.len()))
+}
+
+#[cfg(test)]
+#[path = "channel_clip/tests.rs"]
+mod tests;
diff --git a/crates/engine/src/channel_clip/tests.rs b/crates/engine/src/channel_clip/tests.rs
new file mode 100644
index 000000000..661728b58
--- /dev/null
+++ b/crates/engine/src/channel_clip/tests.rs
@@ -0,0 +1,130 @@
+use super::*;
+use photocraft_color::ColorMode;
+use photocraft_geom::Rect;
+
+const W: i32 = 40;
+const H: i32 = 20;
+
+/// A white document whose left half is #336699: red 0.2, green 0.4, blue 0.6 there.
+fn session(depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": W, "height": H, "depth": depth})).unwrap();
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap();
+ s.execute("edit.fill", json!({"color": "#336699"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s
+}
+
+fn px(s: &Session, x: i32, y: i32) -> Vec<f32> {
+ let d = s.active().unwrap();
+ d.doc.layer(d.active_layer.unwrap()).unwrap().surface().unwrap().pixel(x, y)
+}
+
+fn layers(s: &Session) -> usize {
+ s.active().unwrap().doc.walk().len()
+}
+
+fn near(a: &[f32], b: &[f32]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3)
+}
+
+#[test]
+fn copy_red_paste_into_blue() {
+ for depth in [8, 16, 32] {
+ let mut s = session(depth);
+ let (left, right) = (px(&s, 5, 5), px(&s, 30, 5));
+ s.execute("channel.target", json!({"channel": "red"})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ let clip = s.clipboard.as_ref().unwrap();
+ assert_eq!(clip.surface.format().mode, ColorMode::Grayscale, "depth {depth}: a channel copies as grayscale");
+ assert_eq!(clip.bounds, Rect::new(0, 0, W, H), "no selection: the whole channel");
+ let n = layers(&s);
+ s.execute("channel.target", json!({"channel": "blue"})).unwrap();
+ s.execute("edit.paste", json!({})).unwrap();
+ assert_eq!(layers(&s), n, "depth {depth}: no new layer");
+ assert!(near(&px(&s, 5, 5), &[left[0], left[1], left[0], 1.0]), "depth {depth}: blue = old red, {:?}", px(&s, 5, 5));
+ assert!(near(&px(&s, 30, 5), &right));
+ assert!(s.active().unwrap().doc.selection.is_none());
+ s.undo();
+ assert!(near(&px(&s, 5, 5), &left), "depth {depth}: one undoable step");
+ }
+}
+
+#[test]
+fn alpha_channels_copy_and_paste_into_colour_channels() {
+ let mut s = session(8);
+ // Alpha 1: white on the top half.
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": W, "height": H / 2})).unwrap();
+ s.execute("channel.new", json!({"fill": "selection"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ let clip = &s.clipboard.as_ref().unwrap().surface;
+ assert_eq!((clip.pixel(30, 2), clip.pixel(30, 15)), (vec![1.0, 1.0], vec![0.0, 1.0]), "the alpha channel's values");
+ s.execute("channel.target", json!({"channel": "green"})).unwrap();
+ s.execute("edit.paste", json!({})).unwrap();
+ assert!(near(&px(&s, 30, 2), &[1.0, 1.0, 1.0, 1.0]));
+ assert!(near(&px(&s, 30, 15), &[1.0, 0.0, 1.0, 1.0]), "green = Alpha 1, {:?}", px(&s, 30, 15));
+ // With the composite targeted, Paste still makes a layer (grey, from the grayscale clip).
+ s.execute("channel.target", json!({"channel": "composite"})).unwrap();
+ let n = layers(&s);
+ s.execute("edit.paste", json!({})).unwrap();
+ assert_eq!(layers(&s), n + 1);
+ assert!(near(&px(&s, 30, 15), &[0.0, 0.0, 0.0, 1.0]));
+}
+
+#[test]
+fn copy_an_alpha_channel_without_a_pixel_layer() {
+ let mut s = session(8);
+ s.execute("channel.new", json!({"fill": "white"})).unwrap();
+ s.edit("no pixel layer", |_, active| {
+ *active = None;
+ Ok(())
+ })
+ .unwrap();
+ assert!(s.is_enabled("edit.copy"), "an alpha channel needs no pixel layer");
+ s.execute("edit.copy", json!({})).unwrap();
+ assert_eq!(s.clipboard.as_ref().unwrap().surface.pixel(3, 3), vec![1.0, 1.0]);
+}
+
+#[test]
+fn paste_into_a_colour_channel_keeps_to_the_selection() {
+ let mut s = session(16);
+ // Paste Into centres the paste on the selection: copy the same area so it lands in place.
+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": H})).unwrap();
+ s.execute("channel.target", json!({"channel": "red"})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ s.execute("channel.target", json!({"channel": "green"})).unwrap();
+ let n = layers(&s);
+ s.execute("edit.pasteSpecial.pasteInto", json!({})).unwrap();
+ assert_eq!(layers(&s), n, "no new layer or mask");
+ let (inside, outside) = (px(&s, 5, 5), px(&s, 15, 5));
+ assert!(near(&inside, &[0.2, 0.2, 0.6, 1.0]), "green = red inside, {inside:?}");
+ assert!(near(&outside, &[0.2, 0.4, 0.6, 1.0]), "untouched outside, {outside:?}");
+}
+
+#[test]
+fn copying_and_pasting_channels_fail_cleanly() {
+ let mut s = session(8);
+ s.execute("channel.target", json!({"channel": "red"})).unwrap();
+ // An empty selection copies nothing and leaves the clipboard alone.
+ s.edit("empty selection", |doc, _| {
+ doc.selection = Some(Surface::new(photocraft_color::PixelFormat::GRAY8));
+ Ok(())
+ })
+ .unwrap();
+ assert!(s.execute("edit.copy", json!({})).is_err());
+ assert!(s.clipboard.is_none());
+ // A pixel-locked layer refuses the paste and keeps its pixels.
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("edit.copy", json!({})).unwrap();
+ let id = s.active().unwrap().active_layer.unwrap();
+ s.edit("lock", |doc, _| {
+ doc.layer_mut(id).unwrap().locks.pixels = true;
+ Ok(())
+ })
+ .unwrap();
+ let before = px(&s, 5, 5);
+ s.execute("channel.target", json!({"channel": "blue"})).unwrap();
+ assert!(s.execute("edit.paste", json!({})).is_err());
+ assert_eq!(px(&s, 5, 5), before);
+}
diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs
index 1d2ee0363..9116779f1 100644
--- a/crates/engine/src/edit_cmds.rs
+++ b/crates/engine/src/edit_cmds.rs
@@ -55,6 +55,11 @@ fn has_layer_pixels(s: &Session) -> std::result::Result<(), String> {
active_layer(s)?.surface().map(|_| ()).ok_or_else(|| "the active layer has no pixels".into())
}
+/// Copy also copies a targeted alpha channel, with or without a pixel layer (#2307).
+fn can_copy(s: &Session) -> std::result::Result<(), String> {
+ if crate::channel_clip::copies_alpha_channel(s) { Ok(()) } else { has_layer_pixels(s) }
+}
+
fn has_clip(s: &Session) -> std::result::Result<(), String> {
has_doc(s)?;
s.clipboard.as_ref().map(|_| ()).ok_or_else(|| "the clipboard is empty".into())
@@ -172,6 +177,10 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result<Value> {
if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels {
return paste_to_target(s, p, in_place, None, "Paste");
}
+ // A targeted colour channel takes the paste instead of a new layer (#2307).
+ if let Some(k) = crate::channel_clip::paste_color_target(s, p) {
+ return crate::channel_clip::paste(s, p, k, in_place, None, "Paste");
+ }
let canvas = d.doc.bounds();
let fmt = d.doc.pixel_format();
let (dx, dy) = paste_offset(&clip, canvas, p, in_place);
@@ -192,7 +201,7 @@ fn paste(s: &mut Session, p: &Value, in_place: bool) -> Result<Value> {
/// How far a paste moves the clipboard pixels: not at all in place (or when they lie on the
/// canvas and no `center` is given), else onto `center` (the view centre from the UI) or the
/// canvas centre.
-fn paste_offset(clip: &Clip, canvas: Rect, p: &Value, in_place: bool) -> (i32, i32) {
+pub(crate) fn paste_offset(clip: &Clip, canvas: Rect, p: &Value, in_place: bool) -> (i32, i32) {
if in_place || (clip.bounds.intersect(&canvas) == clip.bounds && p.get("center").is_none()) {
return (0, 0);
}
@@ -202,7 +211,7 @@ fn paste_offset(clip: &Clip, canvas: Rect, p: &Value, in_place: bool) -> (i32, i
((cx - (b.x0 + b.x1) as f64 / 2.0).round() as i32, (cy - (b.y0 + b.y1) as f64 / 2.0).round() as i32)
}
-fn shifted(surface: &Surface, dx: i32, dy: i32) -> Surface {
+pub(crate) fn shifted(surface: &Surface, dx: i32, dy: i32) -> Surface {
if dx == 0 && dy == 0 { surface.clone() } else { photocraft_algo::resample::translate_surface(surface, dx, dy) }
}
@@ -559,7 +568,12 @@ pub fn specs() -> Vec<CommandSpec> {
s.edit("Cut Pixels", |doc, _| clear_selected(doc, id, bg))?;
Ok(r)
}),
- spec!("edit.copy", "Copy", &["Edit"], Some("Cmd+C"), "{}", has_layer_pixels, |s, _| copy(s, false)),
+ 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.copyMerged", "Copy Merged", &["Edit"], Some("Cmd+Shift+C"), "{}", has_doc, |s, _| copy(s, true)),
spec!(
"edit.paste",
diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs
index 240de5dac..02374d06b 100644
--- a/crates/engine/src/extra_cmds.rs
+++ b/crates/engine/src/extra_cmds.rs
@@ -390,6 +390,10 @@ fn paste_into(s: &mut Session, p: &Value, outside: bool) -> Result<Value> {
if let Some(c) = p.get("center") {
params["center"] = c.clone();
}
+ // A targeted colour channel (#2307): the paste goes into it, only where `limit` allows.
+ if let Some(k) = crate::channel_clip::paste_color_target(s, p) {
+ return crate::channel_clip::paste(s, &params, k, false, Some(&limit), label);
+ }
if crate::channel_cmds::target_of(p) != crate::channel_cmds::Target::Pixels {
// A targeted mask or channel (#1035): the paste goes into it, only where `limit` allows.
params["target"] = p.get("target").cloned().unwrap_or_default();
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 5245eed1c..e70781bd2 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -20,6 +20,7 @@ pub mod brush_key_cmds;
pub mod brush_preset_cmds;
pub mod build_info;
mod canvas_geom;
+mod channel_clip;
pub mod channel_cmds;
pub mod color_cmds;
pub mod color_to_alpha_cmds;