Skip to content

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

Selective Color and Color Lookup: a wrong-typed key is an error (#1790)

kayrockscreenprinting1284e79d232a
diff --git a/crates/engine/src/adjust_cmds.rs b/crates/engine/src/adjust_cmds.rs
index 000b7e4c8..e42ffbaa8 100644
--- a/crates/engine/src/adjust_cmds.rs
+++ b/crates/engine/src/adjust_cmds.rs
@@ -31,42 +31,77 @@ fn num(p: &Value, key: &str, default: f32) -> f32 {
p.get(key).and_then(Value::as_f64).map_or(default, |v| v as f32)
}
+/// `key`'s value; a null counts as missing (as in `adjust_params`).
+fn given<'a>(p: &'a Value, key: &str) -> Option<&'a Value> {
+ p.get(key).filter(|v| !v.is_null())
+}
+
+fn opt_str<'a>(cmd: &str, p: &'a Value, key: &str) -> Result<Option<&'a str>> {
+ match given(p, key) {
+ None => Ok(None),
+ Some(Value::String(s)) => Ok(Some(s)),
+ Some(_) => Err(bad(cmd, format!("`{key}` must be a string"))),
+ }
+}
+
+fn opt_bool(cmd: &str, p: &Value, key: &str) -> Result<Option<bool>> {
+ match given(p, key) {
+ None => Ok(None),
+ Some(Value::Bool(b)) => Ok(Some(*b)),
+ Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))),
+ }
+}
+
+/// A percentage in -100..100 (clamped); anything but a finite number is an error.
+fn percent(cmd: &str, key: &str, v: &Value) -> Result<f32> {
+ let x = v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad(cmd, format!("`{key}` must be a number")))?;
+ Ok((x as f32).clamp(-100.0, 100.0))
+}
+
/// Selective Color from params. Accepts per-range arrays (`"reds":[c,m,y,k]` in percent) and the
/// dialog's single-range form (`"colors":"reds","cyan":…,"magenta":…,"yellow":…,"black":…`);
-/// `"method":"relative|absolute"`. Unspecified ranges keep `base`'s values.
-pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Adjustment {
+/// `"method":"relative|absolute"`. Unspecified ranges keep `base`'s values; a key of the wrong
+/// type is an error.
+pub fn selective_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjustment> {
+ const CMD: &str = "selectiveColor";
let (mut relative, mut adj) = match base {
Some(Adjustment::SelectiveColor { relative, adjustments }) => (*relative, *adjustments),
_ => (true, [[0.0; 4]; 9]),
};
- if let Some(m) = p.get("method").and_then(Value::as_str) {
- relative = m != "absolute";
+ match opt_str(CMD, p, "method")? {
+ None => {}
+ Some("relative") => relative = true,
+ Some("absolute") => relative = false,
+ Some(m) => return Err(bad(CMD, format!("`method` must be \"relative\" or \"absolute\", not `{m}`"))),
}
- if let Some(b) = p.get("relative").and_then(Value::as_bool) {
+ if let Some(b) = opt_bool(CMD, p, "relative")? {
relative = b;
}
- for (i, key) in RANGES.iter().enumerate() {
- if let Some(a) = p.get(*key).and_then(Value::as_array) {
- for (k, v) in a.iter().take(4).enumerate() {
- adj[i][k] = (v.as_f64().unwrap_or(0.0) as f32).clamp(-100.0, 100.0);
- }
+ for (row, key) in adj.iter_mut().zip(RANGES) {
+ let Some(v) = given(p, key) else { continue };
+ let a = v.as_array().filter(|a| a.len() == 4).ok_or_else(|| bad(CMD, format!("`{key}` must be an array of 4 numbers [c, m, y, k]")))?;
+ for (slot, x) in row.iter_mut().zip(a) {
+ *slot = percent(CMD, key, x)?;
}
}
- let range = p.get("colors").and_then(Value::as_str).and_then(|c| RANGES.iter().position(|r| *r == c));
- if let Some(i) = range {
- for (k, key) in ["cyan", "magenta", "yellow", "black"].iter().enumerate() {
- if let Some(v) = p.get(*key).and_then(Value::as_f64) {
- adj[i][k] = (v as f32).clamp(-100.0, 100.0);
+ if let Some(c) = opt_str(CMD, p, "colors")? {
+ let Some((row, _)) = adj.iter_mut().zip(RANGES).find(|(_, r)| *r == c) else {
+ return Err(bad(CMD, format!("unknown range `{c}` (ranges: {})", RANGES.join(", "))));
+ };
+ for (slot, key) in row.iter_mut().zip(["cyan", "magenta", "yellow", "black"]) {
+ if let Some(v) = given(p, key) {
+ *slot = percent(CMD, key, v)?;
}
}
}
- Adjustment::SelectiveColor { relative, adjustments: adj }
+ Ok(Adjustment::SelectiveColor { relative, adjustments: adj })
}
/// Color Lookup from params: `"lut"` (a built-in look id or `"none"`), `"file"` (a .cube / .3dl /
/// .look path, native only) or `"data"` (the file's text, with `"fileName"` naming its format),
/// `"interpolation":"trilinear|tetrahedral"`, `"dither":bool`. The table is embedded in the
-/// layer, as Photoshop does. Unspecified fields keep `base`'s values.
+/// layer, as Photoshop does. Unspecified fields keep `base`'s values; a key of the wrong type is an
+/// error.
pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjustment> {
const CMD: &str = "colorLookup";
let (mut name, mut lut, mut size, mut tetrahedral, mut dither) = match base {
@@ -74,7 +109,7 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
_ => (String::new(), None, 0, false, false),
};
let mut loaded: Option<(photocraft_cms::lutfile::LutFile, String)> = None;
- if let Some(id) = p.get("lut").and_then(Value::as_str) {
+ if let Some(id) = opt_str(CMD, p, "lut")? {
if id == "none" || id.is_empty() {
name.clear();
lut = None;
@@ -85,12 +120,13 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
loaded = Some((f, label));
}
}
- if let Some(text) = p.get("data").and_then(Value::as_str) {
- let file_name = p.get("fileName").and_then(Value::as_str).unwrap_or("lut.cube");
+ let file_name = opt_str(CMD, p, "fileName")?;
+ if let Some(text) = opt_str(CMD, p, "data")? {
+ let file_name = file_name.unwrap_or("lut.cube");
let f = photocraft_cms::lutfile::parse(file_name, text.as_bytes()).map_err(|e| bad(CMD, e.0))?;
loaded = Some((f, base_name(file_name)));
}
- if let Some(path) = p.get("file").and_then(Value::as_str).filter(|s| !s.is_empty()) {
+ if let Some(path) = opt_str(CMD, p, "file")?.filter(|s| !s.is_empty()) {
let bytes = read_file(path).ok_or_else(|| bad(CMD, format!("can't read {path}")))?;
let f = photocraft_cms::lutfile::parse(path, &bytes).map_err(|e| bad(CMD, format!("{path}: {}", e.0)))?;
loaded = Some((f, base_name(path)));
@@ -109,13 +145,16 @@ pub fn lookup_from_params(p: &Value, base: Option<&Adjustment>) -> Result<Adjust
size = f.size as u32;
lut = Some(std::sync::Arc::new(f.data));
}
- if let Some(i) = p.get("interpolation").and_then(Value::as_str) {
- tetrahedral = i == "tetrahedral";
+ match opt_str(CMD, p, "interpolation")? {
+ None => {}
+ Some("trilinear") => tetrahedral = false,
+ Some("tetrahedral") => tetrahedral = true,
+ Some(i) => return Err(bad(CMD, format!("`interpolation` must be \"trilinear\" or \"tetrahedral\", not `{i}`"))),
}
- if let Some(b) = p.get("tetrahedral").and_then(Value::as_bool) {
+ if let Some(b) = opt_bool(CMD, p, "tetrahedral")? {
tetrahedral = b;
}
- if let Some(b) = p.get("dither").and_then(Value::as_bool) {
+ if let Some(b) = opt_bool(CMD, p, "dither")? {
dither = b;
}
Ok(Adjustment::ColorLookup { name, lut, size, tetrahedral, dither })
@@ -143,7 +182,7 @@ fn read_file(_: &str) -> Option<Vec<u8>> {
pub fn update_adjustment(existing: &Adjustment, p: &Value) -> Option<Result<Adjustment>> {
let empty = p.as_object().is_none_or(|o| o.keys().all(|k| matches!(k.as_str(), "layer" | "coalesce" | "__kind")));
match existing {
- Adjustment::SelectiveColor { .. } => Some(Ok(selective_from_params(p, (!empty).then_some(existing)))),
+ Adjustment::SelectiveColor { .. } => Some(selective_from_params(p, (!empty).then_some(existing))),
Adjustment::ColorLookup { .. } => Some(lookup_from_params(p, (!empty).then_some(existing))),
_ => None,
}
diff --git a/crates/engine/src/adjust_cmds/tests.rs b/crates/engine/src/adjust_cmds/tests.rs
index 67719afbc..5f781c405 100644
--- a/crates/engine/src/adjust_cmds/tests.rs
+++ b/crates/engine/src/adjust_cmds/tests.rs
@@ -219,6 +219,87 @@ LUT_3D_SIZE 2
assert_eq!(looks.as_array().unwrap().len(), photocraft_cms::lutfile::BUILTIN.len());
}
+/// The kind's parameters, read back from the model (Color Lookup with its table name and size).
+fn adjustment_of(s: &Session, id: photocraft_doc::LayerId) -> Adjustment {
+ match &doc(s).layer(id).unwrap().content {
+ LayerContent::Adjustment(a) => a.clone(),
+ other => panic!("{other:?}"),
+ }
+}
+
+#[test]
+fn selective_color_and_color_lookup_reject_wrong_typed_params() {
+ let cube = "LUT_3D_SIZE 2\n0 0 0\n1 0 0\n0 1 0\n1 1 0\n0 0 1\n1 0 1\n0 1 1\n1 1 1\n";
+ // (kind, params, the key the error must name)
+ let cases: Vec<(&str, Value, &str)> = vec![
+ ("selectiveColor", json!({"method": 5}), "method"),
+ ("selectiveColor", json!({"method": "sideways"}), "method"),
+ ("selectiveColor", json!({"relative": "yes"}), "relative"),
+ ("selectiveColor", json!({"reds": "not-an-array"}), "reds"),
+ ("selectiveColor", json!({"blues": [10, 20]}), "blues"),
+ ("selectiveColor", json!({"neutrals": [10, "20", 0, 0]}), "neutrals"),
+ ("selectiveColor", json!({"colors": 3, "cyan": 50}), "colors"),
+ ("selectiveColor", json!({"colors": "purples", "cyan": 50}), "purples"),
+ ("selectiveColor", json!({"colors": "reds", "cyan": "50"}), "cyan"),
+ ("selectiveColor", json!({"colors": "blacks", "black": [1]}), "black"),
+ ("colorLookup", json!({"lut": 42}), "lut"),
+ ("colorLookup", json!({"interpolation": 5}), "interpolation"),
+ ("colorLookup", json!({"interpolation": "bicubic"}), "interpolation"),
+ ("colorLookup", json!({"tetrahedral": 1}), "tetrahedral"),
+ ("colorLookup", json!({"dither": "yes"}), "dither"),
+ ("colorLookup", json!({"data": 42}), "data"),
+ ("colorLookup", json!({"data": cube, "fileName": 7}), "fileName"),
+ ("colorLookup", json!({"file": 42}), "file"),
+ ];
+ let named = |r: Result<Value>, key: &str, what: &str| match r {
+ Err(e @ EngineError::BadParams { .. }) => assert!(e.to_string().contains(key), "{what}: {e}"),
+ other => panic!("{what}: expected BadParams naming `{key}`, got {other:?}"),
+ };
+ for depth in DEPTHS {
+ for mode in ["rgb", "cmyk", "lab"] {
+ for (kind, p, key) in &cases {
+ let what = format!("{kind} {p} {depth} {mode}");
+ let mut s = session(depth, mode);
+ let (layers, steps, px) = (doc(&s).layers.len(), s.active().unwrap().history.past_len(), rgba(&s, 3, 3));
+ named(s.execute(&format!("image.adjustments.{kind}"), p.clone()), key, &what);
+ named(s.execute(&format!("layer.newAdjustmentLayer.{kind}"), p.clone()), key, &what);
+ assert_eq!(doc(&s).layers.len(), layers, "{what}: no layer added");
+ assert_eq!(s.active().unwrap().history.past_len(), steps, "{what}: no history step");
+ assert_eq!(rgba(&s, 3, 3), px, "{what}: pixels unchanged");
+ }
+ }
+ }
+ // An update with a wrong-typed key fails and keeps every existing value.
+ let mut s = session(8, "rgb");
+ let made = [
+ ("selectiveColor", json!({"method": "absolute", "reds": [10, -20, 30, -40], "colors": "blues", "yellow": 40})),
+ ("colorLookup", json!({"lut": "warm", "interpolation": "tetrahedral", "dither": true})),
+ ];
+ for (kind, p) in made {
+ let id = photocraft_doc::LayerId(s.execute(&format!("layer.newAdjustmentLayer.{kind}"), p).unwrap()["layer"].as_u64().unwrap());
+ let before = adjustment_of(&s, id);
+ for (k, p, key) in cases.iter().filter(|c| c.0 == kind) {
+ let mut p = p.clone();
+ p["layer"] = json!(id.0);
+ named(s.execute("layer.setAdjustment", p.clone()), key, &format!("setAdjustment {k} {p}"));
+ assert_eq!(adjustment_of(&s, id), before, "{p}");
+ }
+ // Null still means "not given": the update keeps everything.
+ let nulls = json!({"layer": id.0, "method": null, "reds": null, "colors": null, "lut": null, "interpolation": null, "dither": null});
+ s.execute("layer.setAdjustment", nulls).unwrap();
+ assert_eq!(adjustment_of(&s, id), before, "{kind}: nulls");
+ }
+ // Well-typed values reach the model.
+ match adjustment_of(&s, doc(&s).layers[1].id) {
+ Adjustment::SelectiveColor { relative: false, adjustments } => {
+ assert_eq!(adjustments[0], [10.0, -20.0, 30.0, -40.0]);
+ assert_eq!(adjustments[4], [0.0, 0.0, 40.0, 0.0]);
+ }
+ other => panic!("{other:?}"),
+ }
+ assert!(matches!(adjustment_of(&s, doc(&s).layers[2].id), Adjustment::ColorLookup { lut: Some(_), tetrahedral: true, dither: true, .. }));
+}
+
#[test]
fn new_kinds_round_trip_through_psd_and_pcraft() {
let mut s = session(8, "rgb");
diff --git a/crates/engine/src/adjust_params.rs b/crates/engine/src/adjust_params.rs
index ee3b429d9..7bad00f44 100644
--- a/crates/engine/src/adjust_params.rs
+++ b/crates/engine/src/adjust_params.rs
@@ -203,7 +203,7 @@ pub fn from_params(kind: &str, p: &Value, base: Option<&Adjustment>, mode: Color
};
Adjustment::GradientMap { stops, reverse: r.boolean("reverse", rev0)?, dither: r.boolean("dither", dither0)? }
}
- "selectiveColor" => crate::adjust_cmds::selective_from_params(p, base.filter(|b| matches!(b, Adjustment::SelectiveColor { .. }))),
+ "selectiveColor" => crate::adjust_cmds::selective_from_params(p, base.filter(|b| matches!(b, Adjustment::SelectiveColor { .. })))?,
"colorLookup" => crate::adjust_cmds::lookup_from_params(p, base.filter(|b| matches!(b, Adjustment::ColorLookup { .. })))?,
other => return Err(bad("adjustment", format!("unknown adjustment kind `{other}`"))),
})
@@ -909,6 +909,12 @@ mod tests {
("channelMixer", json!({"red": [1, 2, 3]})),
("gradientMap", json!({"stops": [[0, "#000"]]})),
("gradientMap", json!({"stops": 7})),
+ ("selectiveColor", json!({"method": 5})),
+ ("selectiveColor", json!({"reds": "not-an-array"})),
+ ("selectiveColor", json!({"colors": "reds", "cyan": "50"})),
+ ("colorLookup", json!({"lut": 42})),
+ ("colorLookup", json!({"interpolation": 5})),
+ ("colorLookup", json!({"dither": "yes"})),
("nope", json!({})),
("levels", json!([1, 2])),
] {