From d5056fc5bfee9ac2159d95e93095620cccb3b594 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 14 Oct 2026 23:15:20 +0200 Subject: [PATCH 1/5] Channels: CMYK channels duplicate, load, split and merge as tone, not ink (#5787) CMYK pixels are stored as ink (1 = full ink), but the Channels panel and Photoshop show a CMYK channel as its tone (white = no ink). The engine copied raw ink, so on a white CMYK document Duplicate Channel of Cyan made a black alpha, Load Selection from Cyan selected nothing, Split Channels made black grayscale documents, Merge Channels of white documents made a black CMYK image, and channel copy/paste was inverted. A small `tone(mode, v)` helper (1 - v for CMYK, its own inverse) now reads a CMYK colour channel as tone in ref_planes (Duplicate, Load Selection, Calculations, Apply Image sources), Split Channels and channel copy, and writes tone back as ink in Merge Channels, channel paste and Apply Image of a single plane onto a CMYK layer. Co-Authored-By: Claude Opus 5.5 (1M context) --- crates/engine/src/channel_clip.rs | 8 ++- crates/engine/src/channel_clip/tests.rs | 25 ++++++++ crates/engine/src/channel_cmds.rs | 19 ++++-- crates/engine/src/channel_cmds/tests.rs | 77 +++++++++++++++++++++++++ 4 files changed, 122 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rs index 86a49b0be6..a23608f328 100644 --- a/crates/engine/src/channel_clip.rs +++ b/crates/engine/src/channel_clip.rs @@ -59,12 +59,14 @@ pub(crate) fn copy(s: &mut Session) -> Result> { 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 mode = src.format().mode; let values = crate::allocation::read_region(src, area, "copying a channel")?; let cover = sel.map(|m| crate::allocation::read_region(m, area, "copying a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?; let len = (values.len() / n).checked_mul(2).ok_or_else(|| EngineError::Other("the channel is too large to copy".into()))?; let mut px = crate::allocation::capacity(len, "copying a channel")?; for (i, p) in values.chunks_exact(n).enumerate() { - px.push(p.get(k).copied().unwrap_or(0.0)); + // A CMYK channel copies as its tone (#5787). + px.push(p.get(k).map_or(0.0, |&v| crate::channel_cmds::tone(mode, v))); 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); @@ -91,7 +93,7 @@ pub(crate) fn paste(s: &mut Session, p: &Value, k: usize, in_place: bool, limit: 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(); + let (n, mode) = (surf.format().channels(), surf.format().mode); if k >= n { return Err(EngineError::Other(format!("no colour channel {k} in this layer"))); } @@ -105,7 +107,7 @@ pub(crate) fn paste(s: &mut Session, p: &Value, k: usize, in_place: bool, limit: let mut px = crate::allocation::read_region(surf, area, "pasting into a channel")?; 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]]); + let v = crate::channel_cmds::tone(mode, 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); } diff --git a/crates/engine/src/channel_clip/tests.rs b/crates/engine/src/channel_clip/tests.rs index 3d89c8f647..cf35bef93e 100644 --- a/crates/engine/src/channel_clip/tests.rs +++ b/crates/engine/src/channel_clip/tests.rs @@ -72,6 +72,31 @@ fn alpha_channels_copy_and_paste_into_colour_channels() { assert!(near(&px(&s, 30, 15), &[0.0, 0.0, 0.0, 1.0])); } +#[test] +fn cmyk_channels_copy_and_paste_as_tone() { + // #5787: copying a CMYK channel gives its tone (white where there is no ink), and pasting a + // tone into a CMYK channel writes it back as ink. + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let (left, right) = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let clip = &s.clipboard.as_ref().unwrap().surface; + assert!((clip.pixel(30, 5)[0] - 1.0).abs() < 1e-3, "depth {depth}: no ink copies as white"); + assert!((clip.pixel(5, 5)[0] - (1.0 - left[0])).abs() < 1e-3, "depth {depth}: ink copies dark"); + // Cyan pasted into Black: black gets cyan's ink, and white stays white. + s.execute("channel.target", json!({"channel": "black"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert!(near(&px(&s, 30, 5), &right), "depth {depth}: no ink stays no ink, {:?}", px(&s, 30, 5)); + let p = px(&s, 5, 5); + assert!((p[3] - left[0]).abs() < 2e-3 && near(&p[..3], &left[..3]), "depth {depth}: black = old cyan, {p:?} vs {left:?}"); + } +} + #[test] fn copy_an_alpha_channel_without_a_pixel_layer() { let mut s = session(8); diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index 00f3ec4e31..5956bccdfc 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -226,6 +226,13 @@ fn materialize(s: &mut Surface, r: Rect) { s.write_region(r, &v); } +/// A colour channel sample as the Channels panel shows it: CMYK stores ink (1 = full ink) but a +/// CMYK channel reads as its tone (white = no ink), as in Photoshop. Its own inverse, so it also +/// turns a tone back into ink. Other modes are unchanged. +pub(crate) fn tone(mode: ColorMode, v: f32) -> f32 { + if mode == ColorMode::Cmyk { 1.0 - v } else { v } +} + fn luminosity(rgba: [f32; 4]) -> f32 { 0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2] } @@ -355,7 +362,10 @@ fn ref_planes(doc: &Document, layer: Option, active: Option, r let (px, n) = native_pixels(doc, layer)?; let planes: Vec> = (0..colors).map(|c| px.chunks_exact(n).map(|p| p[c]).collect()).collect(); match r { - ChanRef::Color(k) => vec![planes.get(k).cloned().ok_or_else(|| EngineError::Other(format!("no colour channel {k}")))?], + ChanRef::Color(k) => { + let plane = planes.get(k).ok_or_else(|| EngineError::Other(format!("no colour channel {k}")))?; + vec![plane.iter().map(|&v| tone(edit_mode(doc), v)).collect()] + } _ => planes, } } @@ -1484,7 +1494,7 @@ fn split(s: &mut Session, p: &Value) -> Result { let short = |name: &str| name.chars().next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_default(); let mut docs: Vec = Vec::new(); for (c, name) in names.iter().enumerate() { - let plane: Vec = px.chunks_exact(n).map(|p| p[c]).collect(); + let plane: Vec = px.chunks_exact(n).map(|p| tone(mode, p[c])).collect(); docs.push(gray_document(&format!("{}_{}", doc.name, short(name)), &doc, &plane)); } for ch in &doc.channels { @@ -1551,7 +1561,7 @@ fn merge(s: &mut Session, p: &Value) -> Result { let mut data = Vec::with_capacity(npx * fmt.channels()); for i in 0..npx { for pl in &planes[..cc] { - data.push(pl[i].clamp(0.0, 1.0)); + data.push(tone(mode, pl[i]).clamp(0.0, 1.0)); } data.push(1.0); } @@ -1627,7 +1637,8 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { // source-over, so applying to an empty layer copies the source in any mode. let out_a = if preserve { base_a } else { w + base_a * (1.0 - w) }; for (c, b) in px[..colors].iter_mut().enumerate() { - let top = src.get(c).unwrap_or(&src[0])[i]; + // One plane is a tone (a channel, a mask): a CMYK layer takes it as ink. + let top = if src.len() > 1 { src.get(c).unwrap_or(&src[0])[i] } else { tone(sf.mode, src[0][i]) }; let blended = top + (blending.apply(*b, top) - top) * base_a; *b = if preserve { *b + (blended - *b) * w } else { (w * blended + base_a * (1.0 - w) * *b) / out_a }; } diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 1d721ee5c5..673f8e45c4 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -120,6 +120,38 @@ fn load_transparency_mask_and_composite() { assert_eq!(sel_at(&s, 10, 5), 1.0); } +/// A white CMYK document (no ink anywhere) whose left half carries some cyan ink. +fn cmyk_session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + rect(&mut s, 0, 0, 20, 20, "replace"); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +#[test] +fn cmyk_channels_duplicate_and_load_as_tone_not_ink() { + // #5787: a CMYK channel is its tone, as the Channels panel draws it: white where there is no ink. + // (The merged image goes through RGB, so inked pixels may drift a few levels.) + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let ink = px(&s, 5, 5)[0]; + assert!(ink > 0.5 && px(&s, 30, 5)[0] == 0.0, "depth {depth}: cyan ink on the left only, {ink}"); + s.execute("channel.duplicate", json!({"channel": "cyan"})).unwrap(); + assert_eq!(doc(&s).channels[0].name, "Cyan copy"); + assert!((chan(&s, 0, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: no ink duplicates as white"); + assert!((chan(&s, 0, 5, 5) - (1.0 - ink)).abs() < 0.02, "depth {depth}: ink duplicates dark"); + s.execute("select.loadSelection", json!({"channel": "cyan"})).unwrap(); + assert!((sel_at(&s, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: no ink is selected"); + assert!((sel_at(&s, 5, 5) - (1.0 - ink)).abs() < 0.02, "depth {depth}"); + // Calculations read the same tone. + let r = s.execute("image.calculations", json!({"source1": {"channel": "cyan"}, "source2": {"channel": "cyan"}, "blending": "normal"})).unwrap(); + let i = r["channel"].as_u64().unwrap() as usize; + assert!((chan(&s, i, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}"); + } +} + #[test] fn channel_management_and_view_state() { let mut s = session(); @@ -592,6 +624,27 @@ fn apply_image_into_alpha_channel() { assert!(chan(&s, 0, 3, 3) < 0.01); } +#[test] +fn cmyk_apply_image_of_a_colour_channel_keeps_ink_and_tone_apart() { + // #5787: the Cyan channel is read as tone and written back as ink, so applying it onto its own + // CMYK layer leaves cyan as it was, and into an alpha channel it lands as tone. (The merged + // image goes through RGB, so a few levels of drift are allowed.) + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let before = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "normal"})).unwrap(); + let after = px(&s, 5, 5); + assert!((after[0] - before.0[0]).abs() < 0.02, "depth {depth}: cyan unchanged, {after:?} vs {:?}", before.0); + assert!(px(&s, 30, 5).iter().zip(&before.1).all(|(a, b)| (a - b).abs() < 1e-3), "depth {depth}: no ink stays no ink"); + s.undo(); + s.execute("image.applyImage", json!({"blending": "normal"})).unwrap(); + assert!(px(&s, 5, 5).iter().zip(&before.0).all(|(a, b)| (a - b).abs() < 0.02), "depth {depth}: CMYK onto itself is a no-op"); + s.execute("channel.new", json!({"fill": "black"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "normal"})).unwrap(); + assert!((chan(&s, 0, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: tone into an alpha channel"); + } +} + #[test] fn calculations_results() { let mut s = session(); @@ -652,6 +705,30 @@ fn split_and_merge_channels() { assert!(s.execute("channel.merge", json!({"mode": "cmyk"})).is_err()); } +#[test] +fn cmyk_split_and_merge_use_tone() { + // #5787: Split Channels of a white CMYK image gives white grayscale documents, and merging + // them back gives the same CMYK pixels (within the few levels the merged image's trip + // through RGB costs). + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let (left, right) = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("channel.split", json!({})).unwrap(); + assert_eq!(s.documents().len(), 4); + let v = |s: &Session, i: usize, x: i32| s.documents()[i].doc.layers[0].surface().unwrap().pixel(x, 5)[0]; + for i in 0..4 { + assert!((v(&s, i, 30) - 1.0).abs() < 1e-3, "depth {depth}: channel {i} of white is white"); + } + assert!((v(&s, 0, 5) - (1.0 - left[0])).abs() < 0.02, "depth {depth}: cyan ink splits dark"); + s.set_active(0); + s.execute("channel.merge", json!({"mode": "cmyk", "documents": [0, 1, 2, 3]})).unwrap(); + assert_eq!(doc(&s).mode, ColorMode::Cmyk); + let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.02); + assert!(near(&px(&s, 5, 5), &left), "depth {depth}: round trip {:?} vs {left:?}", px(&s, 5, 5)); + assert!(near(&px(&s, 30, 5), &right), "depth {depth}: white stays white {:?}", px(&s, 30, 5)); + } +} + #[test] fn merge_rejects_a_repeated_source_and_keeps_unrelated_documents() { // #934: `documents: [0, 0, 1]` passed validation, then the close loop ran `close(1)`, From af4da5d602e9dcc73f5bf4aad40484684f59fcdb Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 19 Oct 2026 14:55:20 +0200 Subject: [PATCH 2/5] Channels: Apply Image blends a CMYK layer as tone; spot channels read as tone (#5787) Apply Image now blends a CMYK layer's channels as tone, as Photoshop does, so the default Multiply with a white channel or mask no longer wipes the ink, and Multiply adds ink. A spot channel reads as its tone as well, so its solid ink applies as ink and Load Selection picks the unprinted area (checked in Photoshop). Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_cmds.rs | 17 ++++++++++---- crates/engine/src/channel_cmds/tests.rs | 31 +++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index 7c4d1c4076..ca6ba905d9 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -445,7 +445,12 @@ fn ref_planes(doc: &Document, layer: Option, active: Option, r _ => planes, } } - ChanRef::Alpha(i) => vec![read_plane(&doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i}")))?.surface, area)], + ChanRef::Alpha(i) => { + let ch = doc.channels.get(i).ok_or_else(|| EngineError::Other(format!("no alpha channel {i}")))?; + let plane = read_plane(&ch.surface, area); + // A spot channel stores ink (1 = solid) but reads as its tone, as in Photoshop. + vec![if ch.spot.is_some() { plane.into_iter().map(|v| 1.0 - v).collect() } else { plane }] + } ChanRef::QuickMask => vec![read_plane(&doc.quick_mask.as_ref().ok_or_else(|| EngineError::Other("not in Quick Mask mode".into()))?.surface, area)], ChanRef::Selection => vec![sel::mask_from_surface(doc.selection.as_ref(), area)], ChanRef::Transparency => { @@ -1713,10 +1718,12 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { // source-over, so applying to an empty layer copies the source in any mode. let out_a = if preserve { base_a } else { w + base_a * (1.0 - w) }; for (c, b) in px[..colors].iter_mut().enumerate() { - // One plane is a tone (a channel, a mask): a CMYK layer takes it as ink. - let top = if src.len() > 1 { src.get(c).unwrap_or(&src[0])[i] } else { tone(sf.mode, src[0][i]) }; - let blended = top + (blending.apply(*b, top) - top) * base_a; - *b = if preserve { *b + (blended - *b) * w } else { (w * blended + base_a * (1.0 - w) * *b) / out_a }; + // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back + // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. + let top = if src.len() > 1 { tone(sf.mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; + let base = tone(sf.mode, *b); + let blended = top + (blending.apply(base, top) - top) * base_a; + *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); } if sf.alpha { px[colors] = out_a; diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 6e3a3facbd..5397d89c1a 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -645,6 +645,37 @@ fn cmyk_apply_image_of_a_colour_channel_keeps_ink_and_tone_apart() { } } +#[test] +fn cmyk_apply_image_blends_as_tone() { + // Photoshop blends a CMYK layer as tone: Multiply (the default) with a white source changes + // nothing, and Multiply with Cyan multiplies every channel's tone by Cyan's, so it adds ink. + // A spot channel reads as tone too: its solid ink applies as full ink and isn't selected. + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let (left, right) = (px(&s, 5, 5), px(&s, 30, 5)); + let near = |a: &[f32], b: &[f32]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01); + s.execute("channel.new", json!({"fill": "white"})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"channel": 0}})).unwrap(); + assert!(near(&px(&s, 5, 5), &left), "depth {depth}: white multiplies to no change, {:?} vs {left:?}", px(&s, 5, 5)); + s.undo(); + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "multiply"})).unwrap(); + let want: Vec = left[..4].iter().map(|&ink| 1.0 - (1.0 - ink) * (1.0 - left[0])).chain([1.0]).collect(); + assert!(near(&px(&s, 5, 5), &want), "depth {depth}: {:?} vs {want:?}", px(&s, 5, 5)); + assert!(near(&px(&s, 30, 5), &right), "depth {depth}: no ink stays no ink"); + s.undo(); + rect(&mut s, 0, 0, 20, 20, "replace"); + let r = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap(); + let spot = r["channel"].as_u64().unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": "composite"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"channel": spot}, "blending": "normal"})).unwrap(); + assert!(near(&px(&s, 5, 5), &[1.0; 5]) && near(&px(&s, 30, 5), &right), "depth {depth}: spot ink applies as ink, {:?}", px(&s, 5, 5)); + s.execute("select.loadSelection", json!({"channel": spot})).unwrap(); + assert!(sel_at(&s, 5, 5) < 1e-3 && (sel_at(&s, 30, 5) - 1.0).abs() < 1e-3, "depth {depth}: the spot's unprinted area loads"); + } +} + #[test] fn calculations_results() { let mut s = session(); From fcbb428ed527e9478e46e06d835f27f833a2f364 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 19 Oct 2026 16:10:16 +0200 Subject: [PATCH 3/5] Channels: Apply Image and paste into a spot channel work in tone; copy a spot as tone (#5787) A spot channel stores ink but now reads as tone, so it must also take tone: Apply Image onto a spot (itself, Cyan, any source) and Paste into a spot convert its ink to tone and back, and copying a spot gives its tone. An RGB composite applied onto a CMYK layer is read in its own mode, so the default Multiply with white no longer fills the layer with ink. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_clip.rs | 14 ++++----- crates/engine/src/channel_clip/tests.rs | 29 ++++++++++++++++++ crates/engine/src/channel_cmds.rs | 28 ++++++++++++++++-- crates/engine/src/channel_cmds/tests.rs | 39 +++++++++++++++++++++++++ crates/engine/src/edit_cmds.rs | 8 +++++ 5 files changed, 109 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/channel_clip.rs b/crates/engine/src/channel_clip.rs index a23608f328..5bf31f0e38 100644 --- a/crates/engine/src/channel_clip.rs +++ b/crates/engine/src/channel_clip.rs @@ -36,17 +36,18 @@ pub(crate) fn copy(s: &mut Session) -> Result> { 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 { + // The surface the values come from, which of its samples is the channel, and whether it stores + // ink (CMYK, a spot channel) rather than tone. + let (src, k, ink) = match d.channel_view.target { ChannelTarget::Composite | ChannelTarget::LayerMask | ChannelTarget::VectorMask => 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) + (surf, k, surf.format().mode == ColorMode::Cmyk) } 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) + (&c.surface, 0, c.spot.is_some()) } }; let n = src.format().channels(); @@ -59,14 +60,13 @@ pub(crate) fn copy(s: &mut Session) -> Result> { 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 mode = src.format().mode; let values = crate::allocation::read_region(src, area, "copying a channel")?; let cover = sel.map(|m| crate::allocation::read_region(m, area, "copying a channel selection").map(|v| (v, m.format().channels().max(1)))).transpose()?; let len = (values.len() / n).checked_mul(2).ok_or_else(|| EngineError::Other("the channel is too large to copy".into()))?; let mut px = crate::allocation::capacity(len, "copying a channel")?; for (i, p) in values.chunks_exact(n).enumerate() { - // A CMYK channel copies as its tone (#5787). - px.push(p.get(k).map_or(0.0, |&v| crate::channel_cmds::tone(mode, v))); + // A CMYK or spot channel copies as its tone (#5787). + px.push(p.get(k).map_or(0.0, |&v| if ink { 1.0 - v } else { v })); 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); diff --git a/crates/engine/src/channel_clip/tests.rs b/crates/engine/src/channel_clip/tests.rs index cf35bef93e..a5e687b297 100644 --- a/crates/engine/src/channel_clip/tests.rs +++ b/crates/engine/src/channel_clip/tests.rs @@ -97,6 +97,35 @@ fn cmyk_channels_copy_and_paste_as_tone() { } } +#[test] +fn spot_channels_copy_and_paste_as_tone() { + // #5787: a spot channel stores ink but copies as its tone, and a tone pasted into it goes back + // to ink: spot -> Black prints the spot's ink in black, Cyan -> spot gives the spot Cyan's ink. + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": W / 2, "height": H})).unwrap(); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + let cyan = px(&s, 5, 5)[0]; + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 10, "height": H})).unwrap(); + let spot = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap()["channel"].as_u64().unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": spot})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + let clip = &s.clipboard.as_ref().unwrap().surface; + assert!(clip.pixel(5, 5)[0] < 1e-3 && (clip.pixel(30, 5)[0] - 1.0).abs() < 1e-3, "depth {depth}: ink copies dark"); + s.execute("channel.target", json!({"channel": "black"})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + assert!((px(&s, 5, 5)[3] - 1.0).abs() < 2e-3 && px(&s, 30, 5)[3] < 2e-3, "depth {depth}: black = the spot's ink"); + s.execute("channel.target", json!({"channel": "cyan"})).unwrap(); + s.execute("edit.copy", json!({})).unwrap(); + s.execute("channel.target", json!({"channel": spot})).unwrap(); + s.execute("edit.paste", json!({})).unwrap(); + let ink = |x| s.active().unwrap().doc.channels[spot as usize].surface.sample_channel(x, 5, 0); + assert!(near(&[ink(5), ink(15), ink(30)], &[cyan, cyan, 0.0]), "depth {depth}: spot = Cyan's ink, {:?}", [ink(5), ink(15), ink(30)]); + } +} + #[test] fn copy_an_alpha_channel_without_a_pixel_layer() { let mut s = session(8); diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index c52cbb8b77..b511e45ad9 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -638,6 +638,19 @@ pub(crate) fn is_channel_target(p: &Value) -> bool { matches!(target_of(p), Target::Alpha(_) | Target::QuickMask) } +/// The target is a spot channel: it stores ink but takes tone, as it reads. +pub(crate) fn is_spot_target(doc: &Document, p: &Value) -> bool { + matches!(target_of(p), Target::Alpha(i) if doc.channels.get(i).is_some_and(|c| c.spot.is_some())) +} + +/// Inverts `r` of a channel surface (ink to tone and back). +pub(crate) fn invert_region(s: &mut Surface, r: Rect) -> Result<()> { + let mut v = crate::allocation::read_region(s, r, "inverting a channel")?; + v.iter_mut().for_each(|x| *x = 1.0 - *x); + s.try_write_region(r, &v)?; + Ok(()) +} + /// The surface a pixel command writes to and whether the layer's transparency is locked. pub(crate) fn target_surface<'a>(doc: &'a mut Document, layer: Option, p: &Value) -> Result<(&'a mut Surface, bool)> { match target_of(p) { @@ -1680,6 +1693,8 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let preserve = p.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false); let src_spec = source_spec(p, "source", "source").unwrap_or_else(|| json!({})); let src = source(s, &src_spec, cmd, false)?; + // A composite's planes are in its own document's mode, which may not be the target's. + let src_mode = s.documents().get(doc_index(s, &src_spec, "document")?).map(|d| edit_mode(&d.doc)).ok_or(EngineError::NoDocument)?; let mask = mask_plane(s, p, cmd)?; let layer = s.active().and_then(|d| d.active_layer); s.edit("Apply Image", |doc, _| { @@ -1690,9 +1705,18 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { // A grayscale target gets the luminosity of a colour source (one plane). let srcp = if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; + let spot = is_spot_target(doc, p); + let ink = |v: f32| if spot { 1.0 - v } else { v }; let (surf, _) = target_surface(doc, None, p)?; let base = read_plane(surf, area); - let out: Vec = base.iter().enumerate().map(|(i, &b)| b + (blending.apply(b, srcp[i]) - b) * weight(i)).collect(); + let out: Vec = base + .iter() + .enumerate() + .map(|(i, &b)| { + let b = ink(b); + ink(b + (blending.apply(b, srcp[i]) - b) * weight(i)) + }) + .collect(); *surf = plane_surface(&out, area, surf.format()); return Ok(()); } @@ -1722,7 +1746,7 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { for (c, b) in px[..colors].iter_mut().enumerate() { // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. - let top = if src.len() > 1 { tone(sf.mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; + let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; let base = tone(sf.mode, *b); let blended = top + (blending.apply(base, top) - top) * base_a; *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 5397d89c1a..5a8e64a952 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -676,6 +676,45 @@ fn cmyk_apply_image_blends_as_tone() { } } +#[test] +fn apply_image_onto_a_spot_channel_blends_as_tone() { + let near = |a: &[f32], b: &[f32]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01); + // #5787: a spot channel stores ink but reads and takes tone, so the spot applied onto itself + // changes nothing (Normal or Multiply), and Cyan applied onto it gives it Cyan's ink. + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let cyan = px(&s, 5, 5)[0]; + rect(&mut s, 0, 0, 10, 20, "replace"); + let spot = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap()["channel"].as_u64().unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let ink = |s: &Session| [5, 15, 30].map(|x| chan(s, spot as usize, x, 5)); + let before = ink(&s); + assert!(near(&before, &[1.0, 0.0, 0.0]), "depth {depth}: {before:?}"); + for blending in ["normal", "multiply"] { + s.execute("image.applyImage", json!({"source": {"channel": spot}, "blending": blending, "target": {"channel": spot}})).unwrap(); + assert!(near(&ink(&s), &before), "depth {depth}: {blending} onto itself, {:?}", ink(&s)); + } + s.execute("image.applyImage", json!({"source": {"channel": "cyan"}, "blending": "normal", "target": {"channel": spot}})).unwrap(); + assert!(near(&ink(&s), &[cyan, cyan, 0.0]), "depth {depth}: Cyan's ink, {:?}", ink(&s)); + } +} + +#[test] +fn apply_image_from_an_rgb_document_onto_cmyk_reads_it_in_its_own_mode() { + let near = |a: &[f32], b: &[f32]| a.len() == b.len() && a.iter().zip(b).all(|(x, y)| (x - y).abs() < 0.01); + // #5787: an RGB composite is tone in RGB terms: white multiplied (the default) onto a CMYK + // layer changes nothing. + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "background": "white"})).unwrap(); + rect(&mut s, 0, 0, 20, 20, "replace"); + s.execute("edit.fill", json!({"color": "#00ffff"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let before = (px(&s, 5, 5), px(&s, 30, 5)); + s.execute("image.applyImage", json!({"source": {"document": 0}})).unwrap(); + assert!(near(&px(&s, 5, 5), &before.0) && near(&px(&s, 30, 5), &before.1), "{:?} vs {before:?}", (px(&s, 5, 5), px(&s, 30, 5))); +} + #[test] fn calculations_results() { let mut s = session(); diff --git a/crates/engine/src/edit_cmds.rs b/crates/engine/src/edit_cmds.rs index 7cdb595212..8bb073d497 100644 --- a/crates/engine/src/edit_cmds.rs +++ b/crates/engine/src/edit_cmds.rs @@ -481,8 +481,16 @@ pub(crate) fn paste_to_target(s: &mut Session, p: &Value, in_place: bool, limit: let src = shifted(&clip.surface, dx, dy); let area = src.content_bounds().intersect(&canvas); s.edit(label, |doc, _| { + // A spot channel stores ink: the paste goes over its tone, then back to ink (#5787). + let spot = crate::channel_cmds::is_spot_target(doc, p); let (surf, _) = crate::channel_cmds::target_surface(doc, layer, p)?; + if spot { + crate::channel_cmds::invert_region(surf, area)?; + } crate::fill_cmds::composite_over(surf, &src, area, limit)?; + if spot { + crate::channel_cmds::invert_region(surf, area)?; + } surf.prune(); doc.selection = None; Ok(()) From b1fdd74afe6169d145cebef78325c8838cae20d8 Mon Sep 17 00:00:00 2001 From: David Mann Date: Mon, 19 Oct 2026 16:50:44 +0200 Subject: [PATCH 4/5] Apply Image: a CMYK composite reads as tone onto channels and other modes (#5787) A CMYK composite applied onto a spot channel averaged its stored ink and then treated it as tone, so Normal on a white page filled the spot with solid ink (main left it empty). The composite's planes are now averaged as tone. Onto an RGB or Gray layer, Black alone turned white because K was dropped; each tone is now darkened by the source's Black. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_cmds.rs | 15 ++++++++--- crates/engine/src/channel_cmds/tests.rs | 35 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index b511e45ad9..d2f95f0edf 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -1702,9 +1702,13 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area)); let weight = |i: usize| opacity * mask.as_ref().map_or(1.0, |m| m[i]) * selection.as_ref().map_or(1.0, |m| m[i]); if is_channel_target(p) { - // A grayscale target gets the luminosity of a colour source (one plane). - let srcp = - if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; + // A grayscale target gets the luminosity of a colour source (one plane). A composite's + // planes are averaged as tone: a CMYK composite stores ink, so white has none. + let srcp = if src.len() == 1 { + src[0].clone() + } else { + (0..src[0].len()).map(|i| src.iter().map(|pl| tone(src_mode, pl[i])).sum::() / src.len() as f32).collect() + }; let spot = is_spot_target(doc, p); let ink = |v: f32| if spot { 1.0 - v } else { v }; let (surf, _) = target_surface(doc, None, p)?; @@ -1746,7 +1750,10 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { for (c, b) in px[..colors].iter_mut().enumerate() { // Blended as tone, as Photoshop does: a CMYK layer's ink turns into tone and back // (Multiply darkens, so it adds ink). One plane (a channel, a mask) is a tone already. - let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) } else { src[0][i] }; + // A CMYK composite onto another mode darkens each tone by its Black, so Black + // alone stays black. + let k = if src_mode == ColorMode::Cmyk && sf.mode != ColorMode::Cmyk { src.get(3).map_or(1.0, |pl| tone(src_mode, pl[i])) } else { 1.0 }; + let top = if src.len() > 1 { tone(src_mode, src.get(c).unwrap_or(&src[0])[i]) * k } else { src[0][i] }; let base = tone(sf.mode, *b); let blended = top + (blending.apply(base, top) - top) * base_a; *b = tone(sf.mode, if preserve { base + (blended - base) * w } else { (w * blended + base_a * (1.0 - w) * base) / out_a }); diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index 5a8e64a952..a461b655b0 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -715,6 +715,41 @@ fn apply_image_from_an_rgb_document_onto_cmyk_reads_it_in_its_own_mode() { assert!(near(&px(&s, 5, 5), &before.0) && near(&px(&s, 30, 5), &before.1), "{:?} vs {before:?}", (px(&s, 5, 5), px(&s, 30, 5))); } +#[test] +fn apply_image_of_a_cmyk_composite_onto_a_spot_channel_blends_as_tone() { + // #5787: the CMYK composite stores ink, so its white has none: applied in Normal onto an empty + // spot channel, the spot stays empty on the white and takes ink on the Cyan. + for depth in [8, 16] { + let mut s = cmyk_session(depth); + let spot = s.execute("channel.newSpot", json!({"color": "#ff00ff", "solidity": 100})).unwrap()["channel"].as_u64().unwrap() as usize; + s.execute("image.applyImage", json!({"blending": "normal", "target": {"channel": spot}})).unwrap(); + let (cyan, white) = (chan(&s, spot, 5, 5), chan(&s, spot, 30, 5)); + assert!(white < 0.01 && cyan > 0.1 && cyan < 0.9, "depth {depth}: cyan {cyan}, white {white}"); + } +} + +#[test] +fn apply_image_of_a_cmyk_composite_onto_rgb_keeps_black() { + // #5787: Black alone (no C, M or Y) applied from a CMYK document onto RGB stays black, and + // the CMYK white stays white (the merged image goes through RGB, so a few levels of drift). + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "background": "white"})).unwrap(); + { + let d = s.active_mut().unwrap(); + let id = d.active_layer.unwrap(); + let surf = std::sync::Arc::make_mut(&mut d.doc).layer_mut(id).unwrap().surface_mut().unwrap(); + let n = surf.format().channels(); + let mut k = vec![0.0; 20 * 20 * n]; + k.chunks_exact_mut(n).for_each(|p| p[3] = 1.0); + surf.write_region(Rect::new(0, 0, 20, 20), &k); + } + s.execute("file.new", json!({"width": 40, "height": 20, "background": "white"})).unwrap(); + s.execute("image.applyImage", json!({"source": {"document": 0}, "blending": "normal"})).unwrap(); + let (black, white) = (px(&s, 5, 5), px(&s, 30, 5)); + assert!(black[..3].iter().all(|&v| v < 0.05), "{black:?}"); + assert!(white[..3].iter().all(|&v| v > 0.95), "{white:?}"); +} + #[test] fn calculations_results() { let mut s = session(); From 9154d64ce5bee7fe740f88a45623b193e6bd9369 Mon Sep 17 00:00:00 2001 From: David Mann Date: Tue, 20 Oct 2026 15:17:44 +0200 Subject: [PATCH 5/5] Channels: Apply Image of a CMYK composite onto a channel takes its luminosity (#5787) An average of the four tones left Black alone light gray (0.67 where Calculations reads 0.13); the channel now gets the same luminosity Calculations reads. Other modes are unchanged. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/channel_cmds.rs | 15 +++++++-------- crates/engine/src/channel_cmds/tests.rs | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/channel_cmds.rs b/crates/engine/src/channel_cmds.rs index d2f95f0edf..f2f1ef3a5b 100644 --- a/crates/engine/src/channel_cmds.rs +++ b/crates/engine/src/channel_cmds.rs @@ -1692,9 +1692,11 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let opacity = p.get("opacity").and_then(Value::as_f64).unwrap_or(100.0).clamp(0.0, 100.0) as f32 / 100.0; let preserve = p.get("preserveTransparency").and_then(Value::as_bool).unwrap_or(false); let src_spec = source_spec(p, "source", "source").unwrap_or_else(|| json!({})); - let src = source(s, &src_spec, cmd, false)?; // A composite's planes are in its own document's mode, which may not be the target's. let src_mode = s.documents().get(doc_index(s, &src_spec, "document")?).map(|d| edit_mode(&d.doc)).ok_or(EngineError::NoDocument)?; + // A CMYK composite reaches a channel as its luminosity, as Calculations reads it: its planes + // are ink, and an average of their tones would leave Black alone light gray. + let src = source(s, &src_spec, cmd, src_mode == ColorMode::Cmyk && is_channel_target(p))?; let mask = mask_plane(s, p, cmd)?; let layer = s.active().and_then(|d| d.active_layer); s.edit("Apply Image", |doc, _| { @@ -1702,13 +1704,10 @@ fn apply_image(s: &mut Session, p: &Value) -> Result { let selection = doc.selection.as_ref().map(|m| sel::mask_from_surface(Some(m), area)); let weight = |i: usize| opacity * mask.as_ref().map_or(1.0, |m| m[i]) * selection.as_ref().map_or(1.0, |m| m[i]); if is_channel_target(p) { - // A grayscale target gets the luminosity of a colour source (one plane). A composite's - // planes are averaged as tone: a CMYK composite stores ink, so white has none. - let srcp = if src.len() == 1 { - src[0].clone() - } else { - (0..src[0].len()).map(|i| src.iter().map(|pl| tone(src_mode, pl[i])).sum::() / src.len() as f32).collect() - }; + // A grayscale target gets one plane: a CMYK composite's luminosity (above), the average of + // another composite's planes. + let srcp = + if src.len() == 1 { src[0].clone() } else { (0..src[0].len()).map(|i| src.iter().map(|pl| pl[i]).sum::() / src.len() as f32).collect() }; let spot = is_spot_target(doc, p); let ink = |v: f32| if spot { 1.0 - v } else { v }; let (surf, _) = target_surface(doc, None, p)?; diff --git a/crates/engine/src/channel_cmds/tests.rs b/crates/engine/src/channel_cmds/tests.rs index a461b655b0..01a24c4414 100644 --- a/crates/engine/src/channel_cmds/tests.rs +++ b/crates/engine/src/channel_cmds/tests.rs @@ -750,6 +750,31 @@ fn apply_image_of_a_cmyk_composite_onto_rgb_keeps_black() { assert!(white[..3].iter().all(|&v| v > 0.95), "{white:?}"); } +#[test] +fn apply_image_of_a_cmyk_composite_onto_an_alpha_channel_takes_its_luminosity() { + // #5787: a CMYK composite reaches a channel as its luminosity, as Calculations reads it, so + // Black alone stays dark and white stays white. + for depth in [8, 16] { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 40, "height": 20, "mode": "cmyk", "depth": depth, "background": "white"})).unwrap(); + { + let d = s.active_mut().unwrap(); + let id = d.active_layer.unwrap(); + let surf = std::sync::Arc::make_mut(&mut d.doc).layer_mut(id).unwrap().surface_mut().unwrap(); + let n = surf.format().channels(); + let mut k = vec![1.0; 20 * 20 * n]; + k.chunks_exact_mut(n).for_each(|p| p[..3].fill(0.0)); + surf.write_region(Rect::new(0, 0, 20, 20), &k); + } + let a = s.execute("channel.new", json!({})).unwrap()["channel"].as_u64().unwrap() as usize; + s.execute("image.applyImage", json!({"blending": "normal", "target": {"channel": a}})).unwrap(); + let b = s.execute("image.calculations", json!({"source1": {}, "source2": {}, "blending": "normal"})).unwrap()["channel"].as_u64().unwrap() as usize; + let (black, white) = (chan(&s, a, 5, 5), chan(&s, a, 30, 5)); + assert!(black < 0.25 && (white - 1.0).abs() < 1e-3, "depth {depth}: black {black}, white {white}"); + assert!((black - chan(&s, b, 5, 5)).abs() < 1e-3, "depth {depth}: as Calculations reads it"); + } +} + #[test] fn calculations_results() { let mut s = session();