Skip to content

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

Layer style colours keep the document's mode (Gray, CMYK) (#2103)

kayrockscreenprinting5630e112b479
diff --git a/crates/doc/src/effects.rs b/crates/doc/src/effects.rs
index 06028a400..1b502ca00 100644
--- a/crates/doc/src/effects.rs
+++ b/crates/doc/src/effects.rs
@@ -276,6 +276,31 @@ pub enum Effect {
}
impl Effect {
+ /// This effect with its colours in `mode`'s model ([`Color::in_mode`]): a layer's effect
+ /// colours are in its document's mode, as Image › Mode keeps them.
+ pub fn in_mode(mut self, mode: photocraft_color::ColorMode) -> Effect {
+ let cc = |c: &mut Color| *c = c.in_mode(mode);
+ let paint = |p: &mut FxPaint| match p {
+ FxPaint::Color(c) => cc(c),
+ FxPaint::Gradient(g) => g.stops.iter_mut().for_each(|s| cc(&mut s.1)),
+ FxPaint::Pattern { .. } => {}
+ };
+ match &mut self {
+ Effect::DropShadow(s) | Effect::InnerShadow(s) => cc(&mut s.color),
+ Effect::OuterGlow(g) | Effect::InnerGlow(g) => paint(&mut g.paint),
+ Effect::Stroke(s) => paint(&mut s.paint),
+ 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),
+ Effect::BevelEmboss(b) => {
+ cc(&mut b.highlight_color);
+ cc(&mut b.shadow_color);
+ }
+ Effect::PatternOverlay { .. } => {}
+ }
+ self
+ }
+
/// Whether this instance is switched on.
pub fn enabled(&self) -> bool {
match self {
diff --git a/crates/engine/src/extra_cmds.rs b/crates/engine/src/extra_cmds.rs
index 658e75e1e..9a6353c8b 100644
--- a/crates/engine/src/extra_cmds.rs
+++ b/crates/engine/src/extra_cmds.rs
@@ -744,8 +744,11 @@ pub fn specs() -> Vec<CommandSpec> {
},
|s, p| {
let id = layer_param(s, p)?;
- let (fx, blend, fill, advanced) = s.style_clipboard.clone().ok_or(EngineError::Other("no layer style has been copied".into()))?;
+ let (mut fx, blend, fill, advanced) = s.style_clipboard.clone().ok_or(EngineError::Other("no layer style has been copied".into()))?;
s.edit("Paste Layer Style", |doc, _| {
+ // A style copied from a document in another mode takes this one's colours.
+ let mode = doc.mode;
+ fx.items = std::mem::take(&mut fx.items).into_iter().map(|e| e.in_mode(mode)).collect();
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
l.effects = fx;
l.blend = blend;
diff --git a/crates/engine/src/fx_mode_tests.rs b/crates/engine/src/fx_mode_tests.rs
new file mode 100644
index 000000000..660a69b10
--- /dev/null
+++ b/crates/engine/src/fx_mode_tests.rs
@@ -0,0 +1,116 @@
+//! Layer style colours made in a Grayscale or CMYK document are in the document's mode, so a red
+//! Color Overlay in a Gray document composites grey, like red painted with Edit › Fill (the
+//! effect counterpart of #1905; Image › Mode already converts them).
+
+use crate::Session;
+use serde_json::{Value, json};
+
+const KINDS: [&str; 9] = ["dropShadow", "innerShadow", "outerGlow", "innerGlow", "satin", "colorOverlay", "gradientOverlay", "stroke", "bevelEmboss"];
+
+fn session(mode: &str, depth: u32) -> Session {
+ let mut s = Session::new();
+ s.execute("file.new", json!({"width": 48, "height": 32, "mode": mode, "depth": depth, "background": "white"})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 12, "y": 8, "width": 24, "height": 16})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s
+}
+
+/// The modes of every colour stored in the active layer's effects (any `{mode, c, alpha}`).
+fn effect_colour_modes(s: &Session) -> Vec<String> {
+ fn walk(v: &Value, out: &mut Vec<String>) {
+ match v {
+ Value::Object(o) => {
+ if let (Some(m), true, true) = (o.get("mode").and_then(Value::as_str), o.contains_key("c"), o.contains_key("alpha")) {
+ out.push(m.to_string());
+ }
+ o.values().for_each(|v| walk(v, out));
+ }
+ Value::Array(a) => a.iter().for_each(|v| walk(v, out)),
+ _ => {}
+ }
+ }
+ let st = s.active().unwrap();
+ let l = st.doc.layer(st.active_layer.unwrap()).unwrap();
+ let mut out = Vec::new();
+ for e in &l.effects.items {
+ walk(&serde_json::to_value(e).unwrap(), &mut out);
+ }
+ out
+}
+
+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]]
+}
+
+fn mode_name(mode: &str) -> &'static str {
+ match mode {
+ "gray" => "Grayscale",
+ "cmyk" => "Cmyk",
+ _ => "Rgb",
+ }
+}
+
+fn assert_in_mode(s: &Session, mode: &str, what: &str) {
+ let modes = effect_colour_modes(s);
+ assert!(!modes.is_empty(), "{what}: no colours found");
+ assert!(modes.iter().all(|m| m == mode_name(mode)), "{what}: colours {modes:?} in a {mode} document");
+}
+
+#[test]
+fn every_effect_command_stores_colours_in_the_document_mode() {
+ for mode in ["gray", "cmyk", "rgb"] {
+ for depth in [8, 16, 32] {
+ for kind in KINDS {
+ let mut s = session(mode, depth);
+ s.execute(&format!("layer.layerStyle.{kind}"), json!({"color": "#ff3300"})).unwrap();
+ assert_in_mode(&s, mode, &format!("{mode}/{depth} {kind}"));
+ }
+ }
+ }
+}
+
+#[test]
+fn the_layer_style_dialog_stores_colours_in_the_document_mode() {
+ for mode in ["gray", "cmyk"] {
+ let mut s = session(mode, 8);
+ let effects: Vec<Value> = KINDS.iter().map(|k| json!({"kind": k, "params": {"color": "#ff3300"}})).collect();
+ s.execute("layer.layerStyle.replace", json!({ "effects": effects })).unwrap();
+ assert_in_mode(&s, mode, &format!("{mode} layer.layerStyle.replace"));
+ }
+}
+
+#[test]
+fn a_red_color_overlay_is_grey_in_a_grayscale_document() {
+ for depth in [8, 16, 32] {
+ let mut s = session("gray", depth);
+ s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap();
+ let p = pixel(&mut s, 20, 15);
+ // Red painted into a Gray document: 0.299.
+ assert!((p[0] - 0.299).abs() < 0.01 && p[0] == p[1] && p[1] == p[2], "{depth}-bit: {p:?}");
+ }
+}
+
+#[test]
+fn a_style_pasted_or_applied_into_a_grayscale_document_converts() {
+ // Copied from an RGB document, pasted into a Gray one.
+ let mut s = session("rgb", 8);
+ s.execute("layer.layerStyle.colorOverlay", json!({"color": "#ff0000"})).unwrap();
+ s.execute("layer.layerStyle.copyLayerStyle", json!({})).unwrap();
+ s.execute("file.new", json!({"width": 48, "height": 32, "mode": "gray", "depth": 8, "background": "white"})).unwrap();
+ s.execute("layer.new.layer", json!({})).unwrap();
+ s.execute("select.rect", json!({"x": 12, "y": 8, "width": 24, "height": 16})).unwrap();
+ s.execute("edit.fill", json!({"contents": "color", "color": "#808080"})).unwrap();
+ s.execute("select.deselect", json!({})).unwrap();
+ s.execute("layer.layerStyle.pasteLayerStyle", json!({})).unwrap();
+ assert_in_mode(&s, "gray", "Paste Layer Style");
+ let p = pixel(&mut s, 20, 15);
+ assert!(p[0] == p[1] && p[1] == p[2], "pasted overlay is neutral: {p:?}");
+ // A style preset (RGB colours) applied in a Gray document.
+ let mut s = session("gray", 16);
+ s.execute("style.presets.apply", json!({"preset": "Gold"})).unwrap();
+ assert_in_mode(&s, "gray", "style.presets.apply Gold");
+}
diff --git a/crates/engine/src/layer_style.rs b/crates/engine/src/layer_style.rs
index 15d4a88d6..c410a46cc 100644
--- a/crates/engine/src/layer_style.rs
+++ b/crates/engine/src/layer_style.rs
@@ -531,8 +531,9 @@ fn replace_effects(s: &mut Session, p: &Value) -> Result<Value> {
for pat in &pats {
crate::pattern_cmds::ensure_in_doc(doc, pat);
}
+ let mode = doc.mode;
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
- l.effects.items = list;
+ l.effects.items = list.into_iter().map(|e| e.in_mode(mode)).collect();
l.effects.enabled = true;
Ok(())
})?;
@@ -552,6 +553,8 @@ fn set_effect(s: &mut Session, p: &Value, kind: &str) -> Result<Value> {
if let Some(pat) = &pattern {
crate::pattern_cmds::ensure_in_doc(doc, pat);
}
+ // Colours in the document's mode, as Image › Mode keeps them.
+ let fx = fx.in_mode(doc.mode);
let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?;
l.effects.enabled = true;
match l.effects.items.iter_mut().find(|e| same_kind(e, &fx)) {
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 1c4bec9ed..b368c67cb 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -647,3 +647,6 @@ mod fill_layer_mode_tests;
mod pattern_mode_tests;
#[cfg(test)]
mod tests;
+
+#[cfg(test)]
+mod fx_mode_tests;
diff --git a/crates/engine/src/presets/styles.rs b/crates/engine/src/presets/styles.rs
index a2c29a47c..a8c60d6a4 100644
--- a/crates/engine/src/presets/styles.rs
+++ b/crates/engine/src/presets/styles.rs
@@ -187,6 +187,9 @@ fn apply(s: &mut Session, p: &Value) -> Result<Value> {
for pat in &pats {
crate::pattern_cmds::ensure_in_doc(doc, pat);
}
+ // A preset's colours are RGB; the layer's are in the document's mode.
+ let mode = doc.mode;
+ let effects: Vec<_> = effects.iter().cloned().map(|e| e.in_mode(mode)).collect();
for id in &ids {
let l = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?;
// Styles can't sit on the Background: Photoshop turns it into a normal layer first.