Skip to content

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

Keep Duotone ink colours when converting to RGB, CMYK or Lab (#2383) (#2614)

Fabio Lussi2d6154a69bc0
diff --git a/crates/engine/src/color_cmds.rs b/crates/engine/src/color_cmds.rs
index ac96cf72b..dad511186 100644
--- a/crates/engine/src/color_cmds.rs
+++ b/crates/engine/src/color_cmds.rs
@@ -16,7 +16,7 @@ use std::sync::{Arc, Mutex, Weak};
use photocraft_cms::{Builtin, ColorSpace, GamutCheck, Intent, Lut3d, Profile, SampleKind, Transform};
use photocraft_color::{Color, ColorMode, PixelFormat, SampleType};
-use photocraft_doc::{DocId, Document, Effect, Fill, FxPaint, Layer, LayerContent};
+use photocraft_doc::{DocId, Document, Duotone, Effect, Fill, FxPaint, Layer, LayerContent};
use photocraft_raster::Surface;
use serde_json::{Value, json};
@@ -576,23 +576,24 @@ fn convert_color(c: &mut Color, from: ColorMode, to: ColorMode, t: &Transform) {
c.c = nc;
}
-fn convert_fill(f: &mut Fill, from: ColorMode, to: ColorMode, t: &Transform) {
+fn convert_fill(f: &mut Fill, cc: &mut dyn FnMut(&mut Color)) {
match f {
- Fill::Solid(c) => convert_color(c, from, to, t),
- Fill::Gradient { stops, .. } => stops.iter_mut().for_each(|s| convert_color(&mut s.1, from, to, t)),
+ Fill::Solid(c) => cc(c),
+ Fill::Gradient { stops, .. } => stops.iter_mut().for_each(|s| cc(&mut s.1)),
Fill::Pattern { .. } => {}
}
}
-fn convert_layer_colors(l: &mut Layer, from: ColorMode, to: ColorMode, t: &Transform) {
- let mut cc = |c: &mut Color| convert_color(c, from, to, t);
+/// Applies `cc` to every colour value of `l` (fill, text, shape and effect colours), recursing
+/// into groups.
+fn convert_layer_colors(l: &mut Layer, cc: &mut dyn FnMut(&mut Color)) {
let mut touched_fx = false;
for e in &mut l.effects.items {
touched_fx = true;
match e {
Effect::DropShadow(s) | Effect::InnerShadow(s) => cc(&mut s.color),
- Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint_colors(&mut g.paint, &mut cc),
- Effect::Stroke(s) => paint_colors(&mut s.paint, &mut cc),
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint_colors(&mut g.paint, cc),
+ Effect::Stroke(s) => paint_colors(&mut s.paint, cc),
Effect::ColorOverlay { color, .. } => cc(color),
Effect::GradientOverlay { gradient, .. } => gradient.stops.iter_mut().for_each(|s| cc(&mut s.1)),
Effect::Satin(s) => cc(&mut s.color),
@@ -605,7 +606,7 @@ fn convert_layer_colors(l: &mut Layer, from: ColorMode, to: ColorMode, t: &Trans
}
let _ = touched_fx;
match &mut l.content {
- LayerContent::Fill(f) => convert_fill(f, from, to, t),
+ LayerContent::Fill(f) => convert_fill(f, cc),
LayerContent::Text(tx) => {
cc(&mut tx.color);
for r in &mut tx.runs {
@@ -614,22 +615,22 @@ fn convert_layer_colors(l: &mut Layer, from: ColorMode, to: ColorMode, t: &Trans
}
LayerContent::Shape(sh) => {
if let Some(f) = &mut sh.fill {
- convert_fill(f, from, to, t);
+ convert_fill(f, cc);
}
if let Some(s) = &mut sh.stroke {
- convert_fill(&mut s.paint, from, to, t);
+ convert_fill(&mut s.paint, cc);
}
}
LayerContent::Group(g) => {
for c in &mut g.children {
- convert_layer_colors(c, from, to, t);
+ convert_layer_colors(c, cc);
}
}
_ => {}
}
}
-fn paint_colors(p: &mut FxPaint, cc: &mut impl FnMut(&mut Color)) {
+fn paint_colors(p: &mut FxPaint, cc: &mut dyn FnMut(&mut Color)) {
match p {
FxPaint::Color(c) => cc(c),
FxPaint::Gradient(g) => g.stops.iter_mut().for_each(|s| cc(&mut s.1)),
@@ -640,9 +641,13 @@ fn paint_colors(p: &mut FxPaint, cc: &mut impl FnMut(&mut Color)) {
/// Converts every pixel layer (and cached text/shape/smart pixels and fill caches) of `doc`
/// from its profile to `dst`, switching the mode to `dst`'s colour space. Masks, alpha
/// channels and the selection are untouched; fill, text, shape and effect colours are
-/// converted. The document is tagged with `dst`.
+/// converted. A Duotone document going to a colour space starts from its ink colours
+/// ([`ink_duotone`]). The document is tagged with `dst`.
pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc: bool) -> Result<()> {
let to_mode = space_mode(dst.color_space).ok_or_else(|| EngineError::Other(format!("cannot convert to a {:?} profile", dst.color_space)))?;
+ if to_mode != ColorMode::Grayscale {
+ ink_duotone(doc);
+ }
let src = document_profile(doc);
let from_mode = doc.pixel_format().mode;
let t = Transform::new(&src, dst, intent, bpc).map_err(cms_err)?;
@@ -652,7 +657,7 @@ pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc:
*surf = convert_surface(surf, from_mode, f, &t);
});
for l in &mut doc.layers {
- convert_layer_colors(l, from_mode, to_mode, &t);
+ convert_layer_colors(l, &mut |c| convert_color(c, from_mode, to_mode, &t));
// Preserved PSD blocks describing colours in the old mode no longer apply.
}
doc.mode = to_mode;
@@ -663,6 +668,76 @@ pub fn convert_document(doc: &mut Document, dst: &Profile, intent: Intent, bpc:
Ok(())
}
+/// Turns a Duotone document into the sRGB document it displays as: every gray pixel and colour
+/// value becomes its printed ink colour ([`Duotone::render`], sRGB like the inks), so converting
+/// to a colour mode keeps the inks' look, as Photoshop converts them to their equivalents.
+/// Other documents (and Duotone without inks) are left alone.
+fn ink_duotone(doc: &mut Document) {
+ if doc.mode != ColorMode::Duotone {
+ return;
+ }
+ let Some(d) = doc.duotone.take_if(|d| !d.inks.is_empty()) else { return };
+ crate::image_cmds::for_each_surface(&mut doc.layers, false, &mut |surf, _| *surf = ink_surface(surf, &d));
+ for l in &mut doc.layers {
+ convert_layer_colors(l, &mut |c| {
+ if matches!(c.mode, ColorMode::Grayscale | ColorMode::Duotone) {
+ let [r, g, b] = d.render(c.c[0]);
+ *c = Color::rgba(r, g, b, c.alpha);
+ }
+ });
+ }
+ doc.mode = ColorMode::Rgb;
+ doc.icc_profile = Some(Builtin::Srgb.profile().to_bytes());
+}
+
+/// The RGB surface of a gray surface's ink colours (same depth and alpha), one parallel pass
+/// over the tiles. Non-gray surfaces are returned unchanged.
+fn ink_surface(s: &Surface, d: &Duotone) -> Surface {
+ use rayon::prelude::*;
+ let sf = s.format();
+ if sf.mode != ColorMode::Grayscale {
+ return s.clone();
+ }
+ let to = PixelFormat { mode: ColorMode::Rgb, ..sf };
+ let (ss, ds) = (sf.channels(), to.channels());
+ let ink = |src: &[f32], out: &mut [f32]| {
+ let [r, g, b] = d.render(src.first().copied().unwrap_or(0.0));
+ for (o, v) in out.iter_mut().zip([r, g, b].into_iter().chain(src.get(1).copied())) {
+ *o = v;
+ }
+ };
+ let mut dp = vec![0.0f32; ds];
+ ink(&s.default_pixel(), &mut dp);
+ let mut out = Surface::with_default(to, &dp);
+ let tiles: Vec<_> = s.tiles().map(|(c, t)| (*c, t.clone())).collect();
+ let inked: Vec<Vec<u8>> = tiles
+ .par_iter()
+ .map(|(_, t)| {
+ let src = t.bytes();
+ let n = src.len() / sf.bytes_per_pixel().max(1);
+ let mut dst = vec![0u8; n * to.bytes_per_pixel()];
+ let (mut px, mut o) = ([0.0f32; 2], [0.0f32; 4]);
+ for i in 0..n {
+ for (k, v) in px.iter_mut().enumerate().take(ss) {
+ *v = photocraft_color::read_sample(src, sf.sample, i * ss + k);
+ }
+ ink(&px[..ss], &mut o[..ds]);
+ for (k, v) in o.iter().enumerate().take(ds) {
+ photocraft_color::write_sample(&mut dst, to.sample, i * ds + k, *v);
+ }
+ }
+ dst
+ })
+ .collect();
+ for ((c, _), bytes) in tiles.iter().zip(inked) {
+ let tile = out.tile_mut(*c).bytes_mut();
+ if tile.len() == bytes.len() {
+ tile.copy_from_slice(&bytes);
+ }
+ }
+ out
+}
+
/// Image › Mode › RGB/Grayscale/CMYK/Lab through the CMS. Params: `profile` (destination,
/// default the mode's working profile), `intent` (default relative), `bpc` (default true).
pub fn convert_mode(s: &mut Session, mode: ColorMode, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/mode_cmds/tests.rs b/crates/engine/src/mode_cmds/tests.rs
index 850da98f8..b7b7068fd 100644
--- a/crates/engine/src/mode_cmds/tests.rs
+++ b/crates/engine/src/mode_cmds/tests.rs
@@ -259,3 +259,82 @@ fn modes_round_trip_through_pcraft() {
assert_eq!(back.color_table, doc(&s).color_table);
assert_eq!(back.mode, ColorMode::Indexed);
}
+
+/// Leaving Duotone for a colour mode keeps the printed look (#2383): the converted pixels are
+/// the displayed ink colours, through the destination profile. Grayscale drops the inks.
+#[test]
+fn duotone_to_colour_modes_keeps_the_ink_colours() {
+ use photocraft_cms::{Builtin, Transform};
+ let configs = [
+ json!({"type": "duotone"}),
+ json!({"type": "monotone", "inks": [{"name": "Orange", "color": "#ff8000", "curve": [[0, 0], [100, 100]]}]}),
+ json!({"type": "quadtone"}),
+ ];
+ for depth in [8, 16, 32] {
+ for cfg in &configs {
+ for mode in ["rgb", "cmyk", "lab", "grayscale"] {
+ let ctx = format!("{depth}-bit {cfg} → {mode}");
+ let mut s = session(16, 2, depth, "gray");
+ paint(&mut s, |x, _| {
+ let v = x as f32 / 15.0;
+ [v, v, v, 1.0]
+ });
+ s.execute("image.mode.duotone", cfg.clone()).unwrap();
+ let before = s.active().unwrap().doc.clone();
+ let gray: Vec<f32> = (0..16).map(|x| before.layers[0].surface().unwrap().pixel(x, 1)[0]).collect();
+ let shown = photocraft_compose::render(&display_document(&before).unwrap(), Rect::from_xywh(0, 1, 16, 1)).px;
+ s.execute(&format!("image.mode.{mode}"), json!({})).unwrap();
+ let d = doc(&s);
+ assert!(d.duotone.is_none(), "{ctx}");
+ let surf = d.layers[0].surface().unwrap();
+ let target = match mode {
+ "rgb" => ColorMode::Rgb,
+ "cmyk" => ColorMode::Cmyk,
+ "lab" => ColorMode::Lab,
+ _ => ColorMode::Grayscale,
+ };
+ assert_eq!(d.mode, target, "{ctx}");
+ let srgb = Builtin::Srgb.profile();
+ let dst = crate::color_cmds::working_profile(target);
+ let t = Transform::new(srgb, &dst, s.color.settings.intent(), s.color.settings.bpc).unwrap();
+ for x in 0..16 {
+ let got = surf.pixel(x, 1);
+ let want: Vec<f32> = if target == ColorMode::Grayscale {
+ vec![gray[x as usize]]
+ } else {
+ let mut o = [0.0f32; 16];
+ t.eval(&shown[x as usize][..3], &mut o);
+ o[..target.color_channels()].to_vec()
+ };
+ // The display's gradient map samples the inks at 33 stops; dark CMYK
+ // separations magnify that a little.
+ let tol = if target == ColorMode::Cmyk { 0.03 } else { 0.02 };
+ for (g, w) in got.iter().zip(&want) {
+ assert!((g - w).abs() < tol, "{ctx} x={x}: got {got:?}, want {want:?}");
+ }
+ }
+ // Undo brings back the inks and the gray pixels.
+ s.execute("edit.undo", json!({})).unwrap();
+ let back = doc(&s);
+ assert_eq!((back.mode, &back.duotone), (ColorMode::Duotone, &before.duotone), "{ctx}");
+ assert_eq!(back.layers[0].surface().unwrap().pixel(7, 1), before.layers[0].surface().unwrap().pixel(7, 1), "{ctx}");
+ }
+ }
+ }
+}
+
+/// Colours stored in a Duotone document (fill layers) take the ink colours too.
+#[test]
+fn duotone_to_rgb_inks_fill_layer_colours() {
+ let mut s = session(4, 4, 8, "gray");
+ s.execute("image.mode.duotone", json!({"type": "monotone", "inks": [{"name": "Orange", "color": "#ff8000"}]})).unwrap();
+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#808080"})).unwrap();
+ s.execute("image.mode.rgb", json!({})).unwrap();
+ let d = doc(&s);
+ let Some(LayerContent::Fill(photocraft_doc::Fill::Solid(c))) = d.layers.last().map(|l| &l.content) else { panic!("no fill layer") };
+ assert_eq!(c.mode, ColorMode::Rgb);
+ // Gray 0.5 is half-density orange: (1, 0.75, 0.5).
+ for (g, w) in c.c[..3].iter().zip([1.0, 0.75, 0.5]) {
+ assert!((g - w).abs() < 0.02, "{c:?}");
+ }
+}