PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Filter Gallery: an unknown option is a bad-params error (#2548 follow-up) (#2599)
xsvm13e478cc6e7c
diff --git a/crates/engine/src/filters/validation.rs b/crates/engine/src/filters/validation.rsindex 5468c8d2f..127e92efe 100644--- a/crates/engine/src/filters/validation.rs+++ b/crates/engine/src/filters/validation.rs@@ -34,7 +34,7 @@ impl Rule {}// The bounds and choices are the core filters' public dialog-unit contract. Defaults remain in-// params_for; gallery filters keep their own parsing until their validation is added.+// params_for; gallery filters are checked in gallery_cmds.fn fields(id: &str) -> Option<&'static [(&'static str, Rule)]> {use Rule::{Bool, Choice, Number, Unsigned};Some(match id {@@ -134,7 +134,7 @@ pub(crate) fn validate_params(id: &str, params: &Value) -> Result<()> {}return Ok(());}- let Some(fields) = fields(id) else { return Ok(()) };+ let Some(fields) = fields(id) else { return crate::gallery_cmds::validate_params(id, params) };if params.is_null() {return Ok(());}diff --git a/crates/engine/src/gallery_cmds.rs b/crates/engine/src/gallery_cmds.rsindex 848400d37..0474bc08a 100644--- a/crates/engine/src/gallery_cmds.rs+++ b/crates/engine/src/gallery_cmds.rs@@ -88,6 +88,41 @@ pub fn params_for(id: &str, p: &Value) -> Option<FilterParams> {Some(FilterParams::FilterGallery { effects: vec![effect_from_json(f, p, &Value::Null)] })}+/// An unknown choice name or a wrong-typed choice is a bad-params error, for one gallery filter+/// or each effect of a `filter.filterGallery` stack. Checked only for new invocations (via+/// `filters::validate_params`); stored smart filters keep decoding tolerantly.+pub(crate) fn validate_params(id: &str, p: &Value) -> Result<()> {+ let bad = |msg: String| EngineError::BadParams { cmd: id.into(), msg };+ if id == "filter.filterGallery" {+ for (k, item) in p.get("effects").and_then(Value::as_array).into_iter().flatten().enumerate() {+ let Some(f) = item.get("filter").and_then(Value::as_str).and_then(GalleryFilter::from_key) else { continue };+ let params = item.get("params").filter(|v| v.is_object()).unwrap_or(item);+ check_choices(f, params).map_err(|m| bad(format!("effect {k}: {m}")))?;+ }+ return Ok(());+ }+ match id.strip_prefix("filter.gallery.").and_then(GalleryFilter::from_key) {+ Some(f) => check_choices(f, p).map_err(bad),+ None => Ok(()),+ }+}++fn check_choices(f: GalleryFilter, p: &Value) -> std::result::Result<(), String> {+ for prm in f.params() {+ let (Some(v), GalleryParamKind::Choice(names)) = (p.get(prm.key), &prm.kind) else { continue };+ let ok = match v {+ Value::String(name) => names.iter().any(|n| n.eq_ignore_ascii_case(name)),+ // A choice index, clamped as the dialog stores it.+ Value::Number(_) => true,+ _ => false,+ };+ if !ok {+ return Err(format!("`{}` must be one of {}", prm.key, names.join("|")));+ }+ }+ Ok(())+}+/// Whether the command reads the foreground/background colours.pub(crate) fn uses_colours(id: &str) -> bool {id == "filter.filterGallery" || id.strip_prefix("filter.gallery.").and_then(GalleryFilter::from_key).is_some_and(GalleryFilter::uses_colours)diff --git a/crates/engine/src/gallery_cmds/tests.rs b/crates/engine/src/gallery_cmds/tests.rsindex 93d848701..064bddca3 100644--- a/crates/engine/src/gallery_cmds/tests.rs+++ b/crates/engine/src/gallery_cmds/tests.rs@@ -139,3 +139,33 @@ fn gallery_is_a_smart_filter_on_smart_objects() {assert_eq!(sm.smart_filters[0].command, "filter.filterGallery");assert_eq!(sm.smart_filters[0].params["effects"][0]["filter"], json!("texturizer"));}++#[test]+fn unknown_choice_names_are_bad_params_without_editing() {+ let mut s = session(8, "rgb");+ let before = pixels(&s);+ let history = s.active().unwrap().history.entries();+ let mut checked = 0;+ for f in GalleryFilter::ALL.iter().copied() {+ for prm in f.params() {+ let GalleryParamKind::Choice(names) = prm.kind else { continue };+ let id = f.command_id();+ for v in [json!("zzbogus"), json!(true), json!([0])] {+ let err = s.execute(id, json!({prm.key: v})).unwrap_err();+ assert!(matches!(err, EngineError::BadParams { .. }), "{id}.{}: {err}", prm.key);+ assert!(err.to_string().contains(prm.key), "{err}");+ let stack = json!({"effects": [{"filter": f.key(), "params": {prm.key: v}}]});+ assert!(matches!(s.execute("filter.filterGallery", stack), Err(EngineError::BadParams { .. })), "{id}.{}", prm.key);+ }+ assert_eq!(pixels(&s), before);+ assert_eq!(s.active().unwrap().history.entries(), history);+ // Every listed name (any case) and an index still run.+ for v in names.iter().map(|n| json!(n.to_uppercase())).chain([json!(names.len() - 1)]) {+ s.execute(id, json!({prm.key: v})).unwrap();+ s.undo();+ }+ checked += 1;+ }+ }+ assert!(checked >= 16, "{checked}");+}