PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Fill layers keep their colours in the document's mode (#1915)
kayrockscreenprinting19256a29f527
diff --git a/crates/color/src/lib.rs b/crates/color/src/lib.rsindex 17c59a6b6..a33437963 100644--- a/crates/color/src/lib.rs+++ b/crates/color/src/lib.rs@@ -170,6 +170,27 @@ impl Color {}}+ /// This colour in `mode`'s model, converted as pixels written to a surface of that mode+ /// are (through sRGB); unchanged when it is already in `mode`. Indexed and Multichannel+ /// documents keep RGB colours, as [`Color::to_rgb`] reads them.+ pub fn in_mode(self, mode: ColorMode) -> Color {+ let rgb_like = |m: ColorMode| matches!(m, ColorMode::Rgb | ColorMode::Indexed | ColorMode::Multichannel);+ if self.mode == mode || (rgb_like(self.mode) && rgb_like(mode)) {+ return self;+ }+ let rgb = self.to_rgb();+ let (mode, c) = match mode {+ ColorMode::Rgb | ColorMode::Indexed | ColorMode::Multichannel => (ColorMode::Rgb, [rgb[0], rgb[1], rgb[2], 0.0]),+ ColorMode::Grayscale | ColorMode::Bitmap | ColorMode::Duotone => (mode, [convert::rgb_to_gray(rgb), 0.0, 0.0, 0.0]),+ ColorMode::Cmyk => (mode, convert::rgb_to_cmyk(rgb)),+ ColorMode::Lab => {+ let l = convert::srgb_to_lab(rgb);+ (mode, [l[0] / 100.0, (l[1] + 128.0) / 255.0, (l[2] + 128.0) / 255.0, 0.0])+ }+ };+ Color { mode, c, alpha: self.alpha }+ }+pub fn to_rgba8(&self) -> [u8; 4] {let [r, g, b] = self.to_rgb();let q = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;@@ -181,6 +202,24 @@ impl Color {mod tests {use super::*;+ #[test]+ fn colors_convert_into_a_document_mode() {+ let blue = Color::rgba(0.0, 0.0, 1.0, 0.5);+ let g = blue.in_mode(ColorMode::Grayscale);+ assert_eq!((g.mode, g.alpha), (ColorMode::Grayscale, 0.5));+ assert!((g.c[0] - 0.114).abs() < 1e-6, "{g:?}");+ // RGB-based modes keep RGB colours; a colour already in the mode is unchanged.+ assert_eq!(blue.in_mode(ColorMode::Indexed), blue);+ assert_eq!(g.in_mode(ColorMode::Grayscale), g);+ for mode in [ColorMode::Cmyk, ColorMode::Lab] {+ let c = blue.in_mode(mode);+ assert_eq!(c.mode, mode);+ let back = c.in_mode(ColorMode::Rgb);+ assert_eq!(back.mode, ColorMode::Rgb);+ assert_eq!(back.to_rgb(), c.to_rgb(), "{mode:?}: back to RGB shows the same colour");+ }+ }+#[test]fn pixel_format_sizes() {assert_eq!(PixelFormat::RGBA8.bytes_per_pixel(), 4);diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rsindex 0f0fc1aec..93e0d3ae0 100644--- a/crates/doc/src/lib.rs+++ b/crates/doc/src/lib.rs@@ -337,6 +337,17 @@ impl Fill {pub fn gradient(stops: Vec<(f32, Color)>, angle: f32, scale: f32, style: GradientStyle, reverse: bool) -> Fill {Fill::Gradient { stops, angle, scale, style, reverse, opacity_stops: Vec::new(), midpoints: Vec::new(), offset: (0.0, 0.0), dither: false, align: true }}++ /// This fill with its colours in `mode`'s model (see [`Color::in_mode`]): a fill layer's+ /// colours are in its document's mode, which the compositors read them as.+ pub fn in_mode(mut self, mode: ColorMode) -> Fill {+ match &mut self {+ Fill::Solid(c) => *c = c.in_mode(mode),+ Fill::Gradient { stops, .. } => stops.iter_mut().for_each(|(_, c)| *c = c.in_mode(mode)),+ Fill::Pattern { .. } => {}+ }+ self+ }}#[derive(Clone, Debug, PartialEq)]diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex cfc6f9d7a..178861396 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -747,7 +747,8 @@ fn build() -> Vec<CommandSpec> {|s, p| {let c = color_param(p, "color", s.tools.foreground);let id = s.edit("New Color Fill Layer", |doc, active| {- let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3]))));+ let fill = Fill::Solid(Color::rgba(c[0], c[1], c[2], c[3])).in_mode(doc.mode);+ let mut l = Layer::new(doc.next_layer_name("Color Fill"), LayerContent::Fill(fill));mask_new_layer(doc, &mut l, p, "layer.newFillLayer.solidColor")?;let id = doc.insert_above(*active, l);*active = Some(id);@@ -776,7 +777,8 @@ fn build() -> Vec<CommandSpec> {1.0,style,reverse,- );+ )+ .in_mode(doc.mode);let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));mask_new_layer(doc, &mut l, p, "layer.newFillLayer.gradient")?;let id = doc.insert_above(*active, l);diff --git a/crates/engine/src/fill_layer_mode_tests.rs b/crates/engine/src/fill_layer_mode_tests.rsnew file mode 100644index 000000000..69f786baa--- /dev/null+++ b/crates/engine/src/fill_layer_mode_tests.rs@@ -0,0 +1,133 @@+//! Fill layers made in a Grayscale, CMYK or Lab document keep their colours in the document's+//! mode, so they composite as the same colour painted on a pixel layer does (#1905).++use crate::Session;+use photocraft_doc::{ColorMode, Fill, LayerContent};+use serde_json::{Value, json};++const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];+const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];++fn session(mode: &str, depth: u32) -> Session {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 64, "height": 32, "mode": mode, "depth": depth, "background": "white"})).unwrap();+ s.tools.foreground = BLUE;+ s.tools.background = GREEN;+ s+}++fn pixel(s: &mut Session, x: i32, y: i32) -> [f32; 4] {+ let v = s.execute("document.pixel", json!({"x": x, "y": y})).unwrap();+ let a: Vec<f32> = v.as_array().unwrap().iter().map(|c| c.as_f64().unwrap() as f32).collect();+ [a[0], a[1], a[2], a[3]]+}++/// The composite of `color` painted with Edit › Fill on a new pixel layer: what a fill layer of+/// that colour must look like.+fn painted(mode: &str, depth: u32, color: [f32; 4]) -> [f32; 4] {+ let mut s = session(mode, depth);+ s.execute("layer.new.layer", json!({})).unwrap();+ s.execute("edit.fill", json!({"contents": "color", "color": color})).unwrap();+ pixel(&mut s, 10, 10)+}++fn close(a: [f32; 4], b: [f32; 4], tol: f32) -> bool {+ a.iter().zip(&b).all(|(x, y)| (x - y).abs() <= tol)+}++fn active_fill(s: &Session) -> Fill {+ let st = s.active().unwrap();+ match &st.doc.layer(st.active_layer.unwrap()).unwrap().content {+ LayerContent::Fill(f) => f.clone(),+ other => panic!("not a fill layer: {other:?}"),+ }+}++fn fill_colors(f: &Fill) -> Vec<photocraft_doc::Color> {+ match f {+ Fill::Solid(c) => vec![*c],+ Fill::Gradient { stops, .. } => stops.iter().map(|s| s.1).collect(),+ Fill::Pattern { .. } => Vec::new(),+ }+}++fn assert_in_mode(s: &Session, mode: ColorMode, what: &str) {+ let f = active_fill(s);+ for c in fill_colors(&f) {+ assert_eq!(c.mode, mode, "{what}: {f:?}");+ }+}++#[test]+fn solid_color_fill_matches_edit_fill() {+ for (mode, cm) in [("gray", ColorMode::Grayscale), ("cmyk", ColorMode::Cmyk), ("lab", ColorMode::Lab)] {+ for depth in [8, 16, 32] {+ let mut s = session(mode, depth);+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap();+ assert_in_mode(&s, cm, mode);+ let got = pixel(&mut s, 10, 10);+ let want = painted(mode, depth, BLUE);+ assert!(close(got, want, 0.01), "{mode}/{depth}: fill layer {got:?}, painted {want:?}");+ if cm == ColorMode::Grayscale {+ assert!((got[0] - 0.114).abs() < 0.01 && got[0] == got[1] && got[1] == got[2], "{mode}/{depth}: {got:?}");+ }+ }+ }+}++#[test]+fn gradient_fill_layers_are_gray_in_a_grayscale_document() {+ let grey = |p: [f32; 4]| (p[0] - p[1]).abs() < 1e-4 && (p[1] - p[2]).abs() < 1e-4;+ let ways: [(&str, Value); 3] = [+ ("layer.newFillLayer.gradient", json!({"from": "#0000ff", "to": "#00ff00", "angle": 0})),+ ("gradient.fill.create", json!({"from": [0, 16], "to": [64, 16]})),+ ("gradient.presets.apply", json!({"preset": "Blue 01", "angle": 0})),+ ];+ for depth in [8, 16, 32] {+ for (cmd, p) in &ways {+ let mut s = session("gray", depth);+ s.execute(cmd, p.clone()).unwrap();+ assert_in_mode(&s, ColorMode::Grayscale, cmd);+ for x in [1, 32, 62] {+ let px = pixel(&mut s, x, 16);+ assert!(grey(px), "{cmd} at 8/16/32 = {depth}, x {x}: {px:?}");+ }+ }+ }+}++#[test]+fn gradient_edits_keep_colours_in_the_document_mode() {+ let mut s = session("cmyk", 8);+ s.execute("gradient.fill.create", json!({"from": [0, 16], "to": [64, 16]})).unwrap();+ s.execute("gradient.fill.set", json!({"stops": [[0, "#ff0000"], [1, "#0000ff"]]})).unwrap();+ assert_in_mode(&s, ColorMode::Cmyk, "gradient.fill.set");+ let start = pixel(&mut s, 0, 16);+ let red = painted("cmyk", 8, [1.0, 0.0, 0.0, 1.0]);+ assert!(close(start, red, 0.02), "{start:?} vs {red:?}");+ s.execute("gradient.presets.select", json!({"preset": "Green 01"})).unwrap();+ assert_in_mode(&s, ColorMode::Cmyk, "gradient.presets.select");+}++#[test]+fn rgb_documents_keep_rgb_fill_colours() {+ let mut s = session("rgb", 8);+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap();+ assert_eq!(active_fill(&s), Fill::Solid(photocraft_doc::Color::rgb(0.0, 0.0, 1.0)));+ assert!(close(pixel(&mut s, 10, 10), BLUE, 1e-6));+}++/// A grayscale fill layer converts like any other colour when the mode changes, and a fill made+/// in Gray survives undo/redo unchanged.+#[test]+fn gray_fill_converts_with_the_document() {+ let mut s = session("gray", 16);+ s.execute("layer.newFillLayer.solidColor", json!({"color": "#0000ff"})).unwrap();+ let before = pixel(&mut s, 10, 10);+ s.execute("image.mode.rgb", json!({})).unwrap();+ assert_in_mode(&s, ColorMode::Rgb, "after Image › Mode › RGB");+ let after = pixel(&mut s, 10, 10);+ assert!(close(before, after, 0.01), "{before:?} -> {after:?}");+ s.execute("edit.undo", json!({})).unwrap();+ assert_in_mode(&s, ColorMode::Grayscale, "undo");+}diff --git a/crates/engine/src/gradient_fill_cmds.rs b/crates/engine/src/gradient_fill_cmds.rsindex 31e7b0eb8..24b0905cd 100644--- a/crates/engine/src/gradient_fill_cmds.rs+++ b/crates/engine/src/gradient_fill_cmds.rs@@ -303,7 +303,8 @@ pub fn new_layer(s: &Session, doc: &Document, p: &Value) -> Result<Layer> {return Err(bad(CMD, "the document is empty"));}let (angle, scale, offset) = gf::from_handles(style, from, to, canvas, 0.0);- let fill = Fill::Gradient { stops, angle, scale: clamp_scale(scale), style, reverse, opacity_stops, midpoints: Vec::new(), offset, dither, align: false };+ let fill = Fill::Gradient { stops, angle, scale: clamp_scale(scale), style, reverse, opacity_stops, midpoints: Vec::new(), offset, dither, align: false }+ .in_mode(doc.mode);let mut l = Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill));l.opacity = opacity;l.blend = blend;@@ -341,8 +342,9 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {fn replace_fill(s: &mut Session, id: LayerId, label: &str, new: Fill) -> Result<()> {s.edit(label, |doc, _| {+ let mode = doc.mode;let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;- l.content = LayerContent::Fill(new);+ l.content = LayerContent::Fill(new.in_mode(mode));Ok(())})}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 9d3d748df..89b1af5a3 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -633,5 +633,7 @@ pub(crate) fn fix_selection(st: &mut DocState) {}}+#[cfg(test)]+mod fill_layer_mode_tests;#[cfg(test)]mod tests;diff --git a/crates/engine/src/presets/gradients.rs b/crates/engine/src/presets/gradients.rsindex 6a5e20641..1165164a0 100644--- a/crates/engine/src/presets/gradients.rs+++ b/crates/engine/src/presets/gradients.rs@@ -417,10 +417,11 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {{let (stops_new, opacity_new) = g.fill_stops(s.tools.foreground, s.tools.background);s.edit("Change Gradient Fill", |doc, _| {+ let mode = doc.mode;if let Some(l) = doc.layer_mut(id)&& let LayerContent::Fill(Fill::Gradient { stops, opacity_stops, midpoints, .. }) = &mut l.content{- *stops = stops_new;+ *stops = stops_new.into_iter().map(|(t, c)| (t, c.in_mode(mode))).collect();*opacity_stops = opacity_new;midpoints.clear();}@@ -440,7 +441,7 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {let style = crate::layer_style::gradient_style(p.get("style").and_then(Value::as_str).unwrap_or("linear"));let reverse = p.get("reverse").and_then(Value::as_bool).unwrap_or(false);let id = s.edit("New Gradient Fill Layer", |doc, active| {- let fill = Fill::gradient(stops, angle, scale, style, reverse);+ let fill = Fill::gradient(stops, angle, scale, style, reverse).in_mode(doc.mode);let id = doc.insert_above(*active, Layer::new(doc.next_layer_name("Gradient Fill"), LayerContent::Fill(fill)));*active = Some(id);Ok(id)diff --git a/crates/ui-egui/src/gradient_ui.rs b/crates/ui-egui/src/gradient_ui.rsindex b102117fa..f7049e726 100644--- a/crates/ui-egui/src/gradient_ui.rs+++ b/crates/ui-egui/src/gradient_ui.rs@@ -106,11 +106,16 @@ fn fill_of(l: &Layer) -> Option<&Fill> {fn edited_fill(app: &PhotocraftApp, layer: &Layer, canvas: Rect32, cmd: &str, p: &Value) -> Option<Fill> {let f = fill_of(layer)?;let (fg, bg) = (app.session.tools.foreground, app.session.tools.background);- match cmd {+ let edited = match cmd {cmds::SET => cmds::apply_set(layer, f, canvas, p, fg, bg).ok(),cmds::STOP => cmds::apply_stop(f, p, fg, bg).ok(),_ => None,- }+ }?;+ // As the command commits it: colours in the document's mode.+ Some(match app.session.active() {+ Some(st) => edited.in_mode(st.doc.mode),+ None => edited,+ })}/// Options-bar params of a new live gradient.