PhotoCraft: An open-source, photo editor written by scratch in pure Rust
file.new rejects invalid parameters instead of falling back (#1878)
Jason Xiang5aaf0e4aae42
diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rsindex d8eda1153..cfc6f9d7a 100644--- a/crates/engine/src/commands.rs+++ b/crates/engine/src/commands.rs@@ -340,10 +340,11 @@ fn build() -> Vec<CommandSpec> {"New…",["File"],Some("Cmd+N"),- r##"{"width":u32=1920,"height":u32=1080,"mode":"rgb|gray|cmyk|lab"="rgb","depth":8|16|32=8,"background":"white|black|backgroundColor|transparent|#rrggbb"="white","backgroundColor":[r,g,b]? (0..1; defaults to toolbox colour),"resolution":ppi=72,"name":str}"##,+ r##"{"width":1..300000=1920,"height":1..300000=1080 (pixel counts are rounded),"mode":"rgb|gray|grayscale|cmyk|lab"="rgb","depth":8|16|32=8,"background":"white|black|backgroundColor|transparent|#rrggbb"="white","backgroundColor":[r,g,b]? (0..1; defaults to toolbox colour),"resolution":1..30000=72 (ppi),"name":str}"##,always,|s, p| {use crate::document_preset_cmds::{MAX_DIMENSION, MAX_RESOLUTION, background_color, color_mode, sample_type};+ crate::document_preset_cmds::validate_new_params(s, p)?;// A size given as a float (`512.0`, as JSON from a UI field) is still that size (#254).let px = |k: &str, d: u32| match p.get(k) {Some(v) => vdiff --git a/crates/engine/src/document_preset_cmds.rs b/crates/engine/src/document_preset_cmds.rsindex 6b5f47211..01cd2cfc8 100644--- a/crates/engine/src/document_preset_cmds.rs+++ b/crates/engine/src/document_preset_cmds.rs@@ -45,6 +45,46 @@ pub(crate) fn background_color(p: &Value, fallback: [f32; 4], cmd: &str) -> ResuOk([c[0], c[1], c[2], 1.0])}+/// Validate creation before dispatch can commit a floating selection or add a document.+/// Missing fields (including a null params object) keep the command's documented defaults.+pub(crate) fn validate_new_params(s: &Session, p: &Value) -> Result<()> {+ let cmd = "file.new";+ if p.is_null() {+ return Ok(());+ }+ let fields = p.as_object().ok_or_else(|| bad(cmd, "params must be a JSON object"))?;+ for (key, value) in fields {+ let (valid, expected) = match key.as_str() {+ "width" | "height" | "resolution" => {+ let max = if key == "resolution" { MAX_RESOLUTION } else { f64::from(MAX_DIMENSION) };+ (value.as_f64().is_some_and(|n| n.is_finite() && (1.0..=max).contains(&n)), format!("a number within 1..={max}"))+ }+ "mode" => (value.as_str().and_then(color_mode).is_some(), "rgb, gray, grayscale, cmyk or lab".into()),+ "depth" => (value.as_u64().and_then(sample_type).is_some(), "8, 16 or 32".into()),+ "background" => (+ value.as_str().is_some_and(|v| {+ matches!(v, "white" | "black" | "transparent" | "backgroundColor")+ || (v.strip_prefix('#').unwrap_or(v).bytes().all(|b| b.is_ascii_hexdigit()) && crate::commands::parse_hex(v).is_some())+ }),+ "white, black, transparent, backgroundColor or a valid hex colour".into(),+ ),+ "backgroundColor" => {+ background_color(p, s.tools.background, cmd)?;+ continue;+ }+ "name" => (value.is_string(), "a string".into()),+ _ => return Err(bad(cmd, format!("unknown parameter `{key}`"))),+ };+ if !valid {+ return Err(bad(cmd, format!("`{key}` must be {expected}")));+ }+ }+ if p.get("background").and_then(Value::as_str) == Some("backgroundColor") {+ background_color(p, s.tools.background, cmd)?;+ }+ Ok(())+}+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct DocumentSettings {@@ -96,8 +136,8 @@ impl DocumentSettings {fields.entry(k.clone()).or_insert_with(|| v.clone());}}- // Like file.new, accept pixel counts sent as floats by a UI. Unlike file.new's fallback- // for legacy callers, refuse invalid input rather than saving a different configuration.+ // Like file.new, accept pixel counts sent as floats by a UI, but refuse invalid input+ // rather than saving a different configuration.for key in ["width", "height"] {let n = fields.get(key)diff --git a/crates/engine/src/jobs.rs b/crates/engine/src/jobs.rsindex 303d1b0be..b486698d7 100644--- a/crates/engine/src/jobs.rs+++ b/crates/engine/src/jobs.rs@@ -603,6 +603,9 @@ impl Session {if let Some(gate) = self.authorize {gate(id, ¶ms)?;}+ if id == "file.new" {+ crate::document_preset_cmds::validate_new_params(self, ¶ms)?;+ }// A floating selection drops before any other command (Undo puts it back instead).if let Some(v) = crate::float_cmds::before_command(self, id)? {return Ok(Started::Done(v));diff --git a/crates/engine/src/render_cmds.rs b/crates/engine/src/render_cmds.rsindex 7d3e27de4..e2ec1d9d7 100644--- a/crates/engine/src/render_cmds.rs+++ b/crates/engine/src/render_cmds.rs@@ -220,9 +220,10 @@ pub fn specs() -> Vec<CommandSpec> {mod tests {use super::*;- fn session(depth: &str) -> Session {+ fn session(depth: u64) -> Session {let mut s = Session::new();s.execute("file.new", json!({"width": 160, "height": 120, "depth": depth})).unwrap();+ assert_eq!(Some(s.active().unwrap().doc.depth), crate::document_preset_cmds::sample_type(depth));s.execute("layer.new.layer", json!({})).unwrap();s}@@ -238,7 +239,7 @@ mod tests {#[test]fn each_renderer_draws_undoes_and_is_seeded_at_every_depth() {- for depth in ["8", "16", "32"] {+ for depth in [8, 16, 32] {for (id, p) in [("filter.render.flame", json!({})),("filter.render.tree", json!({"baseTreeType": 7})),@@ -266,7 +267,7 @@ mod tests {#[test]fn flame_follows_the_work_path() {- let mut s = session("8");+ let mut s = session(8);let r = s.execute("filter.render.flame", json!({})).unwrap();assert_eq!(r["usedPath"], json!(false));s.execute("edit.undo", json!({})).unwrap();@@ -288,7 +289,7 @@ mod tests {#[test]fn selection_limits_and_new_layer() {- let mut s = session("8");+ let mut s = session(8);s.execute("select.rect", json!({"x": 0, "y": 0, "width": 80, "height": 120})).unwrap();let r = s.execute("filter.render.tree", json!({"newLayer": true, "baseTreeType": 1, "leavesAmount": 100})).unwrap();assert_eq!(r["newLayer"], json!(true));diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex ba1d6471a..084f112b2 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -59,9 +59,73 @@ fn file_new_takes_whole_floats_and_survives_odd_sizes() {s.execute("file.new", json!({"width": 512.0, "height": 511.6})).unwrap();let d = &s.active().unwrap().doc;assert_eq!((d.size.width, d.size.height), (512, 512));- s.execute("file.new", json!({"width": -5.0, "height": "x"})).unwrap();+ assert!(s.execute("file.new", json!({"width": -5.0, "height": "x"})).is_err());let d = &s.active().unwrap().doc;- assert_eq!((d.size.width, d.size.height), (1, 1080));+ assert_eq!((d.size.width, d.size.height), (512, 512));+ assert_eq!(s.documents().len(), 1);+}++#[test]+fn file_new_rejects_invalid_fields_without_changing_the_session() {+ let mut s = session_with_doc();+ let original = s.active().unwrap().doc.clone();+ let history = s.active().unwrap().history.entries();+ for (key, values) in [+ ("width", vec![json!(0), json!(-1), json!(300001), json!("32"), json!(null)]),+ ("height", vec![json!(0), json!(-1), json!(1e30), json!(true)]),+ ("resolution", vec![json!(0), json!(30000.001), json!("72"), json!([])]),+ ("mode", vec![json!("hsv"), json!(false), json!(null)]),+ ("depth", vec![json!(12), json!("16"), json!(-1), json!(256)]),+ ("background", vec![json!("#zzzzzz"), json!("#+0+0+0"), json!("##112233"), json!("pink"), json!(42)]),+ ("backgroundColor", vec![json!([1, 0]), json!([2, 0, 0]), json!("red")]),+ ("name", vec![json!(false), json!(null)]),+ ("widht", vec![json!(32)]),+ ] {+ for value in values {+ let mut p = json!({});+ p[key] = value;+ let error = s.execute("file.new", p).unwrap_err().to_string();+ assert!(error.contains("file.new") && error.contains(key), "{error}");+ assert_eq!(s.documents().len(), 1);+ assert_eq!(s.active_index(), Some(0));+ assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &original));+ assert_eq!(s.active().unwrap().history.entries(), history);+ }+ }+}++#[test]+fn invalid_file_new_leaves_a_floating_selection_uncommitted() {+ let mut s = session_with_doc();+ s.execute("select.rect", json!({"x": 0, "y": 0, "width": 4, "height": 4})).unwrap();+ s.execute("select.float", json!({"dx": 8})).unwrap();+ let original = s.active().unwrap().doc.clone();+ let history = s.active().unwrap().history.entries();+ assert!(s.execute("file.new", json!({"depth": 12})).is_err());+ assert!(crate::float_cmds::floating(s.active().unwrap()).is_some());+ assert!(std::sync::Arc::ptr_eq(&s.active().unwrap().doc, &original));+ assert_eq!(s.active().unwrap().history.entries(), history);+ assert_eq!(s.documents().len(), 1);+}++#[test]+fn file_new_keeps_defaults_and_supported_modes_and_depths() {+ for params in [json!({}), Value::Null] {+ let mut s = Session::new();+ s.execute("file.new", params).unwrap();+ let d = &s.active().unwrap().doc;+ assert_eq!((d.size.width, d.size.height, d.resolution_dpi), (1920, 1080, 72.0));+ }+ for mode in ["rgb", "gray", "grayscale", "cmyk", "lab"] {+ for depth in [8, 16, 32] {+ let mut s = Session::new();+ s.execute("file.new", json!({"width": 4.0, "height": 3, "mode": mode, "depth": depth, "resolution": 300})).unwrap();+ let d = &s.active().unwrap().doc;+ assert_eq!(Some(d.mode), crate::document_preset_cmds::color_mode(mode));+ assert_eq!(Some(d.depth), crate::document_preset_cmds::sample_type(depth));+ assert_eq!(d.resolution_dpi, 300.0);+ }+ }}#[test]