Skip to content

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

Merge main into cmyk-native-composite

SBaksab0683da93e7f
diff --cc crates/io/src/flat.rs
index 66478e4aa,5512a55c0..6b5e3e1cb
--- a/crates/io/src/flat.rs
+++ b/crates/io/src/flat.rs
@@@ -335,63 -346,103 +346,80 @@@ fn document_to_image_for(doc: &Document
y = y1;
}
Image::from_raw(w, h, layout, csample(fmt.sample), data)?
- } else if fmt.mode == ColorMode::Cmyk {
- let count = doc.layer_count();
- warnings.push(format!("{count} layer(s) flattened; layers, masks and blend modes are not kept"));
- // A CMYK document is written as CMYK with its own profile (#2220).
- let cs = csample(fmt.sample);
- let (data, opaque) = cmyk_composite(doc, canvas, cs, n, warnings)?;
- Image::from_raw(w, h, layout_for(ColorMode::Cmyk, !opaque), cs, data)?
} else {
- let count = doc.layer_count();
- warnings.push(format!("{count} layer(s) flattened; layers, masks and blend modes are not kept"));
- // The compositor works in RGB; write RGB/gray.
- let gray = fmt.mode == ColorMode::Grayscale;
- if fmt.mode == ColorMode::Lab {
- // The compositor renders Lab documents in sRGB, so the file is tagged sRGB.
- warnings.push(format!("{:?} composite written as sRGB RGB (colour-managed conversion)", fmt.mode));
- icc = Some(photocraft_cms::Builtin::Srgb.profile().to_bytes().to_vec());
+ if single.is_none() {
+ let count = doc.layer_count();
+ warnings.push(format!("{count} layer(s) flattened; layers, masks and blend modes are not kept"));
}
- let cmyk = fmt.mode == ColorMode::Cmyk && cmyk_target;
- // Only a CMYK target needs the document's profile; RGB-only targets keep the compositor's
- // own handling (built-in coated CMYK when the embedded profile is unusable).
- let space = if cmyk {
+ let cs = csample(fmt.sample);
- let colors = if gray { 1 } else { 3 };
- // Rendered and quantised in bands (no full-size float composite), with alpha; the alpha
- // is dropped afterwards, in place, when every pixel turned out opaque.
- let mut data = try_buffer(n, (colors + 1) * cs.bytes())?;
- let mut opaque = true;
- let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> {
- opaque &= band.px.iter().all(|p| p[3] >= 1.0);
- let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| {
- let mut out = Vec::with_capacity(range.len() * (colors + 1) * cs.bytes());
- let mut put = |v: f32| {
- let v = if v.is_nan() { 0.0 } else { v };
- match cs {
- CSample::U8 => out.push((v.clamp(0.0, 1.0) * 255.0).round() as u8),
- CSample::U16 => out.extend_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_ne_bytes()),
- CSample::F16 | CSample::F32 => out.extend_from_slice(&v.to_ne_bytes()),
- }
- };
- for p in &band.px[range] {
- if gray {
- put(photocraft_color::convert::rgb_to_gray([p[0], p[1], p[2]]));
- } else {
- put(p[0]);
- put(p[1]);
- put(p[2]);
++ if fmt.mode == ColorMode::Cmyk && cmyk_target {
++ // A CMYK target is written as CMYK with the document's own profile (#2220), which it
++ // therefore needs; RGB-only targets keep the compositor's own handling (built-in
++ // coated CMYK when the embedded profile is unusable).
+ use photocraft_cms::{Builtin, ColorSpace, Intent, Profile, Transform};
+ let profile = match doc.icc_profile.as_ref() {
+ Some(bytes) => Profile::parse(bytes).map_err(|e| IoError::Unsupported(format!("invalid CMYK composite profile: {e}")))?,
+ None => Builtin::CoatedCmyk.profile().clone(),
+ };
+ if profile.color_space != ColorSpace::Cmyk {
+ return Err(IoError::Unsupported("CMYK composite requires a CMYK ICC profile".into()));
+ }
+ let srgb = Builtin::Srgb.profile();
+ Transform::new(&profile, srgb, Intent::RelativeColorimetric, true).map_err(|e| IoError::Unsupported(e.to_string()))?;
+ Transform::new(srgb, &profile, Intent::RelativeColorimetric, true).map_err(|e| IoError::Unsupported(e.to_string()))?;
+ if icc.is_none() {
+ icc = Some(profile.to_bytes().to_vec());
+ }
- photocraft_compose::cmyk_space(doc)
- } else {
- None
- };
- let gray = fmt.mode == ColorMode::Grayscale;
- if (fmt.mode == ColorMode::Cmyk && !cmyk) || fmt.mode == ColorMode::Lab {
- // RGB-only targets use the sRGB composite directly, without reseparating CMYK.
- warnings.push(format!("{:?} composite written as sRGB RGB (colour-managed conversion)", fmt.mode));
- icc = Some(photocraft_cms::Builtin::Srgb.profile().to_bytes().to_vec());
- }
- let cs = csample(fmt.sample);
- let colors = if cmyk {
- 4
- } else if gray {
- 1
++ let (data, opaque) = cmyk_composite(doc, canvas, cs, n, warnings)?;
++ Image::from_raw(w, h, layout_for(ColorMode::Cmyk, !opaque), cs, data)?
+ } else {
- 3
- };
- // Rendered and quantised in bands (no full-size float composite), with alpha; the alpha
- // is dropped afterwards, in place, when every pixel turned out opaque.
- let mut data = try_buffer(n, (colors + 1) * cs.bytes())?;
- let mut opaque = true;
- let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> {
- opaque &= band.px.iter().all(|p| p[3] >= 1.0);
- let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| {
- photocraft_color::convert::with_cmyk_space(space.as_ref(), || {
++ let gray = fmt.mode == ColorMode::Grayscale;
++ if matches!(fmt.mode, ColorMode::Cmyk | ColorMode::Lab) {
++ // RGB-only targets use the sRGB composite directly, without separating CMYK; the
++ // compositor renders Lab documents in sRGB. Either way the file is tagged sRGB.
++ warnings.push(format!("{:?} composite written as sRGB RGB (colour-managed conversion)", fmt.mode));
++ icc = Some(photocraft_cms::Builtin::Srgb.profile().to_bytes().to_vec());
++ }
++ let colors = if gray { 1 } else { 3 };
++ // Rendered and quantised in bands (no full-size float composite), with alpha; the
++ // alpha is dropped afterwards, in place, when every pixel turned out opaque.
++ let mut data = try_buffer(n, (colors + 1) * cs.bytes())?;
++ let mut opaque = true;
++ let _ = photocraft_compose::render_bands(doc, canvas, 0, |band| -> Result<(), ()> {
++ opaque &= band.px.iter().all(|p| p[3] >= 1.0);
++ let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| {
+ let mut out = Vec::with_capacity(range.len() * (colors + 1) * cs.bytes());
+ let mut put = |v: f32| {
+ let v = if v.is_nan() { 0.0 } else { v };
+ match cs {
+ CSample::U8 => out.push((v.clamp(0.0, 1.0) * 255.0).round() as u8),
+ CSample::U16 => out.extend_from_slice(&((v.clamp(0.0, 1.0) * 65535.0).round() as u16).to_ne_bytes()),
+ CSample::F16 | CSample::F32 => out.extend_from_slice(&v.to_ne_bytes()),
+ }
+ };
- let mut converted = [0.0; 5];
+ for p in &band.px[range] {
- if cmyk {
- let channels = photocraft_raster::from_rgba_into(&fmt, *p, &mut converted);
- for value in converted.iter().take(channels) {
- put(*value);
- }
- continue;
- } else if gray {
++ if gray {
+ put(photocraft_color::convert::rgb_to_gray([p[0], p[1], p[2]]));
+ } else {
+ put(p[0]);
+ put(p[1]);
+ put(p[2]);
+ }
+ put(p[3]);
}
- put(p[3]);
+ out
- })
++ });
++ for part in parts {
++ data.extend_from_slice(&part);
+ }
- out
++ Ok(())
});
-- for part in parts {
-- data.extend_from_slice(&part);
++ if opaque {
++ drop_alpha(&mut data, colors * cs.bytes(), cs.bytes());
}
-- Ok(())
-- });
-- if opaque {
-- drop_alpha(&mut data, colors * cs.bytes(), cs.bytes());
++ let layout = layout_for(if gray { ColorMode::Grayscale } else { ColorMode::Rgb }, !opaque);
++ Image::from_raw(w, h, layout, cs, data)?
}
- let layout = layout_for(if gray { ColorMode::Grayscale } else { ColorMode::Rgb }, !opaque);
- let layout = layout_for(
- if cmyk {
- ColorMode::Cmyk
- } else if gray {
- ColorMode::Grayscale
- } else {
- ColorMode::Rgb
- },
- !opaque,
- );
-- Image::from_raw(w, h, layout, cs, data)?
};
let meta = codecs::Metadata {
exif: doc.metadata.exif.as_ref().map(|e| e.to_vec()),
diff --cc crates/io/tests/cmyk_composite_export.rs
index 000000000,9f537dabf..b0c3da62a
mode 000000,100644..100644
--- a/crates/io/tests/cmyk_composite_export.rs
+++ b/crates/io/tests/cmyk_composite_export.rs
@@@ -1,0 -1,269 +1,272 @@@
+ use photocraft_cms::{Builtin, Intent, Profile, Transform};
+ use photocraft_codecs::{ChannelLayout, SampleType as CodecSample, decode};
-use photocraft_color::{ColorMode, SampleType};
++use photocraft_color::{BlendMode, ColorMode, SampleType};
+ use photocraft_doc::{Document, Layer, LayerContent};
+ use photocraft_geom::Size;
+ use photocraft_io::{ExportOptions, document_to_image, export};
+ use photocraft_raster::Surface;
+
+ fn document(depth: SampleType, alpha: f32) -> Document {
+ let mut doc = Document::new("CMYK composite", Size::new(8, 8), ColorMode::Cmyk, depth);
+ doc.icc_profile = Some(Builtin::CoatedCmyk.profile().to_bytes());
+ let surface = Surface::with_default(doc.pixel_format(), &[0.3, 0.6, 0.1, 0.2, alpha]);
+ doc.layers.push(Layer::new("Ink", LayerContent::Raster(surface)));
+ doc.layers.push(Layer::new("Empty", LayerContent::Raster(Surface::new(doc.pixel_format()))));
+ doc
+ }
+
+ fn tag(bytes: &[u8], id: u16) -> Option<u16> {
+ assert_eq!(&bytes[..2], b"II");
+ let start = usize::try_from(u32::from_le_bytes(bytes[4..8].try_into().unwrap())).unwrap();
+ let count = usize::from(u16::from_le_bytes(bytes[start..start + 2].try_into().unwrap()));
+ bytes[start + 2..]
+ .as_chunks::<12>()
+ .0
+ .iter()
+ .take(count)
+ .find_map(|entry| (u16::from_le_bytes(entry[..2].try_into().unwrap()) == id).then(|| u16::from_le_bytes(entry[8..10].try_into().unwrap())))
+ }
+
+ #[test]
+ fn tiff_keeps_cmyk_profile_depth_and_straight_alpha_when_composited() {
+ for (depth, sample) in [(SampleType::U8, CodecSample::U8), (SampleType::U16, CodecSample::U16), (SampleType::F32, CodecSample::F32)] {
+ for alpha in [1.0, 0.5] {
+ let doc = document(depth, alpha);
+
+ let result = export(&doc, "tiff", &ExportOptions::default()).unwrap();
+
+ let image = decode(&result.bytes).unwrap();
+ assert_eq!(image.layout(), if alpha == 1.0 { ChannelLayout::Cmyk } else { ChannelLayout::CmykA });
+ assert_eq!(image.sample_type(), sample);
+ assert_eq!(image.icc.as_deref(), doc.icc_profile.as_deref().map(Vec::as_slice));
+ assert_eq!(tag(&result.bytes, 262), Some(5));
+ assert_eq!(tag(&result.bytes, 277), Some(if alpha == 1.0 { 4 } else { 5 }));
+ assert_eq!(tag(&result.bytes, 338), if alpha == 1.0 { None } else { Some(2) });
+ if alpha < 1.0 {
+ assert!(image.to_normalized().as_chunks::<5>().0.iter().all(|px| (px[4] - alpha).abs() < 0.004));
+ let opaque = document_to_image(&document(depth, 1.0), &mut Vec::new()).unwrap().to_normalized();
+ for (px, color) in image.to_normalized().as_chunks::<5>().0.iter().zip(opaque.as_chunks::<4>().0) {
+ assert!(px[..4].iter().zip(color).all(|(a, b)| (a - b).abs() < 0.004));
+ }
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn tiff_keeps_true_zero_alpha_when_composited() {
+ for (depth, sample) in [(SampleType::U8, CodecSample::U8), (SampleType::U16, CodecSample::U16), (SampleType::F32, CodecSample::F32)] {
+ let doc = document(depth, 0.0);
+
+ let result = export(&doc, "tiff", &ExportOptions::default()).unwrap();
+
+ let image = decode(&result.bytes).unwrap();
+ assert_eq!(image.layout(), ChannelLayout::CmykA);
+ assert_eq!(image.sample_type(), sample);
+ assert_eq!(image.icc.as_deref(), doc.icc_profile.as_deref().map(Vec::as_slice));
+ assert_eq!(tag(&result.bytes, 262), Some(5));
+ assert_eq!(tag(&result.bytes, 277), Some(5));
+ assert_eq!(tag(&result.bytes, 338), Some(2));
+ assert!(image.to_normalized().as_chunks::<5>().0.iter().all(|px| px[4].abs() < f32::EPSILON));
+ }
+ }
+
+ #[test]
+ fn psd_keeps_cmyk_mode_depth_and_profile_when_composited() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let doc = document(depth, 0.5);
+
+ let result = export(&doc, "psd", &ExportOptions::default()).unwrap();
+
+ let back = photocraft_io::import("composite.psd", &result.bytes).unwrap().document;
+ assert_eq!(back.mode, ColorMode::Cmyk);
+ assert_eq!(back.depth, depth);
+ assert_eq!(back.icc_profile, doc.icc_profile);
+ assert_eq!(back.layer_count(), doc.layer_count());
+ }
+ }
+
+ #[test]
+ fn jpeg_keeps_four_components_profile_and_zero_ink_matte_when_composited() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ for alpha in [1.0, 0.5, 0.0] {
+ let doc = document(depth, alpha);
+ let mut opts = ExportOptions::default();
+ opts.encode.jpeg_quality = 100;
+
+ let result = export(&doc, "jpg", &opts).unwrap();
+
+ let image = decode(&result.bytes).unwrap();
+ assert_eq!(image.layout(), ChannelLayout::Cmyk);
+ assert_eq!(image.icc.as_deref(), doc.icc_profile.as_deref().map(Vec::as_slice));
+ let adobe = result.bytes.windows(5).position(|bytes| bytes == b"Adobe").unwrap();
+ assert_eq!(result.bytes[adobe + 11], 0);
+ let mut marker = 2;
+ while result.bytes[marker + 1] != 192 {
+ let length = usize::from(u16::from_be_bytes(result.bytes[marker + 2..marker + 4].try_into().unwrap()));
+ marker += length + 2;
+ }
+ assert_eq!(result.bytes[marker + 9], 4);
+ let expected = document_to_image(&doc, &mut Vec::new()).unwrap();
+ for (px, source) in image.to_normalized().as_chunks::<4>().0.iter().zip(expected.to_normalized().chunks_exact(expected.layout().channels())) {
+ for channel in 0..4 {
+ let ink = source[channel] * if expected.layout().has_alpha() { source[4] } else { 1.0 };
+ assert!((px[channel] - ink).abs() < 0.015, "{px:?} vs {source:?}");
+ }
+ }
+ if depth != SampleType::U8 {
+ assert!(result.warnings.iter().any(|warning| warning.contains("bit")), "{:?}", result.warnings);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn composite_uses_distinctive_document_profile_on_every_worker() {
+ let params = photocraft_cms::synth::CmykParams {
+ description: "Export synthetic uncoated".into(),
+ tvi: [0.26, 0.26, 0.26, 0.3],
+ grid_a2b: 5,
+ grid_b2a: 9,
+ ..Default::default()
+ };
+ let profile = photocraft_cms::synth::cmyk_profile(&params);
+ let mut doc = document(SampleType::F32, 0.5);
+ doc.size = Size::new(64, 64);
+ doc.icc_profile = Some(profile.to_bytes());
++ // Hue mixes channels, so the stack is composited in RGB and converted back through the
++ // profile (the empty layer leaves the composite as it is): the path under test.
++ doc.layers[1].blend = BlendMode::Hue;
+ let rgb = photocraft_compose::flatten(&doc);
+ let transform = Transform::new(Builtin::Srgb.profile(), &profile, Intent::RelativeColorimetric, true).unwrap();
+ let fallback = Transform::new(Builtin::Srgb.profile(), Builtin::CoatedCmyk.profile(), Intent::RelativeColorimetric, true).unwrap();
+ let mut expected = [0.0; 4];
+ transform.eval_fast(&rgb.px[0][..3], &mut expected);
+ let mut wrong = [0.0; 4];
+ fallback.eval_fast(&rgb.px[0][..3], &mut wrong);
+ assert!(expected.iter().zip(wrong).any(|(a, b)| (a - b).abs() > 0.02));
+ assert!(photocraft_io::pixels::bands(rgb.px.len()).len() > 1);
+
+ let image = document_to_image(&doc, &mut Vec::new()).unwrap();
+
+ assert_eq!(image.layout(), ChannelLayout::CmykA);
+ for px in image.to_normalized().as_chunks::<5>().0 {
+ assert!(px[..4].iter().zip(expected).all(|(a, b)| (a - b).abs() < 0.00001), "{px:?} vs {expected:?}");
+ }
+ for extension in ["tiff", "jpg"] {
+ let encoded = export(&doc, extension, &ExportOptions::default()).unwrap();
+ assert_eq!(decode(&encoded.bytes).unwrap().icc.as_deref(), doc.icc_profile.as_deref().map(Vec::as_slice));
+ }
+ }
+
+ #[test]
+ fn cmyk_composite_rejects_invalid_non_cmyk_and_unusable_profiles() {
+ let without_tags = |prefix: &[u8]| {
+ let mut bytes = Builtin::CoatedCmyk.profile().to_bytes().to_vec();
+ let count = usize::try_from(u32::from_be_bytes(bytes[128..132].try_into().unwrap())).unwrap();
+ for entry in bytes[132..].as_chunks_mut::<12>().0.iter_mut().take(count) {
+ if &entry[..3] == prefix {
+ entry[..4].copy_from_slice(b"test");
+ }
+ }
+ std::sync::Arc::new(bytes)
+ };
+ for bytes in [std::sync::Arc::new(vec![1, 2, 3]), Builtin::Srgb.profile().to_bytes(), without_tags(b"B2A"), without_tags(b"A2B")] {
+ let mut doc = document(SampleType::U8, 1.0);
+ doc.icc_profile = Some(bytes);
+
+ for extension in ["tiff", "jpg"] {
+ assert!(export(&doc, extension, &ExportOptions::default()).is_err(), "accepted invalid profile for {extension}");
+ }
+ // RGB-only targets never write CMYK, so they still export (through the built-in profile).
+ assert!(export(&doc, "png", &ExportOptions::default()).is_ok(), "rejected invalid profile for png");
+ }
+ }
+
+ #[test]
+ fn untagged_composite_embeds_coated_cmyk() {
+ let mut doc = document(SampleType::U8, 1.0);
+ doc.icc_profile = None;
+
+ let image = document_to_image(&doc, &mut Vec::new()).unwrap();
+
+ assert_eq!(image.layout(), ChannelLayout::Cmyk);
+ assert_eq!(image.icc.unwrap(), Builtin::CoatedCmyk.profile().to_bytes().as_slice());
+ }
+
+ #[test]
+ fn native_samples_are_preserved_without_composite_roundtrip() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let mut doc = document(depth, 0.5);
+ doc.layers.pop();
+ let LayerContent::Raster(surface) = &doc.layers[0].content else { panic!() };
+ let expected = surface.to_interleaved(doc.bounds());
+
+ let image = document_to_image(&doc, &mut Vec::new()).unwrap();
+
+ assert_eq!(image.data(), expected);
+ }
+ }
+
+ #[test]
+ fn rgb_only_export_uses_direct_composite_not_reseparated_cmyk() {
+ let doc = document(SampleType::U16, 0.5);
+ let rgb = photocraft_compose::flatten(&doc);
+ let expected =
+ photocraft_codecs::Image::from_normalized(8, 8, ChannelLayout::Rgba, CodecSample::U16, &rgb.px.into_iter().flatten().collect::<Vec<_>>()).unwrap();
+
+ let result = export(&doc, "png", &ExportOptions::default()).unwrap();
+
+ let image = decode(&result.bytes).unwrap();
+ assert_eq!(image.data(), expected.data());
+ assert_eq!(Profile::parse(image.icc.as_ref().unwrap()).unwrap().color_space, photocraft_cms::ColorSpace::Rgb);
+ }
+
+ #[test]
+ fn layered_tiff_keeps_its_existing_cmyk_psd_composite_path() {
+ let doc = document(SampleType::U16, 0.5);
+ let opts = ExportOptions { tiff_layers: true, ..Default::default() };
+
+ let result = export(&doc, "tiff", &opts).unwrap();
+
+ let image = decode(&result.bytes).unwrap();
+ assert_eq!(image.layout(), ChannelLayout::CmykA);
+ assert_eq!(image.icc.as_deref(), doc.icc_profile.as_deref().map(Vec::as_slice));
+ assert!(image.meta.photoshop_layers.is_some());
+ assert_eq!(tag(&result.bytes, 338), Some(2));
+ assert!(image.to_normalized().as_chunks::<5>().0.iter().all(|px| (px[4] - 0.5).abs() < 0.0001));
+ }
+
+ /// A tagged CMYK file's merged image reads through its own profile, as the compositor reads the
+ /// layers, so the two are compared in the same colours (the oracle tests rely on it: psd-tools'
+ /// tagged CMYK files were 95–100% off before).
+ #[test]
+ fn merged_composite_of_a_tagged_cmyk_file_reads_through_its_profile() {
+ use photocraft_cms::synth::{CmykParams, cmyk_profile};
+ use photocraft_color::convert::{CmykSpace, cmyk_to_rgb, with_cmyk_space};
+ let mut doc = Document::new("tagged", Size::new(6, 4), ColorMode::Cmyk, SampleType::U8);
+ let profile =
+ cmyk_profile(&CmykParams { description: "Merged Test CMYK".into(), tvi: [0.26, 0.26, 0.26, 0.3], grid_a2b: 5, grid_b2a: 9, ..Default::default() });
+ doc.icc_profile = Some(profile.to_bytes());
+ let mut surface = Surface::new(photocraft_color::PixelFormat::new(ColorMode::Cmyk, SampleType::U8, false));
+ for x in 0..6 {
+ for y in 0..4 {
+ surface.write_pixel(x, y, &[x as f32 / 5.0, y as f32 / 3.0, 0.4, (x * y) as f32 / 15.0]);
+ }
+ }
+ doc.layers.push(Layer::new("Background", LayerContent::Raster(surface)));
+ let psd = export(&doc, "psd", &ExportOptions::default()).unwrap();
+ let file = photocraft_psd::PsdFile::from_bytes(&psd.bytes).unwrap();
+ let merged = photocraft_io::merged_composite(&file).unwrap();
+ // The merged image's own inks (planar, 255 = no ink), shown through the file's profile.
+ let raw = file.decode_merged().unwrap();
+ let plane = 6 * 4;
+ let space = CmykSpace::for_profile(doc.icc_profile.as_ref());
+ assert!(space.is_some(), "a profile other than the built-in coated CMYK");
+ let shown: Vec<[f32; 3]> =
+ with_cmyk_space(space.as_ref(), || (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect());
+ let builtin: Vec<[f32; 3]> = (0..plane).map(|i| cmyk_to_rgb(std::array::from_fn(|c| 1.0 - f32::from(raw[c * plane + i]) / 255.0))).collect();
+ let apart = |a: &[[f32; 3]]| merged.iter().zip(a).flat_map(|(m, s)| (0..3).map(move |c| (m[c] - s[c]).abs())).fold(0.0f32, f32::max);
+ assert!(apart(&shown) < 1e-4, "merged image read through its profile: {}", apart(&shown));
+ assert!(apart(&builtin) > 0.01, "the built-in profile would show it differently");
+ }
diff --cc crates/io/tests/cmyk_export.rs
index 6d0b0c88a,000000000..043da677f
mode 100644,000000..100644
--- a/crates/io/tests/cmyk_export.rs
+++ b/crates/io/tests/cmyk_export.rs
@@@ -1,237 -1,0 +1,237 @@@
+//! A CMYK document is written to flat formats as CMYK with its own profile whatever its layers
+//! (#2220), mixing layers on their ink values so opaque pixels keep their exact inks.
+
+use std::sync::Arc;
+
+use photocraft_cms::Builtin;
+use photocraft_codecs::ChannelLayout;
+use photocraft_color::{BlendMode, ColorMode, PixelFormat, SampleType};
+use photocraft_doc::{Document, Layer};
+use photocraft_geom::{Rect, Size};
+use photocraft_io::*;
+
+fn cmyk_doc(depth: SampleType) -> Document {
+ let mut d = Document::new("c", Size::new(12, 8), ColorMode::Cmyk, depth);
+ d.icc_profile = Some(Arc::new(Builtin::CoatedCmyk.profile().to_bytes().to_vec()));
+ d
+}
+
+fn fill(depth: SampleType, alpha: bool, rects: &[(Rect, [f32; 5])]) -> Layer {
+ let mut l = Layer::raster("l", PixelFormat::new(ColorMode::Cmyk, depth, alpha));
+ if let Some(s) = l.surface_mut() {
+ for (r, c) in rects {
+ s.fill_rect(*r, &c[..if alpha { 5 } else { 4 }]);
+ }
+ }
+ l
+}
+
+/// Paper (no ink), K-only black "type", and a four-colour patch, as separate layers.
+fn layered(depth: SampleType) -> Document {
+ let mut d = cmyk_doc(depth);
+ d.layers.push(fill(depth, false, &[(Rect::new(0, 0, 12, 8), [0.0; 5])]));
+ d.layers.push(fill(depth, true, &[(Rect::new(0, 0, 6, 8), [0.0, 0.0, 0.0, 1.0, 1.0])]));
+ d.layers.push(fill(depth, true, &[(Rect::new(6, 0, 12, 4), [0.2, 0.4, 0.6, 0.1, 1.0])]));
+ d
+}
+
+fn decode(bytes: &[u8]) -> photocraft_codecs::Image {
+ photocraft_codecs::decode(bytes).unwrap_or_else(|e| panic!("decode: {e}"))
+}
+
+/// Normalized C, M, Y, K (and alpha) of pixel (x, y).
+fn pixel(img: &photocraft_codecs::Image, x: u32, y: u32) -> Vec<f32> {
+ let n = img.layout().channels();
+ let (w, _) = img.dimensions();
+ let v = img.to_normalized();
+ let i = ((y * w + x) as usize) * n;
+ v[i..i + n].to_vec()
+}
+
+fn q8(v: f32) -> f32 {
+ (v * 255.0).round() / 255.0
+}
+
+#[test]
+fn layered_cmyk_tiff_stays_cmyk_with_the_document_profile_and_exact_inks() {
+ for depth in [SampleType::U8, SampleType::U16, SampleType::F32] {
+ let d = layered(depth);
+ let r = export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{depth:?}: {e}"));
+ assert!(!r.warnings.iter().any(|w| w.contains("written as sRGB") || w.contains("converted back")), "{depth:?}: {:?}", r.warnings);
+ let img = decode(&r.bytes);
+ assert_eq!(img.layout(), ChannelLayout::Cmyk, "{depth:?}: opaque CMYK, no alpha");
+ assert_eq!(img.icc.as_deref(), d.icc_profile.as_deref().map(|v| &v[..]), "{depth:?}: the document's own profile");
+ // Exact inks: K-only black stays K-only, the four-colour patch keeps every ink, paper stays blank.
+ let (k, rich, paper) = (pixel(&img, 2, 3), pixel(&img, 8, 1), pixel(&img, 8, 6));
+ let tol = if depth == SampleType::U8 { 0.0 } else { 1e-4 };
+ let close = |a: &[f32], b: [f32; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() <= tol);
+ let want_rich = if depth == SampleType::U8 { [q8(0.2), q8(0.4), q8(0.6), q8(0.1)] } else { [0.2, 0.4, 0.6, 0.1] };
+ assert!(close(&k, [0.0, 0.0, 0.0, 1.0]), "{depth:?}: {k:?}");
+ assert!(close(&rich, want_rich), "{depth:?}: {rich:?}");
+ assert!(close(&paper, [0.0; 4]), "{depth:?}: {paper:?}");
+ // And it reads back as a CMYK document.
+ let back = import("a.tif", &r.bytes).unwrap_or_else(|e| panic!("{e}")).document;
+ assert_eq!(back.mode, ColorMode::Cmyk, "{depth:?}");
+ }
+}
+
+#[test]
+fn the_reported_case_an_empty_extra_layer() {
+ // #2220: one layer converted to CMYK plus an empty layer used to export as RGB.
+ let mut d = cmyk_doc(SampleType::U8);
+ d.layers.push(fill(SampleType::U8, false, &[(Rect::new(0, 0, 12, 8), [0.3, 0.2, 0.1, 0.0, 1.0])]));
+ d.layers.push(Layer::raster("empty", PixelFormat::new(ColorMode::Cmyk, SampleType::U8, true)));
+ for ext in ["tif", "jpg"] {
+ let r = export(&d, &format!("a.{ext}"), &ExportOptions::default()).unwrap_or_else(|e| panic!("{ext}: {e}"));
+ assert_eq!(decode(&r.bytes).layout(), ChannelLayout::Cmyk, "{ext}");
+ }
+}
+
+#[test]
+fn transparency_is_kept_in_tiff_and_composited_over_paper_in_jpeg() {
+ let mut d = cmyk_doc(SampleType::U8);
+ d.layers.push(fill(SampleType::U8, true, &[(Rect::new(0, 0, 6, 8), [0.0, 0.0, 0.0, 1.0, 1.0])]));
+ d.layers.push(fill(SampleType::U8, true, &[(Rect::new(6, 0, 12, 4), [0.0, 1.0, 0.0, 0.0, 0.5])]));
+ let tif = decode(&export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}")).bytes);
+ assert_eq!(tif.layout(), ChannelLayout::CmykA);
+ assert_eq!(pixel(&tif, 8, 1), vec![0.0, 1.0, 0.0, 0.0, q8(0.5)], "straight ink and coverage");
+ assert_eq!(pixel(&tif, 8, 6)[4], 0.0, "uncovered stays transparent");
+ let r = export(&d, "a.jpg", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ let jpg = decode(&r.bytes);
+ assert_eq!(jpg.layout(), ChannelLayout::Cmyk, "{:?}", r.warnings);
+ // JPEG is lossy: half-covered magenta over blank paper is about M50; uncovered paper has no ink.
+ let (half, blank, k) = (pixel(&jpg, 9, 1), pixel(&jpg, 9, 6), pixel(&jpg, 2, 3));
+ assert!((half[1] - 0.5).abs() < 0.06 && half[0] < 0.06 && half[3] < 0.06, "{half:?}");
+ assert!(blank.iter().all(|v| *v < 0.06), "{blank:?}");
+ assert!(k[3] > 0.94 && k[..3].iter().all(|v| *v < 0.06), "{k:?}");
+}
+
+#[test]
+fn multiply_adds_inks_exactly() {
+ // Multiply darkens: each ink of the result is b + s − b·s, with no ink the layers don't have.
+ let mut d = layered(SampleType::U16);
+ let mut m = fill(SampleType::U16, true, &[(Rect::new(0, 0, 12, 8), [0.0, 0.5, 0.0, 0.0, 1.0])]);
+ m.blend = BlendMode::Multiply;
+ d.layers.push(m);
+ let r = export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ assert!(!r.warnings.iter().any(|w| w.contains("converted back")), "{:?}", r.warnings);
+ let img = decode(&r.bytes);
+ assert_eq!(img.layout(), ChannelLayout::Cmyk);
+ let mul = |b: f32, s: f32| b + s - b * s;
+ let close = |a: &[f32], b: [f32; 4]| a.iter().zip(b).all(|(x, y)| (x - y).abs() <= 1e-4);
+ let (k, rich, paper) = (pixel(&img, 2, 3), pixel(&img, 8, 1), pixel(&img, 8, 6));
+ assert!(close(&k, [0.0, 0.5, 0.0, 1.0]), "{k:?}");
+ assert!(close(&rich, [0.2, mul(0.4, 0.5), 0.6, 0.1]), "{rich:?}");
+ assert!(close(&paper, [0.0, 0.5, 0.0, 0.0]), "{paper:?}");
+}
+
+#[test]
+fn other_stacks_stay_cmyk_through_the_profile() {
+ // Hue mixes channels, so it isn't composited on ink values: the RGB composite is converted back.
+ let mut d = layered(SampleType::U8);
+ let mut m = fill(SampleType::U8, true, &[(Rect::new(0, 0, 12, 8), [0.0, 0.5, 0.0, 0.0, 1.0])]);
+ m.blend = BlendMode::Hue;
+ d.layers.push(m);
+ let r = export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ assert!(r.warnings.iter().any(|w| w.contains("converted back through the document's CMYK profile")), "{:?}", r.warnings);
+ let img = decode(&r.bytes);
+ assert_eq!(img.layout(), ChannelLayout::Cmyk);
+ assert_eq!(img.icc.as_deref(), d.icc_profile.as_deref().map(|v| &v[..]));
+ // Magenta's hue on the four-colour patch shifts its colour; the page still has ink.
+ assert!(pixel(&img, 2, 3)[3] > 0.5, "{:?}", pixel(&img, 2, 3));
+}
+
+#[test]
+fn rgb_only_formats_still_get_rgb_through_the_profile() {
+ let r = export(&layered(SampleType::U8), "a.png", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ let img = decode(&r.bytes);
+ assert!(matches!(img.layout(), ChannelLayout::Rgb | ChannelLayout::Rgba), "{:?}", img.layout());
- assert!(r.warnings.iter().any(|w| w.contains("CMYK converted to sRGB")), "{:?}", r.warnings);
++ assert!(r.warnings.iter().any(|w| w.contains("Cmyk composite written as sRGB RGB")), "{:?}", r.warnings);
+}
+
+#[test]
+fn ink_adjustments_export_exact_inks() {
+ // Invert in CMYK turns every ink into its opposite: blank paper becomes four-colour black,
+ // K-only black loses its K and gains full C, M and Y.
+ let mut d = layered(SampleType::U8);
+ d.layers.push(Layer::new("inv", photocraft_doc::LayerContent::Adjustment(photocraft_doc::Adjustment::Invert)));
+ let r = export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ assert!(!r.warnings.iter().any(|w| w.contains("converted back")), "{:?}", r.warnings);
+ let img = decode(&r.bytes);
+ assert_eq!(img.layout(), ChannelLayout::Cmyk);
+ assert_eq!(pixel(&img, 8, 6), vec![1.0, 1.0, 1.0, 1.0], "paper");
+ assert_eq!(pixel(&img, 2, 3), vec![1.0, 1.0, 1.0, 0.0], "K-only black");
+ let inv = |v: f32| (255.0 - (v * 255.0).round()) / 255.0;
+ assert_eq!(pixel(&img, 8, 1), vec![inv(0.2), inv(0.4), inv(0.6), inv(0.1)], "four-colour patch");
+}
+
+#[test]
+fn channel_weighing_adjustments_go_through_the_profile() {
+ // Threshold weighs the channels together: it isn't an ink-by-ink edit.
+ let mut d = layered(SampleType::U8);
+ d.layers.push(Layer::new("t", photocraft_doc::LayerContent::Adjustment(photocraft_doc::Adjustment::Threshold { level: 0.5 })));
+ let r = export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ assert!(r.warnings.iter().any(|w| w.contains("converted back through the document's CMYK profile")), "{:?}", r.warnings);
+ assert_eq!(decode(&r.bytes).layout(), ChannelLayout::Cmyk);
+}
+
+#[test]
+fn layer_effects_export_their_inks() {
+ // K-only type with a K-only drop shadow on blank paper: the TIFF has black ink only.
+ use photocraft_doc::effects::{Contour, Effect, FxCommon, Shadow};
+ let mut d = cmyk_doc(SampleType::U8);
+ d.layers.push(fill(SampleType::U8, false, &[(Rect::new(0, 0, 12, 8), [0.0; 5])]));
+ let mut t = fill(SampleType::U8, true, &[(Rect::new(2, 2, 6, 5), [0.0, 0.0, 0.0, 1.0, 1.0])]);
+ t.effects.enabled = true;
+ t.effects.items.push(Effect::DropShadow(Shadow {
+ common: FxCommon::new(BlendMode::Multiply, 0.75),
+ color: photocraft_color::Color { mode: ColorMode::Cmyk, c: [0.0, 0.0, 0.0, 1.0], alpha: 1.0 },
+ angle: 135.0,
+ use_global_light: false,
+ distance: 2.0,
+ spread: 0.0,
+ size: 1.0,
+ contour: Contour::Linear,
+ anti_alias: false,
+ noise: 0.0,
+ knocks_out: true,
+ }));
+ d.layers.push(t);
+ let r = export(&d, "a.tif", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ assert!(!r.warnings.iter().any(|w| w.contains("converted back")), "{:?}", r.warnings);
+ let img = decode(&r.bytes);
+ assert_eq!(img.layout(), ChannelLayout::Cmyk);
+ let mut shadow = 0;
+ for y in 0..8 {
+ for x in 0..12 {
+ let p = pixel(&img, x, y);
+ assert_eq!(&p[..3], &[0.0; 3], "({x},{y}) {p:?}");
+ shadow += usize::from(p[3] > 0.0 && p[3] < 1.0);
+ }
+ }
+ assert!(shadow > 0, "a soft shadow");
+ assert_eq!(pixel(&img, 3, 3), vec![0.0, 0.0, 0.0, 1.0], "type");
+}
+
+#[test]
+fn psd_merged_image_keeps_exact_inks() {
+ // The PSD's merged image (what other apps show and print) is mixed on the inks too: K-only
+ // black under a Multiply layer stays K-only, and the four-colour patch keeps its inks.
+ let mut d = layered(SampleType::U8);
+ let mut m = fill(SampleType::U8, true, &[(Rect::new(0, 0, 12, 8), [0.0, 0.4, 0.0, 0.0, 1.0])]);
+ m.blend = BlendMode::Multiply;
+ d.layers.push(m);
+ let r = export(&d, "a.psd", &ExportOptions::default()).unwrap_or_else(|e| panic!("{e}"));
+ let f = photocraft_psd::PsdFile::from_bytes(&r.bytes).unwrap_or_else(|e| panic!("{e}"));
+ let planes = f.decode_merged().unwrap_or_else(|e| panic!("{e}"));
+ let n = 12 * 8;
+ // Planar, inverted (255 = no ink).
+ let ink = |c: usize, x: usize, y: usize| 255 - i32::from(planes.get(c * n + y * 12 + x).copied().unwrap_or(0));
+ let q = |v: f32| (v * 255.0).round() as i32;
+ assert_eq!([ink(0, 2, 3), ink(1, 2, 3), ink(2, 2, 3), ink(3, 2, 3)], [0, q(0.4), 0, 255], "K-only black with magenta multiplied in");
+ let mul = |b: f32, s: f32| b + s - b * s;
+ let qb = |v: f32| ((v * 255.0).round()) / 255.0;
+ let want = [q(0.2), q(mul(qb(0.4), qb(0.4))), q(0.6), q(0.1)];
+ let got = [ink(0, 8, 1), ink(1, 8, 1), ink(2, 8, 1), ink(3, 8, 1)];
+ assert!(got.iter().zip(want).all(|(g, w)| (g - w).abs() <= 1), "{got:?} vs {want:?}");
+}