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)`,