Skip to content

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

Color Picker: CMYK foreground fills a CMYK document with the picked inks (#4196) (#4339)

Valentin Klein3ba0e9419c41
diff --git a/crates/engine/src/brush_cmds.rs b/crates/engine/src/brush_cmds.rs
index 16b7d72a2..abc6b49d9 100644
--- a/crates/engine/src/brush_cmds.rs
+++ b/crates/engine/src/brush_cmds.rs
@@ -249,7 +249,7 @@ fn erase_locked(brush: &mut BrushSettings, lock: bool, bg: [f32; 4]) {
/// The document's own CMYK profile (absent, built-in or not a CMYK document: `None`, the
/// default conversions), which the stroke's colour conversions must honour — the compositors
/// and composite exports enter the same scope.
-fn doc_cmyk_space(s: &Session) -> Option<std::sync::Arc<photocraft_color::convert::CmykSpace>> {
+pub(crate) fn doc_cmyk_space(s: &Session) -> Option<std::sync::Arc<photocraft_color::convert::CmykSpace>> {
photocraft_color::convert::CmykSpace::for_profile(s.active().and_then(|d| d.doc.icc_profile.as_ref()))
}
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs
index 7a1cc4ffb..09db339bf 100644
--- a/crates/engine/src/commands.rs
+++ b/crates/engine/src/commands.rs
@@ -966,11 +966,39 @@ fn build() -> Vec<CommandSpec> {
has_paintable,
crate::brush_cmds::paint_stroke
),
- cmd!("tools.setColors", "Set Colors", [], None, r##"{"foreground":"#rrggbb"?,"background":"#rrggbb"?}"##, always, |s, p| {
- s.tools.foreground = color_param(p, "foreground", s.tools.foreground);
- s.tools.background = color_param(p, "background", s.tools.background);
- Ok(Value::Null)
- }),
+ cmd!(
+ "tools.setColors",
+ "Set Colors",
+ [],
+ None,
+ r##"{"foreground":"#rrggbb"|[r,g,b,a?]?,"background":same?,"foregroundCmyk":[c,m,y,k]? (inks 0..1 the foreground was picked as: a CMYK document is filled with exactly these),"backgroundCmyk":same?}"##,
+ always,
+ |s, p| {
+ let cmyk = |key: &str| -> Result<Option<[f32; 4]>> {
+ let Some(v) = p.get(key).filter(|v| !v.is_null()) else { return Ok(None) };
+ let inks: Option<Vec<f32>> = v
+ .as_array()
+ .filter(|a| a.len() == 4)
+ .and_then(|a| a.iter().map(|x| x.as_f64().filter(|x| x.is_finite()).map(|x| x.clamp(0.0, 1.0) as f32)).collect());
+ match inks.as_deref() {
+ Some(&[c, m, y, k]) => Ok(Some([c, m, y, k])),
+ _ => Err(bad("tools.setColors", format!("`{key}` must be [c, m, y, k] numbers 0..1"))),
+ }
+ };
+ let (fg_cmyk, bg_cmyk) = (cmyk("foregroundCmyk")?, cmyk("backgroundCmyk")?);
+ s.tools.foreground = color_param(p, "foreground", s.tools.foreground);
+ s.tools.background = color_param(p, "background", s.tools.background);
+ if let Some(k) = fg_cmyk {
+ let [r, g, b, _] = s.tools.foreground;
+ s.tools.remember_cmyk([r, g, b], k);
+ }
+ if let Some(k) = bg_cmyk {
+ let [r, g, b, _] = s.tools.background;
+ s.tools.remember_cmyk([r, g, b], k);
+ }
+ Ok(Value::Null)
+ }
+ ),
cmd!("tools.swapColors", "Switch Foreground and Background Colors", [], Some("X"), "{}", always, |s, _| {
std::mem::swap(&mut s.tools.foreground, &mut s.tools.background);
Ok(Value::Null)
diff --git a/crates/engine/src/fill_cmds.rs b/crates/engine/src/fill_cmds.rs
index 130977ce2..d99ebd9a5 100644
--- a/crates/engine/src/fill_cmds.rs
+++ b/crates/engine/src/fill_cmds.rs
@@ -25,6 +25,12 @@ fn bad(msg: impl Into<String>) -> EngineError {
/// What a pixel of the filled area gets before blending.
enum Source {
Color([f32; 4]),
+ /// An opaque colour that was picked as CMYK inks: `rgba` is its sRGB stand-in (what other
+ /// colour models and blend modes use), `cmyk` the inks a CMYK target gets as they are.
+ Cmyk {
+ rgba: [f32; 4],
+ cmyk: [f32; 4],
+ },
/// Straight RGBA per pixel of `rect` (row-major).
Pixels(Rect, Vec<[f32; 4]>),
}
@@ -33,6 +39,7 @@ impl Source {
fn at(&self, x: i32, y: i32) -> [f32; 4] {
match self {
Source::Color(c) => *c,
+ Source::Cmyk { rgba, .. } => *rgba,
Source::Pixels(r, px) => {
if !r.contains(x, y) {
return [0.0; 4];
@@ -97,9 +104,9 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
let mut out = json!({ "contents": contents });
let restore = contents == "history";
let source = match contents {
- "foreground" => Source::Color(s.tools.foreground),
- "background" => Source::Color(s.tools.background),
- "color" => Source::Color(color_param(p, "color", s.tools.foreground)),
+ "foreground" => color_source(s, s.tools.foreground),
+ "background" => color_source(s, s.tools.background),
+ "color" => color_source(s, color_param(p, "color", s.tools.foreground)),
"black" => Source::Color([0.0, 0.0, 0.0, 1.0]),
"gray" => Source::Color([128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]),
"white" => Source::Color([1.0; 4]),
@@ -145,15 +152,44 @@ pub fn fill(s: &mut Session, p: &Value) -> Result<Value> {
if area.is_empty() {
return Ok(out);
}
- s.edit("Fill", |doc, _| {
- let sel = doc.selection.clone();
- let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
- blend_into(surf, area, &source, sel.as_ref(), Blend { mode, opacity, keep_alpha: preserve || lock, restore })?;
- Ok(())
+ // The document's own CMYK profile converts the fill colour, like the compositor and brush.
+ let cmyk = crate::brush_cmds::doc_cmyk_space(s);
+ photocraft_color::convert::with_cmyk_space(cmyk.as_ref(), || {
+ s.edit("Fill", |doc, _| {
+ let sel = doc.selection.clone();
+ let (surf, lock) = crate::channel_cmds::target_surface(doc, id, p)?;
+ blend_into(surf, area, &source, sel.as_ref(), Blend { mode, opacity, keep_alpha: preserve || lock, restore })?;
+ Ok(())
+ })
})?;
Ok(out)
}
+/// A fill colour: the inks it was picked as when it was picked as CMYK (#4196), else plain sRGB.
+fn color_source(s: &Session, c: [f32; 4]) -> Source {
+ match s.tools.picked_cmyk([c[0], c[1], c[2]]) {
+ Some(cmyk) if c[3] >= 1.0 => Source::Cmyk { rgba: c, cmyk },
+ _ => Source::Color(c),
+ }
+}
+
+/// `source`'s opaque colour as samples of `fmt` (alpha last, as in [`from_rgba_into`]), or `None`
+/// for a source that is not one colour. A CMYK pick keeps its inks in a CMYK target.
+fn encode_color(fmt: &photocraft_color::PixelFormat, source: &Source, enc: &mut [f32; 8]) -> Option<usize> {
+ let (rgba, cmyk) = match source {
+ Source::Color(c) if c[3] >= 1.0 => (*c, None),
+ Source::Cmyk { rgba, cmyk } => (*rgba, Some(*cmyk)),
+ _ => return None,
+ };
+ let n = from_rgba_into(fmt, rgba, enc);
+ if let Some(k) = cmyk
+ && fmt.mode == photocraft_color::ColorMode::Cmyk
+ {
+ enc[..4].copy_from_slice(&k);
+ }
+ Some(n)
+}
+
fn read_rgba(src: &Surface, area: Rect, purpose: &str) -> Result<Vec<[f32; 4]>> {
let len = (area.width() as usize)
.checked_mul(area.height() as usize)
@@ -336,12 +372,9 @@ fn blend_into(surf: &mut Surface, area: Rect, source: &Source, sel: Option<&Surf
let fmt = surf.format();
// An opaque colour in Normal mode at 100 % that may replace alpha: fully covered tiles become
// one shared solid tile (copy-on-write), which costs nothing per pixel.
- let solid = match source {
- Source::Color(c) if c[3] >= 1.0 && b.mode == BlendMode::Normal && b.opacity >= 1.0 && (!b.keep_alpha || !fmt.alpha) => {
- let mut enc = [0.0f32; 8];
- let n = from_rgba_into(&fmt, *c, &mut enc);
- Some(surf.solid_tile(enc.get(..n).unwrap_or(&[])))
- }
+ let mut enc = [0.0f32; 8];
+ let solid = match encode_color(&fmt, source, &mut enc) {
+ Some(n) if b.mode == BlendMode::Normal && b.opacity >= 1.0 && (!b.keep_alpha || !fmt.alpha) => Some(surf.solid_tile(enc.get(..n).unwrap_or(&[]))),
_ => None,
};
let count = area.tiles().count();
@@ -409,9 +442,8 @@ fn blend_tile(bytes: &mut [u8], fmt: &photocraft_color::PixelFormat, origin: Rec
let mut enc = [0.0f32; 8];
// An opaque colour at full coverage in Normal mode just replaces the colour (and the alpha
// unless it is kept): copy its encoded bytes.
- let opaque = match source {
- Source::Color(c) if c[3] >= 1.0 && mode == BlendMode::Normal => {
- let m = from_rgba_into(fmt, *c, &mut enc);
+ let opaque = match encode_color(fmt, source, &mut enc) {
+ Some(m) if mode == BlendMode::Normal => {
let mut bytes = vec![0u8; bpp];
photocraft_raster::encode_pixel(fmt, enc.get(..m.min(n)).unwrap_or(&[]), &mut bytes);
// Keeping alpha: copy the colour samples only (alpha is the last sample).
diff --git a/crates/engine/src/fill_key_cmds.rs b/crates/engine/src/fill_key_cmds.rs
index 47559e237..8beff0dc0 100644
--- a/crates/engine/src/fill_key_cmds.rs
+++ b/crates/engine/src/fill_key_cmds.rs
@@ -292,6 +292,35 @@ mod tests {
}
}
+ /// The inks of the active layer's pixel at (0, 0), exactly as stored.
+ fn inks(s: &Session) -> Vec<f32> {
+ let st = s.active().unwrap();
+ let surf = st.doc.layer(st.active_layer.unwrap()).unwrap().surface().unwrap();
+ surf.read_region(photocraft_geom::Rect::new(0, 0, 1, 1)).into_iter().take(4).collect()
+ }
+
+ /// #4196: a foreground picked as CMYK 100/0/0/0 fills a CMYK document with those inks, not with
+ /// whatever its sRGB stand-in converts back to (100/28/0/17).
+ #[test]
+ fn cmyk_pick_fills_a_cmyk_document_with_the_picked_inks() {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 4, "height": 4})).unwrap();
+ s.execute("image.mode.cmyk", json!({})).unwrap();
+ let rgb = photocraft_color::convert::cmyk_to_rgb([1.0, 0.0, 0.0, 0.0]).map(|c| c.clamp(0.0, 1.0));
+ s.execute("tools.setColors", json!({"foreground": rgb, "foregroundCmyk": [1.0, 0.0, 0.0, 0.0]})).unwrap();
+ s.execute("edit.fillForeground", json!({})).unwrap();
+ let got = inks(&s);
+ assert!(got.iter().zip([1.0, 0.0, 0.0, 0.0]).all(|(a, b)| (a - b).abs() < 0.01), "{got:?}");
+ }
+
+ #[test]
+ fn malformed_cmyk_pick_is_an_error_not_a_panic() {
+ let mut s = session();
+ for bad in [json!([1.0]), json!("cyan"), json!([1.0, 0.0, 0.0, "x"]), json!({"c": 1})] {
+ assert!(s.execute("tools.setColors", json!({"foregroundCmyk": bad})).is_err());
+ }
+ }
+
#[test]
fn registered_with_photoshop_default_shortcuts() {
let sc = |id| crate::commands::find(id).and_then(|c| c.shortcut);
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 4df2a0a81..27a2f941a 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -299,9 +299,31 @@ pub struct ToolState {
/// The foreground/background pair of the edit target that isn't current: the layer pixels'
/// colours while a mask is targeted, the mask's while the pixels are (#2166).
pub other_colors: [[f32; 4]; 2],
+ /// Colours picked as CMYK, newest last: the sRGB colour that stands for them and the ink
+ /// values chosen. The tool colours are stored as sRGB, and an sRGB round trip does not give
+ /// back what was typed (100/0/0/0 cyan is outside sRGB), so a CMYK document is filled with
+ /// the inks the person picked (#4196). Matched by colour, so it follows a swap, a reset or a
+ /// mask pair without bookkeeping.
+ pub cmyk_picks: Vec<([f32; 3], [f32; 4])>,
}
impl ToolState {
+ /// How many CMYK picks are remembered.
+ const CMYK_PICKS: usize = 8;
+
+ /// Remember that sRGB colour `rgb` was picked as the inks `cmyk` (each 0..1).
+ pub fn remember_cmyk(&mut self, rgb: [f32; 3], cmyk: [f32; 4]) {
+ self.cmyk_picks.retain(|(c, _)| *c != rgb);
+ self.cmyk_picks.push((rgb, cmyk));
+ let extra = self.cmyk_picks.len().saturating_sub(Self::CMYK_PICKS);
+ self.cmyk_picks.drain(..extra);
+ }
+
+ /// The inks `rgb` was picked as, if it was picked as CMYK.
+ pub fn picked_cmyk(&self, rgb: [f32; 3]) -> Option<[f32; 4]> {
+ self.cmyk_picks.iter().rev().find(|(c, _)| *c == rgb).map(|(_, k)| *k)
+ }
+
/// Photoshop's colour pair for a layer mask that has none yet: white foreground, black
/// background (reveal-paint first).
pub const MASK_COLORS: [[f32; 4]; 2] = [[1.0, 1.0, 1.0, 1.0], [0.0, 0.0, 0.0, 1.0]];
@@ -340,6 +362,7 @@ impl Default for ToolState {
current_preset: None,
mask_targeted: false,
other_colors: Self::MASK_COLORS,
+ cmyk_picks: Vec::new(),
}
}
}
diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rs
index 30752c462..24f0afd78 100644
--- a/crates/ui-egui/src/color_picker_ui.rs
+++ b/crates/ui-egui/src/color_picker_ui.rs
@@ -171,7 +171,12 @@ pub fn open(app: &mut PhotocraftApp, target: &str) -> u64 {
let c = if target == "background" { app.session.tools.background } else { app.session.tools.foreground };
let rgb = [c[0], c[1], c[2]];
let label = if target == "background" { "Color Picker (Background Color)" } else { "Color Picker (Foreground Color)" };
- app.ui.open_dialog(DialogKind::Command, initial_fields(target, label, rgb))
+ let mut fields = initial_fields(target, label, rgb);
+ // A colour that was picked as CMYK shows the inks it was picked as, not what its sRGB stand-in converts to (#4196).
+ if let Some(cmyk) = app.session.tools.picked_cmyk(rgb) {
+ fields.insert("__cmyk".into(), json!(cmyk));
+ }
+ app.ui.open_dialog(DialogKind::Command, fields)
}
/// Shared initial state for every target; the picker layout is independent of its destination.
@@ -787,7 +792,12 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,
// The pasteboard menu's Select Custom Color…: the custom colour, and use it.
return app.run("prefs.set", json!({"values": {"interface.canvasColor": "custom", "interface.canvasCustomColor": color}}));
}
- let r = app.run("tools.setColors", json!({ target: color }))?;
+ let mut params = json!({ target: color });
+ // The CMYK values the person entered stay the colour's inks: a CMYK document is filled with them (#4196).
+ if let Some(cmyk) = parse_hex(color).and_then(|rgb| kept::<4>(f, "__cmyk", rgb, photocraft_color::convert::cmyk_to_rgb)) {
+ params[format!("{target}Cmyk")] = json!(cmyk);
+ }
+ let r = app.run("tools.setColors", params)?;
if target == "foreground" {
crate::type_tool::foreground_changed(app);
}
@@ -1109,6 +1119,24 @@ mod tests {
assert_eq!(hex([app.session.tools.background[0], app.session.tools.background[1], app.session.tools.background[2]]), "#3366cc");
}
+ /// #4196: CMYK values typed into the picker survive OK, so the colour fills a CMYK document with those inks and
+ /// reopening the picker shows them again.
+ #[test]
+ fn cmyk_values_survive_ok_and_a_reopen() {
+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Default::default());
+ let cyan = [1.0, 0.0, 0.0, 0.0];
+ let id = open(&mut app, "foreground");
+ let d = app.ui.dialog_mut(id).unwrap();
+ set_rgb(&mut d.fields, photocraft_color::convert::cmyk_to_rgb(cyan).map(|c| c.clamp(0.0, 1.0)), Keep::Cmyk(cyan));
+ let fields = d.fields.clone();
+ confirm(&mut app, &fields).unwrap();
+ let fg = app.session.tools.foreground;
+ assert_eq!(app.session.tools.picked_cmyk([fg[0], fg[1], fg[2]]), Some(cyan));
+ let id = open(&mut app, "foreground");
+ let again = current(&app.ui.dialogs.iter().find(|d| d.id == id).unwrap().fields);
+ assert_eq!(again.cmyk, cyan);
+ }
+
fn dialog_color(app: &PhotocraftApp, id: u64) -> &str {
app.ui.dialogs.iter().find(|d| d.id == id).and_then(|d| d.fields.get("color")).and_then(Value::as_str).unwrap()
}