PhotoCraft: An open-source, photo editor written by scratch in pure Rust
CMYK documents export as CMYK, mixing pixel layers on their ink values (#2220)
SBaksa4af9f116e79a
diff --git a/crates/compose/src/cmyk.rs b/crates/compose/src/cmyk.rsnew file mode 100644index 000000000..c97b27d4e--- /dev/null+++ b/crates/compose/src/cmyk.rs@@ -0,0 +1,325 @@+//! Mode-native CMYK compositing: a CMYK document's layers mixed on their ink values, so opaque+//! pixels keep their exact inks (K-only black stays K-only) instead of going through display RGB+//! and back through the profile.+//!+//! This path covers the layer stacks whose blending is the same in every colour model: Normal+//! pixel layers with opacity, fill opacity and masks, isolated and pass-through groups, and+//! clipping groups. [`supports`] says whether a document stays on it; anything else (type,+//! shapes, fills, effects, adjustments, other blend modes, knockouts, channel restrictions,+//! Blend If) is left to the RGB compositor, whose result callers convert back to CMYK.+//!+//! Buffers hold straight-alpha `[C, M, Y, K, A]` in 0..1 ink (0 = no ink).++use photocraft_color::ColorMode;+use photocraft_color::blend::BlendMode;+use photocraft_doc::{Document, Knockout, Layer, LayerContent};+use photocraft_geom::Rect;++use super::{Ctx, RENDER_TILE, advanced, empty_in, mask_vals, pattern};++/// One straight-alpha CMYK pixel: C, M, Y, K (0..1 ink), alpha.+pub type Cmyka = [f32; 5];++/// Deepest group nesting this path composites (deeper documents use the RGB compositor).+pub const MAX_DEPTH: u32 = 64;++/// Straight-alpha CMYK + alpha float buffer covering a rectangle.+#[derive(Clone, Debug, PartialEq)]+pub struct CmykBuffer {+ pub rect: Rect,+ pub px: Vec<Cmyka>,+}++impl CmykBuffer {+ pub fn transparent(rect: Rect) -> Self {+ Self { rect, px: vec![[0.0; 5]; rect.width() as usize * rect.height() as usize] }+ }+}++/// Whether [`render_cmyk`] composites `doc` natively (a CMYK document made only of layers this+/// path handles; invisible layers don't count).+pub fn supports(doc: &Document) -> bool {+ doc.mode == ColorMode::Cmyk && stack_supported(&doc.layers, 0)+}++/// The sibling list grouped as the compositor groups it: each base with the clipped layers above it.+fn clip_groups(layers: &[Layer]) -> impl Iterator<Item = (&Layer, &[Layer])> {+ let mut i = 0;+ std::iter::from_fn(move || {+ let base = layers.get(i)?;+ let mut j = i + 1;+ while layers.get(j).is_some_and(|l| l.clipped) && !base.clipped {+ j += 1;+ }+ let clipped = layers.get(i + 1..j).unwrap_or(&[]);+ i = j.max(i + 1);+ Some((base, clipped))+ })+}++fn stack_supported(layers: &[Layer], depth: u32) -> bool {+ if depth > MAX_DEPTH {+ return false;+ }+ clip_groups(layers).all(|(base, clipped)| !base.visible || layer_supported(base, clipped, depth))+}++/// What every natively composited layer needs, whatever its content.+fn plain(l: &Layer) -> bool {+ l.opacity.is_finite()+ && l.fill_opacity.is_finite()+ && !super::effects::has_effects(l)+ && l.advanced.knockout == Knockout::None+ && l.excluded_channels == 0+ && l.blend_if.is_default()+}++fn cmyk_raster(l: &Layer) -> bool {+ matches!(&l.content, LayerContent::Raster(s) if s.format().mode == ColorMode::Cmyk)+}++fn layer_supported(l: &Layer, clipped: &[Layer], depth: u32) -> bool {+ if !plain(l) || advanced::clips_individually(l, clipped) {+ return false;+ }+ let content = match &l.content {+ LayerContent::Raster(_) => cmyk_raster(l) && l.blend == BlendMode::Normal,+ LayerContent::Group(g) => {+ g.artboard.is_none()+ && matches!(l.blend, BlendMode::Normal | BlendMode::PassThrough)+ // A pass-through group with clipped layers mixes them through its isolated rendering.+ && !(passes_through(l) && clipped.iter().any(|c| c.visible))+ && stack_supported(&g.children, depth + 1)+ }+ _ => false,+ };+ content && clipped.iter().filter(|c| c.visible).all(|c| plain(c) && cmyk_raster(c) && c.blend == BlendMode::Normal)+}++/// A group whose children composite straight into the backdrop (the compositor's rule).+fn passes_through(l: &Layer) -> bool {+ matches!(l.content, LayerContent::Group(_)) && l.blend == BlendMode::PassThrough && l.fill_opacity >= 1.0 && !super::effects::has_effects(l)+}++/// Normal compositing of straight-alpha `source` (alpha times `opacity`) over `backdrop`: the+/// compositor's Normal formula, on the four ink channels.+#[inline]+pub fn normal(backdrop: Cmyka, source: Cmyka, opacity: f32) -> Cmyka {+ let ab = backdrop[4];+ let as_ = source[4] * opacity;+ if as_ <= 0.0 {+ return backdrop;+ }+ let ao = as_ + ab * (1.0 - as_);+ if ao <= 0.0 {+ return [0.0; 5];+ }+ let kb = ab * (1.0 - as_);+ let inv = 1.0 / ao;+ let c = |i: usize| (kb * backdrop[i] + as_ * source[i]) * inv;+ [c(0), c(1), c(2), c(3), ao]+}++/// A finite sample in 0..1 (non-finite samples, possible in 32-bit documents, count as 0).+#[inline]+fn clean(v: f32) -> f32 {+ if v.is_finite() { v } else { 0.0 }+}++/// A CMYK pixel layer's own pixels over `rect`, masks applied.+fn raster_content(l: &Layer, rect: Rect, cx: &Ctx) -> CmykBuffer {+ let mut out = CmykBuffer::transparent(rect);+ if let LayerContent::Raster(s) = &l.content {+ let ch = s.format().channels();+ let alpha = s.format().alpha;+ let mut v = Vec::new();+ s.read_region_into(rect, &mut v);+ for (o, p) in out.px.iter_mut().zip(v.chunks_exact(ch.max(1))) {+ let a = if alpha { p.get(4).copied().map_or(0.0, clean) } else { 1.0 };+ *o = [+ p.first().copied().map_or(0.0, clean),+ p.get(1).copied().map_or(0.0, clean),+ p.get(2).copied().map_or(0.0, clean),+ p.get(3).copied().map_or(0.0, clean),+ a,+ ];+ }+ }+ apply_mask(l, &mut out, cx);+ out+}++fn apply_mask(l: &Layer, buf: &mut CmykBuffer, cx: &Ctx) {+ if let Some(m) = mask_vals(l, buf.rect, cx) {+ for (p, k) in buf.px.iter_mut().zip(&m) {+ p[4] *= clean(*k).max(0.0);+ }+ }+}++/// Mask value `i` of `m` (1 where there is no mask or no value).+#[inline]+fn mask_at(m: &Option<Vec<f32>>, i: usize) -> f32 {+ m.as_ref().and_then(|v| v.get(i)).copied().map_or(1.0, |k| clean(k).max(0.0))+}++/// Clipped layers onto their base's own rendering: each blends as if the base were opaque and+/// the base keeps its alpha.+fn composite_clipped(clipped: &[Layer], base: &mut CmykBuffer, cx: &Ctx) {+ for c in clipped.iter().filter(|c| c.visible) {+ let content = raster_content(c, base.rect, cx);+ let opacity = c.opacity * c.fill_opacity;+ for (p, s) in base.px.iter_mut().zip(&content.px) {+ let alpha = p[4];+ if alpha <= 0.0 {+ continue;+ }+ let r = normal([p[0], p[1], p[2], p[3], 1.0], *s, opacity);+ *p = [r[0], r[1], r[2], r[3], alpha];+ }+ }+}++fn blend_into(backdrop: &mut CmykBuffer, src: &CmykBuffer, opacity: f32) {+ for (b, s) in backdrop.px.iter_mut().zip(&src.px) {+ if s[4] > 0.0 {+ *b = normal(*b, *s, opacity);+ }+ }+}++fn composite_stack(layers: &[Layer], backdrop: &mut CmykBuffer, cx: &Ctx) {+ for (base, clipped) in clip_groups(layers) {+ if base.visible {+ composite_layer(base, clipped, backdrop, cx);+ }+ }+}++fn composite_layer(l: &Layer, clipped: &[Layer], backdrop: &mut CmykBuffer, cx: &Ctx) {+ let rect = backdrop.rect;+ if empty_in(l, rect) {+ return;+ }+ let opacity = l.opacity * l.fill_opacity;+ if let LayerContent::Group(g) = &l.content {+ if passes_through(l) {+ let needs_mix = opacity < 1.0 || l.mask.is_some() || l.vector_mask.is_some();+ let before = needs_mix.then(|| backdrop.clone());+ composite_stack(&g.children, backdrop, cx);+ if let Some(before) = &before {+ // The compositor's pass-through mix: coverage mixes premultiplied colour.+ let mv = mask_vals(l, rect, cx);+ for (i, (p, a)) in backdrop.px.iter_mut().zip(&before.px).enumerate() {+ let k = opacity * mask_at(&mv, i);+ let b = *p;+ let wa = a[4] * (1.0 - k);+ let wb = b[4] * k;+ let alpha = wa + wb;+ *p = if alpha > 0.0 {+ let c = |c: usize| (a[c] * wa + b[c] * wb) / alpha;+ [c(0), c(1), c(2), c(3), alpha]+ } else {+ [0.0; 5]+ };+ }+ }+ return;+ }+ let mut content = CmykBuffer::transparent(rect);+ composite_stack(&g.children, &mut content, cx);+ apply_mask(l, &mut content, cx);+ composite_clipped(clipped, &mut content, cx);+ blend_into(backdrop, &content, opacity);+ return;+ }+ let mut content = raster_content(l, rect, cx);+ composite_clipped(clipped, &mut content, cx);+ blend_into(backdrop, &content, opacity);+}++fn render_tile(doc: &Document, rect: Rect, cx: &Ctx) -> CmykBuffer {+ let mut b = CmykBuffer::transparent(rect);+ composite_stack(&doc.layers, &mut b, cx);+ b+}++/// The composite of `doc` over `rect` in CMYK + alpha, mixed on ink values; `None` when+/// [`supports`] is false. Tiles render in parallel on native targets (one at a time on wasm);+/// every tile is independent, so the result doesn't depend on the tiling or the thread count.+pub fn render_cmyk(doc: &Document, rect: Rect) -> Option<CmykBuffer> {+ render_cmyk_tiled(doc, rect, RENDER_TILE)+}++/// [`render_cmyk`] with an explicit tile size (tests check tile independence).+pub fn render_cmyk_tiled(doc: &Document, rect: Rect, tile: i32) -> Option<CmykBuffer> {+ if !supports(doc) {+ return None;+ }+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);+ let cx = Ctx::for_doc(doc, &patterns);+ Some(render_with(doc, rect, tile, &cx))+}++fn render_with(doc: &Document, rect: Rect, tile: i32, cx: &Ctx) -> CmykBuffer {+ let tile = tile.max(1);+ let mut out = CmykBuffer::transparent(rect);+ if rect.is_empty() {+ return out;+ }+ let w = rect.width() as usize;+ let mut tiles = Vec::new();+ let mut y = rect.y0;+ while y < rect.y1 {+ let y1 = y.saturating_add(tile).min(rect.y1);+ let mut x = rect.x0;+ while x < rect.x1 {+ let x1 = x.saturating_add(tile).min(rect.x1);+ tiles.push(Rect::new(x, y, x1, y1));+ x = x1;+ }+ y = y1;+ }+ #[cfg(not(target_arch = "wasm32"))]+ let parts: Vec<CmykBuffer> = {+ use rayon::prelude::*;+ tiles.par_iter().map(|t| render_tile(doc, *t, cx)).collect()+ };+ #[cfg(target_arch = "wasm32")]+ let parts: Vec<CmykBuffer> = tiles.iter().map(|t| render_tile(doc, *t, cx)).collect();+ for part in &parts {+ let pw = part.rect.width() as usize;+ for (row, src) in part.px.chunks_exact(pw.max(1)).enumerate() {+ let o = ((part.rect.y0 - rect.y0) as usize + row) * w + (part.rect.x0 - rect.x0) as usize;+ if let Some(dst) = out.px.get_mut(o..o + pw) {+ dst.copy_from_slice(src);+ }+ }+ }+ out+}++/// [`render_cmyk`] in horizontal bands, top to bottom, handing each band to `sink` (so a huge+/// document is never held as one full-size float composite); `None` when [`supports`] is false.+/// `band_rows` as in [`super::render_bands`].+pub fn render_cmyk_bands<E>(doc: &Document, rect: Rect, band_rows: i32, mut sink: impl FnMut(CmykBuffer) -> Result<(), E>) -> Option<Result<(), E>> {+ if !supports(doc) {+ return None;+ }+ let patterns = pattern::PreparedPatterns::new(&doc.patterns, pattern::PREPARED_PATTERN_BYTES).in_mode(doc.pixel_format().mode);+ let cx = Ctx::for_doc(doc, &patterns);+ let rows = super::band_rows_for(rect.width(), band_rows);+ let mut y = rect.y0;+ while y < rect.y1 {+ let y1 = y.saturating_add(rows).min(rect.y1);+ if let Err(e) = sink(render_with(doc, Rect::new(rect.x0, y, rect.x1, y1), RENDER_TILE, &cx)) {+ return Some(Err(e));+ }+ y = y1;+ }+ Some(Ok(()))+}++#[cfg(test)]+#[path = "cmyk_tests.rs"]+mod tests;diff --git a/crates/compose/src/cmyk_tests.rs b/crates/compose/src/cmyk_tests.rsnew file mode 100644index 000000000..d9e25fded--- /dev/null+++ b/crates/compose/src/cmyk_tests.rs@@ -0,0 +1,454 @@+use photocraft_color::blend::BlendMode;+use photocraft_color::{ColorMode, PixelFormat, SampleType};+use photocraft_doc::{Adjustment, Document, Knockout, Layer, LayerContent, LayerMask};+use photocraft_geom::{Rect, Size};+use photocraft_raster::Surface;+use proptest::prelude::*;++use super::*;++const CMYKA8: PixelFormat = PixelFormat { mode: ColorMode::Cmyk, sample: SampleType::U8, alpha: true };+const CMYK8: PixelFormat = PixelFormat { mode: ColorMode::Cmyk, sample: SampleType::U8, alpha: false };++fn doc(w: u32, h: u32) -> Document {+ Document::new("c", Size::new(w, h), ColorMode::Cmyk, SampleType::U8)+}++fn layer(rects: &[(Rect, Cmyka)]) -> Layer {+ let mut l = Layer::raster("l", CMYKA8);+ for (r, c) in rects {+ if let Some(s) = l.surface_mut() {+ s.fill_rect(*r, c);+ }+ }+ l+}++/// An opaque layer without alpha (as a flattened Background is).+fn paper(w: i32, h: i32, c: [f32; 4]) -> Layer {+ let mut l = Layer::raster("bg", CMYK8);+ if let Some(s) = l.surface_mut() {+ s.fill_rect(Rect::new(0, 0, w, h), &c);+ }+ l+}++fn mask(rects: &[(Rect, f32)], default: f32, density: f32, enabled: bool) -> LayerMask {+ let mut surface = Surface::with_default(PixelFormat::GRAY8, &[default]);+ for (r, v) in rects {+ surface.fill_rect(*r, &[*v]);+ }+ LayerMask { surface, enabled, linked: true, density, feather: 0.0 }+}++/// An 8-bit sample as stored.+fn q(v: f32) -> f32 {+ (v.clamp(0.0, 1.0) * 255.0).round() / 255.0+}++// ---- an independent per-pixel reference -------------------------------------------------------++/// Porter-Duff source-over with straight alpha, written out separately from the compositor.+fn over(b: Cmyka, s: Cmyka, opacity: f32) -> Cmyka {+ let sa = s[4] * opacity;+ let a = sa + b[4] * (1.0 - sa);+ if sa <= 0.0 {+ return b;+ }+ if a <= 0.0 {+ return [0.0; 5];+ }+ let mut o = [0.0; 5];+ for i in 0..4 {+ o[i] = (s[i] * sa + b[i] * b[4] * (1.0 - sa)) / a;+ }+ o[4] = a;+ o+}++fn ref_mask(l: &Layer, x: i32, y: i32) -> f32 {+ l.mask.as_ref().map_or(1.0, |m| if m.enabled { 1.0 - m.density * (1.0 - m.surface.sample_channel(x, y, 0)) } else { 1.0 })+}++fn ref_own(l: &Layer, x: i32, y: i32) -> Cmyka {+ let Some(s) = l.surface() else { return [0.0; 5] };+ let p = s.pixel(x, y);+ let a = if s.format().alpha { p[4] } else { 1.0 };+ [p[0], p[1], p[2], p[3], a * ref_mask(l, x, y)]+}++fn ref_stack(layers: &[Layer], x: i32, y: i32, mut b: Cmyka) -> Cmyka {+ let mut i = 0;+ while i < layers.len() {+ let base = &layers[i];+ let mut j = i + 1;+ while j < layers.len() && layers[j].clipped && !base.clipped {+ j += 1;+ }+ if base.visible {+ b = ref_layer(base, &layers[i + 1..j], x, y, b);+ }+ i = j;+ }+ b+}++fn ref_layer(l: &Layer, clipped: &[Layer], x: i32, y: i32, b: Cmyka) -> Cmyka {+ let op = l.opacity * l.fill_opacity;+ let mut content = match &l.content {+ LayerContent::Group(g) if l.blend == BlendMode::PassThrough && l.fill_opacity >= 1.0 => {+ let r = ref_stack(&g.children, x, y, b);+ if op >= 1.0 && l.mask.is_none() {+ return r;+ }+ let k = op * ref_mask(l, x, y);+ let (wa, wb) = (b[4] * (1.0 - k), r[4] * k);+ let a = wa + wb;+ if a <= 0.0 {+ return [0.0; 5];+ }+ let mut o = [0.0; 5];+ for c in 0..4 {+ o[c] = (b[c] * wa + r[c] * wb) / a;+ }+ o[4] = a;+ return o;+ }+ LayerContent::Group(g) => {+ let mut c = ref_stack(&g.children, x, y, [0.0; 5]);+ c[4] *= ref_mask(l, x, y);+ c+ }+ _ => ref_own(l, x, y),+ };+ for c in clipped.iter().filter(|c| c.visible) {+ if content[4] > 0.0 {+ let a = content[4];+ let r = over([content[0], content[1], content[2], content[3], 1.0], ref_own(c, x, y), c.opacity * c.fill_opacity);+ content = [r[0], r[1], r[2], r[3], a];+ }+ }+ over(b, content, op)+}++fn assert_matches_reference(d: &Document) {+ let rect = Rect::new(-1, -1, d.size.width as i32 + 1, d.size.height as i32 + 1);+ let Some(got) = render_cmyk(d, rect) else { panic!("supported") };+ let rgb = crate::render(d, rect);+ for y in rect.y0..rect.y1 {+ for x in rect.x0..rect.x1 {+ let i = ((y - rect.y0) * rect.width() as i32 + (x - rect.x0)) as usize;+ let (g, want) = (got.px[i], ref_stack(&d.layers, x, y, [0.0; 5]));+ assert!(g.iter().all(|v| v.is_finite()), "({x},{y}) {g:?}");+ // Ink only means something where there is coverage.+ let close = |a: f32, b: f32| (a - b).abs() <= 1e-5;+ assert!(close(g[4], want[4]), "alpha ({x},{y}): {g:?} vs reference {want:?}");+ if want[4] > 1e-4 {+ assert!((0..4).all(|c| close(g[c], want[c])), "ink ({x},{y}): {g:?} vs reference {want:?}");+ }+ // Coverage doesn't depend on the colour model: the RGB compositor agrees.+ assert!((g[4] - rgb.px[i][3]).abs() <= 1e-5, "alpha vs RGB ({x},{y}): {g:?} vs {:?}", rgb.px[i]);+ }+ }+}++// ---- directed tests ---------------------------------------------------------------------------++#[test]+fn opaque_pixels_keep_their_exact_inks() {+ let mut d = doc(6, 4);+ d.layers.push(paper(6, 4, [0.0, 0.0, 0.0, 0.0]));+ // K-only black "type", a rich four-colour patch, then a half-covered patch on top.+ d.layers.push(layer(&[(Rect::new(0, 0, 3, 4), [0.0, 0.0, 0.0, 1.0, 1.0])]));+ d.layers.push(layer(&[(Rect::new(3, 0, 6, 2), [0.2, 0.4, 0.6, 0.1, 1.0])]));+ let got = render_cmyk(&d, d.bounds()).unwrap_or_else(|| panic!("supported"));+ let at = |x: i32, y: i32| got.px[(y * 6 + x) as usize];+ assert_eq!(at(1, 1), [0.0, 0.0, 0.0, 1.0, 1.0], "K stays K-only");+ assert_eq!(at(4, 1), [q(0.2), q(0.4), q(0.6), q(0.1), 1.0], "every ink kept as stored");+ assert_eq!(at(4, 3), [0.0, 0.0, 0.0, 0.0, 1.0], "paper: no ink");+}++#[test]+fn partial_coverage_mixes_ink_values() {+ let mut d = doc(2, 1);+ d.layers.push(paper(2, 1, [0.0, 0.0, 0.0, 0.0]));+ let mut l = layer(&[(Rect::new(0, 0, 2, 1), [0.0, 0.0, 0.0, 1.0, 1.0])]);+ l.opacity = 0.5;+ l.fill_opacity = 0.5;+ d.layers.push(l);+ let got = render_cmyk(&d, d.bounds()).unwrap_or_else(|| panic!("supported"));+ // 25% coverage of K100 over paper: K25 and no other ink.+ assert!((got.px[0][3] - 0.25).abs() < 1e-6 && got.px[0][..3] == [0.0; 3], "{:?}", got.px[0]);+}++#[test]+fn masks_groups_and_clipping_match_the_reference() {+ let mut d = doc(8, 6);+ d.layers.push(paper(8, 6, [0.1, 0.0, 0.0, 0.0]));+ let mut base = layer(&[(Rect::new(1, 1, 7, 5), [0.0, 0.5, 0.0, 0.0, 0.8])]);+ base.mask = Some(mask(&[(Rect::new(0, 0, 4, 6), 0.0)], 1.0, 0.75, true));+ let mut clip = layer(&[(Rect::new(0, 0, 8, 3), [0.0, 0.0, 1.0, 0.2, 1.0])]);+ clip.clipped = true;+ clip.opacity = 0.6;+ let mut iso = Layer::group("iso", vec![layer(&[(Rect::new(2, 0, 5, 6), [0.3, 0.3, 0.3, 0.3, 0.5])])]);+ iso.blend = BlendMode::Normal;+ iso.opacity = 0.7;+ iso.mask = Some(mask(&[(Rect::new(0, 3, 8, 6), 0.25)], 1.0, 1.0, true));+ let mut pass = Layer::group("pass", vec![layer(&[(Rect::new(5, 2, 8, 6), [1.0, 0.0, 0.0, 0.0, 1.0])])]);+ pass.opacity = 0.5;+ pass.mask = Some(mask(&[(Rect::new(6, 0, 8, 6), 0.0)], 1.0, 1.0, true));+ d.layers.extend([base, clip, iso, pass]);+ assert_matches_reference(&d);+}++#[test]+fn unsupported_documents_fall_back() {+ let simple = || {+ let mut d = doc(2, 2);+ d.layers.push(layer(&[(Rect::new(0, 0, 2, 2), [0.0, 0.0, 0.0, 1.0, 1.0])]));+ d+ };+ assert!(supports(&simple()));+ let check = |what: &str, f: &dyn Fn(&mut Layer)| {+ let mut d = simple();+ let mut l = layer(&[(Rect::new(0, 0, 1, 1), [0.5; 5])]);+ f(&mut l);+ d.layers.push(l);+ assert!(!supports(&d), "{what}");+ assert!(render_cmyk(&d, d.bounds()).is_none(), "{what}");+ // An invisible layer doesn't matter.+ if let Some(l) = d.layers.last_mut() {+ l.visible = false;+ }+ assert!(supports(&d), "hidden {what}");+ };+ check("multiply", &|l| l.blend = BlendMode::Multiply);+ check("dissolve", &|l| l.blend = BlendMode::Dissolve);+ check("knockout", &|l| l.advanced.knockout = Knockout::Shallow);+ check("channels", &|l| l.excluded_channels = 1);+ check("nan opacity", &|l| l.opacity = f32::NAN);+ check("adjustment", &|l| l.content = LayerContent::Adjustment(Adjustment::Invert));+ check("rgb pixels", &|l| l.content = LayerContent::Raster(Surface::new(PixelFormat::RGBA8)));+ // Not a CMYK document.+ let mut rgb = simple();+ rgb.mode = ColorMode::Rgb;+ assert!(!supports(&rgb));+ // Too deep: refused without recursing through every level.+ let mut deep = layer(&[(Rect::new(0, 0, 1, 1), [0.5; 5])]);+ for _ in 0..(MAX_DEPTH + 8) {+ deep = Layer::group("g", vec![deep]);+ }+ let mut d = simple();+ d.layers.push(deep);+ assert!(!supports(&d));+}++#[test]+fn non_finite_samples_never_reach_the_output() {+ let fmt = PixelFormat { mode: ColorMode::Cmyk, sample: SampleType::F32, alpha: true };+ let mut d = Document::new("f", Size::new(4, 1), ColorMode::Cmyk, SampleType::F32);+ let mut l = Layer::raster("bad", fmt);+ if let Some(s) = l.surface_mut() {+ s.write_region(+ Rect::new(0, 0, 4, 1),+ &[+ f32::NAN,+ 0.0,+ 0.0,+ 0.0,+ 1.0, //+ 0.0,+ f32::INFINITY,+ 0.0,+ 0.0,+ 1.0, //+ 0.0,+ 0.0,+ f32::NEG_INFINITY,+ 0.0,+ f32::NAN, //+ 0.5,+ 0.5,+ 0.5,+ 0.5,+ 0.5,+ ],+ );+ }+ d.layers.push(l);+ let got = render_cmyk(&d, Rect::new(-2, -2, 6, 3)).unwrap_or_else(|| panic!("supported"));+ assert!(got.px.iter().flatten().all(|v| v.is_finite()), "{:?}", got.px);+}++#[test]+fn empty_and_off_canvas_rects() {+ let mut d = doc(4, 4);+ d.layers.push(layer(&[(Rect::new(0, 0, 4, 4), [0.0, 0.0, 0.0, 1.0, 1.0])]));+ assert!(render_cmyk(&d, Rect::new(2, 2, 2, 2)).is_some_and(|b| b.px.is_empty()));+ let far = render_cmyk(&d, Rect::new(1000, 1000, 1003, 1002)).unwrap_or_else(|| panic!("supported"));+ assert_eq!(far.px, vec![[0.0; 5]; 6]);+}++#[test]+fn bands_equal_the_whole_render() {+ let mut d = doc(300, 700);+ d.layers.push(paper(300, 700, [0.0, 0.1, 0.0, 0.0]));+ d.layers.push(layer(&[(Rect::new(10, 20, 290, 690), [0.4, 0.0, 0.2, 0.9, 0.6])]));+ let whole = render_cmyk(&d, d.bounds()).unwrap_or_else(|| panic!("supported"));+ let mut joined = Vec::new();+ let r = render_cmyk_bands(&d, d.bounds(), 256, |b: CmykBuffer| -> Result<(), ()> {+ joined.extend(b.px);+ Ok(())+ });+ assert_eq!(r, Some(Ok(())));+ assert_eq!(joined, whole.px);+}++// ---- random documents -------------------------------------------------------------------------++#[derive(Debug, Clone)]+struct Spec {+ w: i32,+ h: i32,+ layers: Vec<LayerSpec>,+}++#[derive(Debug, Clone)]+enum LayerSpec {+ Pixels { fills: Vec<(Rect, Cmyka)>, opacity: f32, fill: f32, clipped: bool, visible: bool, mask: Option<MaskSpec> },+ Group { children: Vec<LayerSpec>, pass_through: bool, opacity: f32, fill: f32, mask: Option<MaskSpec> },+}++#[derive(Debug, Clone)]+struct MaskSpec {+ rects: Vec<(Rect, f32)>,+ default: f32,+ density: f32,+ enabled: bool,+}++fn unit() -> impl Strategy<Value = f32> {+ prop_oneof![Just(0.0f32), Just(1.0f32), 0.0f32..=1.0]+}++fn rect(w: i32, h: i32) -> impl Strategy<Value = Rect> {+ (-1..w, -1..h, 1..w + 2, 1..h + 2).prop_map(|(x, y, rw, rh)| Rect::new(x, y, x + rw, y + rh))+}++fn mask_spec(w: i32, h: i32) -> impl Strategy<Value = Option<MaskSpec>> {+ prop::option::of(+ (prop::collection::vec((rect(w, h), unit()), 0..3), unit(), unit(), any::<bool>()).prop_map(|(rects, default, density, enabled)| MaskSpec {+ rects,+ default,+ density,+ enabled,+ }),+ )+}++fn pixels(w: i32, h: i32) -> impl Strategy<Value = LayerSpec> {+ (+ prop::collection::vec((rect(w, h), (unit(), unit(), unit(), unit(), unit())), 1..4),+ unit(),+ unit(),+ any::<bool>(),+ prop::bool::weighted(0.9),+ mask_spec(w, h),+ )+ .prop_map(|(fills, opacity, fill, clipped, visible, mask)| LayerSpec::Pixels {+ fills: fills.into_iter().map(|(r, (c, m, y, k, a))| (r, [c, m, y, k, a])).collect(),+ opacity,+ fill,+ clipped,+ visible,+ mask,+ })+}++fn layer_spec(w: i32, h: i32) -> impl Strategy<Value = LayerSpec> {+ pixels(w, h).prop_recursive(3, 12, 4, move |inner| {+ (prop::collection::vec(inner, 1..4), any::<bool>(), unit(), prop_oneof![Just(1.0f32), unit()], mask_spec(w, h))+ .prop_map(move |(children, pass_through, opacity, fill, mask)| LayerSpec::Group { children, pass_through, opacity, fill, mask })+ })+}++fn spec() -> impl Strategy<Value = Spec> {+ (2i32..9, 2i32..7).prop_flat_map(|(w, h)| prop::collection::vec(layer_spec(w, h), 1..6).prop_map(move |layers| Spec { w, h, layers }))+}++fn build(s: &LayerSpec) -> Layer {+ let make_mask = |m: &MaskSpec| mask(&m.rects, m.default, m.density, m.enabled);+ match s {+ LayerSpec::Pixels { fills, opacity, fill, clipped, visible, mask } => {+ let mut l = layer(fills);+ (l.opacity, l.fill_opacity, l.clipped, l.visible) = (*opacity, *fill, *clipped, *visible);+ l.mask = mask.as_ref().map(make_mask);+ l+ }+ LayerSpec::Group { children, pass_through, opacity, fill, mask } => {+ let mut g = Layer::group("g", children.iter().map(build).collect());+ g.blend = if *pass_through { BlendMode::PassThrough } else { BlendMode::Normal };+ (g.opacity, g.fill_opacity) = (*opacity, *fill);+ g.mask = mask.as_ref().map(make_mask);+ g+ }+ }+}++/// Clipped layers onto a pass-through group take the RGB compositor's isolated-rendering path,+/// which this path leaves alone: such specs are filtered out.+fn clips_onto_pass_through(layers: &[LayerSpec]) -> bool {+ layers.windows(2).any(|w| {+ matches!(w[0], LayerSpec::Group { pass_through: true, fill, .. } if fill >= 1.0)+ && matches!(w[1], LayerSpec::Pixels { clipped: true, visible: true, .. })+ }) || layers.iter().any(|l| matches!(l, LayerSpec::Group { children, .. } if clips_onto_pass_through(children)))+}++proptest! {+ #![proptest_config(ProptestConfig { cases: 400, ..ProptestConfig::default() })]++ /// Random stacks of pixel layers, masks, isolated and pass-through groups and clipping+ /// groups: the native composite equals the independent per-pixel reference, and its+ /// coverage equals the RGB compositor's.+ #[test]+ fn random_documents_match_the_reference(s in spec()) {+ prop_assume!(!clips_onto_pass_through(&s.layers));+ let mut d = doc(s.w as u32, s.h as u32);+ d.layers = s.layers.iter().map(build).collect();+ prop_assume!(supports(&d));+ assert_matches_reference(&d);+ }++ /// Tiling never changes the result (tiles render independently, in any order).+ #[test]+ fn tiling_is_invisible(s in spec(), tile in 1i32..9) {+ prop_assume!(!clips_onto_pass_through(&s.layers));+ let mut d = doc(s.w as u32, s.h as u32);+ d.layers = s.layers.iter().map(build).collect();+ prop_assume!(supports(&d));+ let whole = render_cmyk_tiled(&d, d.bounds(), 1024);+ prop_assert_eq!(render_cmyk_tiled(&d, d.bounds(), tile), whole);+ }+}++/// Where the composite is a single opaque layer's pixel (opaque, full opacity, binary masks),+/// the native ink, shown through the document's profile, is the colour the RGB compositor shows.+#[test]+fn opaque_results_look_the_same_as_the_rgb_compositor() {+ let mut d = doc(8, 4);+ d.layers.push(paper(8, 4, [0.0, 0.0, 0.0, 0.0]));+ d.layers.push(layer(&[(Rect::new(0, 0, 4, 4), [0.0, 0.0, 0.0, 1.0, 1.0]), (Rect::new(4, 0, 8, 2), [0.7, 0.1, 0.0, 0.0, 1.0])]));+ let mut top = layer(&[(Rect::new(2, 1, 7, 4), [0.0, 0.9, 0.9, 0.0, 1.0])]);+ top.mask = Some(mask(&[(Rect::new(5, 0, 8, 4), 0.0)], 1.0, 1.0, true));+ d.layers.push(top);+ let native = render_cmyk(&d, d.bounds()).unwrap_or_else(|| panic!("supported"));+ let rgb = crate::render(&d, d.bounds());+ let space = crate::cmyk_space(&d);+ let fmt = PixelFormat { mode: ColorMode::Cmyk, sample: SampleType::F32, alpha: true };+ photocraft_color::convert::with_cmyk_space(space.as_ref(), || {+ for (n, r) in native.px.iter().zip(&rgb.px) {+ let shown = photocraft_raster::to_rgba(&fmt, n);+ assert!((0..4).all(|c| (shown[c] - r[c]).abs() <= 1e-4), "native {n:?} shows {shown:?}, RGB compositor {r:?}");+ }+ });+}diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rsindex 712033e54..c9419e82b 100644--- a/crates/compose/src/lib.rs+++ b/crates/compose/src/lib.rs@@ -19,6 +19,7 @@pub mod adjust;pub mod advanced;pub mod bounds;+pub mod cmyk;pub mod effects;pub mod fill_layout;pub mod gradient_fill;diff --git a/crates/io/src/flat.rs b/crates/io/src/flat.rsindex a64af9c71..c6529c6fd 100644--- a/crates/io/src/flat.rs+++ b/crates/io/src/flat.rs@@ -275,14 +275,20 @@ pub fn document_to_image(doc: &Document, warnings: &mut Vec<String>) -> Result<Iy = 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::Cmyk || fmt.mode == ColorMode::Lab {- // The compositor renders CMYK/Lab documents in sRGB (CMYK through the built-in- // profile), so the file is tagged sRGB.+ 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());}@@ -337,6 +343,71 @@ pub fn document_to_image(doc: &Document, warnings: &mut Vec<String>) -> Result<IOk(img.with_icc(icc).with_meta(meta))}+/// A CMYK document's composite as interleaved CMYK + alpha samples (`cs`), with whether every+/// pixel came out opaque (the caller then drops the alpha). Stacks the native CMYK compositor+/// handles are mixed on their ink values, so opaque pixels keep their exact inks; any other+/// document is composited in RGB and converted back through its own CMYK profile, as PSD+/// export's merged image is. Rendered and quantised in bands on every core.+fn cmyk_composite(doc: &Document, canvas: Rect, cs: CSample, n: usize, warnings: &mut Vec<String>) -> Result<(Vec<u8>, bool), IoError> {+ let mut data = try_buffer(n, 5 * cs.bytes())?;+ let mut opaque = true;+ let put = |out: &mut Vec<u8>, v: f32| {+ let v = if v.is_finite() { v } else { 0.0 };+ 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 native = photocraft_compose::cmyk::render_cmyk_bands(doc, canvas, 0, |band| -> Result<(), ()> {+ opaque &= band.px.iter().all(|p| p[4] >= 1.0);+ let parts = crate::pixels::par_map(crate::pixels::bands(band.px.len()), |range| {+ let mut out = Vec::with_capacity(range.len() * 5 * cs.bytes());+ for p in band.px.get(range).unwrap_or_default() {+ for v in p {+ put(&mut out, *v);+ }+ }+ out+ });+ for part in parts {+ data.extend_from_slice(&part);+ }+ Ok(())+ });+ if native.is_none() {+ // Through RGB and back: the colour model is kept, exact ink values are not.+ warnings.push("CMYK composite converted back through the document's CMYK profile; ink values can differ from the layers'".to_string());+ let space = photocraft_compose::cmyk_space(doc);+ let to = PixelFormat::new(ColorMode::Cmyk, SampleType::F32, 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| {+ // The composite came through the document's CMYK profile: convert back through it.+ photocraft_color::convert::with_cmyk_space(space.as_ref(), || {+ let mut out = Vec::with_capacity(range.len() * 5 * cs.bytes());+ let mut v = [0.0f32; 5];+ for p in band.px.get(range).unwrap_or_default() {+ photocraft_raster::from_rgba_into(&to, *p, &mut v);+ for x in v {+ put(&mut out, x);+ }+ }+ out+ })+ });+ for part in parts {+ data.extend_from_slice(&part);+ }+ Ok(())+ });+ }+ if opaque {+ drop_alpha(&mut data, 4 * cs.bytes(), cs.bytes());+ }+ Ok((data, opaque))+}+/// An empty buffer with room for `pixels × bytes_per_pixel` bytes, or an error (not an abort)/// when that much memory can't be had.pub(crate) fn try_buffer(pixels: usize, bytes_per_pixel: usize) -> Result<Vec<u8>, IoError> {diff --git a/crates/io/tests/cmyk_export.rs b/crates/io/tests/cmyk_export.rsnew file mode 100644index 000000000..44ecc4bba--- /dev/null+++ b/crates/io/tests/cmyk_export.rs@@ -0,0 +1,131 @@+//! A CMYK document is written to flat formats as CMYK with its own profile whatever its layers+//! (#2220), mixing Normal pixel 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 other_stacks_stay_cmyk_through_the_profile() {+ // A Multiply layer isn't composited on ink values (yet): 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::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 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[..]));+ // Multiplying magenta over paper adds magenta ink; it doesn't empty the page.+ assert!(pixel(&img, 8, 6)[1] > 0.3, "{:?}", pixel(&img, 8, 6));+}++#[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);+}