Merge #5789: Channels: CMYK channels duplicate, load, split and merge as tone, not ink (#5787)

This commit is contained in:
aiongg committed 2026-10-27 17:43:58 +00:00
commit 0662885964
10 files changed
+354 -24

No files matched your search

+9 -7
View File
@@ -36,17 +36,18 @@ 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 {
// 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();
@@ -64,7 +65,8 @@ pub(crate) fn copy(s: &mut Session) -> Result<Option<Value>> {
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 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);
@@ -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);
}
+54
View File
@@ -72,6 +72,60 @@ 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 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);
+4 -2
View File
@@ -113,6 +113,7 @@ mod view;
use calc::{apply_image, calculations};
use manage::{delete_channel, duplicate_channel, move_channel, new_channel, new_spot, options, rename_channel, set_visible};
use planes::edit_mode;
pub(crate) use planes::tone;
pub use planes::{
GraySurface, IsolatedCurveChannel, channel_format, color_count, filter_mask_curve_channel, isolated_curve_channel, isolated_curve_channel_for,
next_alpha_name,
@@ -123,8 +124,9 @@ use selection::{load_selection, quick_mask, save_selection};
use spot::{merge, merge_spot, mergeable, split};
use targeting::{SLOT_KEY, target_cmd, target_slot};
pub(crate) use targeting::{
Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target,
is_channel_target, mask_target_enabled, read_target_surface, restrict_to_color, routed, target_of, target_surface, targeted_channel, targeted_color,
Target, channel_surface_for_filter, clear_channel, clear_color_channel, color_restriction, edits_channel, filter_mask_layer, inject_target, invert_region,
is_channel_target, is_spot_target, mask_target_enabled, read_target_surface, restrict_to_color, routed, target_of, target_surface, targeted_channel,
targeted_color,
};
pub use targeting::{follows_filter_mask, follows_target};
pub(crate) use view::fix_view;
+29 -9
View File
@@ -1,7 +1,7 @@
use super::manage::gray_document;
use super::planes::{channel_format, next_alpha_name, plane_surface, read_plane};
use super::refs::{Blending, bad, mask_plane, source, source_spec};
use super::targeting::{Target, is_channel_target, target_of, target_surface};
use super::planes::{channel_format, edit_mode, next_alpha_name, plane_surface, read_plane, tone};
use super::refs::{Blending, bad, doc_index, mask_plane, source, source_spec};
use super::targeting::{Target, is_channel_target, is_spot_target, target_of, target_surface};
use super::*;
// ---------------------------------------------------------------------------------------------
@@ -13,7 +13,11 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
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 or a layer mask 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) || target_of(p) == Target::Mask))?;
let mask = mask_plane(s, p, cmd)?;
let layer = s.active().and_then(|d| d.active_layer);
s.edit("Apply Image", |doc, _| {
@@ -22,12 +26,22 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
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]);
let mask_target = target_of(p) == Target::Mask;
if is_channel_target(p) || mask_target {
// A grayscale target gets the luminosity of a colour source (one plane).
// 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::<f32>() / 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, layer, p)?;
let base = read_plane(surf, area);
let out: Vec<f32> = base.iter().enumerate().map(|(i, &b)| b + (blending.apply(b, srcp[i]) - b) * weight(i)).collect();
let out: Vec<f32> = base
.iter()
.enumerate()
.map(|(i, &b)| {
let b = ink(b);
ink(b + (blending.apply(b, srcp[i]) - b) * weight(i))
})
.collect();
if mask_target {
// A layer mask keeps its default (reveal or hide) outside the canvas.
if surf.channels() != 1 {
@@ -64,9 +78,15 @@ pub(super) fn apply_image(s: &mut Session, p: &Value) -> Result<Value> {
// 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];
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.
// 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 });
}
if sf.alpha {
px[colors] = out_a;
@@ -133,6 +133,13 @@ pub(super) 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 }
}
pub(super) fn luminosity(rgba: [f32; 4]) -> f32 {
0.299 * rgba[0] + 0.587 * rgba[1] + 0.114 * rgba[2]
}
+11 -3
View File
@@ -1,4 +1,4 @@
use super::planes::{color_count, edit_mode, luminosity, read_plane};
use super::planes::{color_count, edit_mode, luminosity, read_plane, tone};
use super::view::{color_names, composite_name};
use super::*;
@@ -127,11 +127,19 @@ fn ref_planes(doc: &Document, layer: Option<LayerId>, active: Option<LayerId>, r
let (px, n) = native_pixels(doc, layer)?;
let planes: Vec<Vec<f32>> = (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,
}
}
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 => {
+3 -3
View File
@@ -1,5 +1,5 @@
use super::manage::{fix_view_now, gray_document};
use super::planes::{channel_format, edit_mode, plane_surface, read_plane};
use super::planes::{channel_format, edit_mode, plane_surface, read_plane, tone};
use super::refs::{ChanRef, alpha_index, bad, gray_plane, native_pixels};
use super::view::{ChannelTarget, ChannelView, color_names};
use super::*;
@@ -66,7 +66,7 @@ pub(super) fn split(s: &mut Session, p: &Value) -> Result<Value> {
let short = |name: &str| name.chars().next().map(|c| c.to_ascii_uppercase().to_string()).unwrap_or_default();
let mut docs: Vec<Document> = Vec::new();
for (c, name) in names.iter().enumerate() {
let plane: Vec<f32> = px.chunks_exact(n).map(|p| p[c]).collect();
let plane: Vec<f32> = 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 {
@@ -133,7 +133,7 @@ pub(super) fn merge(s: &mut Session, p: &Value) -> Result<Value> {
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);
}
@@ -37,6 +37,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<LayerId>, p: &Value) -> Result<(&'a mut Surface, bool)> {
match target_of(p) {
+216
View File
@@ -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();
@@ -627,6 +659,166 @@ 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 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<f32> = 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 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 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 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");
// A targeted layer mask is a grayscale target too: it takes the same luminosity.
s.execute("layer.new.layer", json!({})).unwrap();
s.execute("layer.layerMask.revealAll", json!({})).unwrap();
s.execute("channel.target", json!({"channel": "mask"})).unwrap();
s.execute("image.applyImage", json!({"blending": "normal"})).unwrap();
let d = s.active().unwrap();
let m = &d.doc.layer(d.active_layer.unwrap()).unwrap().mask.as_ref().unwrap().surface;
let (mb, mw) = (m.sample_channel(5, 5, 0), m.sample_channel(30, 5, 0));
assert!((mb - black).abs() < 1e-3 && (mw - 1.0).abs() < 1e-3, "depth {depth}: mask black {mb}, white {mw}");
}
}
#[test]
fn apply_image_into_targeted_layer_mask_leaves_the_pixels() {
let mut s = session();
@@ -706,6 +898,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)`,
+8
View File
@@ -506,8 +506,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(())