From ea752548dfe64e728dadd937306c9f5d61c84f46 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 2 Dec 2026 16:09:00 -0800 Subject: [PATCH] New Document: reject a bad preset or presetCategory instead of ignoring it file.new and file.newPresets.save read `preset` and `presetCategory` with str_param, so a value that is not a string was dropped and the call went on with the default settings or the search of every category. An unknown category reported "no preset called" instead of naming the category, and a presetCategory without a preset was dropped. Each of these is now an error, with the same "unknown category" message file.newPresets gives. Null still leaves a param out, and a replayed journal step reads the params as before, so saved steps still play. presetCategory came in with #9295. --- crates/engine/src/cmd/edit.rs | 2 +- crates/engine/src/cmd/newdoc.rs | 32 +++++++++++++++++++++---- crates/engine/src/tests/newdoc.rs | 39 +++++++++++++++++++++++++++++++ docs/mcp.md | 2 +- 4 files changed, 69 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index 99ef61ef44..b7ba67ef7c 100644 --- a/crates/engine/src/cmd/edit.rs +++ b/crates/engine/src/cmd/edit.rs @@ -24,7 +24,7 @@ pub fn specs() -> Vec { "New…", ["File"], None, - "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", + "{preset?: a name from file.newPresets (start from it; the other params change it), presetCategory?: a category of file.newPresets (preset names a preset of that category; default: a saved preset first, then the built-in ones; an unknown category, or one without preset, is an error), name?|title?: document name (default Untitled-N), width?: pt=612|\"210 mm\", height?: pt=792 (each more than 0 and at most 3,999,856 pt, as artboard.new takes them), units?: \"Pixels\"|\"Points\"|\"Picas\"|\"Inches\"|\"Millimeters\"|\"Centimeters\"|\"Feet\"|\"Yards\"|\"Meters\"|\"Feet & Inches\" (default: prefs unitsGeneral, as print presets; screen presets: Pixels), orientation?: \"portrait\"|\"landscape\" (swaps width and height to match), artboards?: n (a whole number, 1–1000), artboardLayout?: {layout?: \"gridByRow\"|\"gridByColumn\"|\"row\"|\"column\", columns?: n (a whole number, 1–1000; default: all in one row), rows?: n (a whole number, 1–1000; gridByColumn only, an error with another layout: that many rows, in place of columns; a preset keeps them until columns without rows or another layout is given), spacing?: pt=20, rightToLeft?: bool}, bleed?: pt|[top, bottom, left, right]|{top?, …} (0–72 pt), backgroundContents?: \"transparent\"|\"white\" (a white artboard background, not an object), colorMode?: \"rgb\"|\"cmyk\" (a CMYK document starts with CMYK swatches and stores the colours applied to it as CMYK), rasterEffectsPpi?: 72|150|300 (1–2400), previewMode?: \"default\"|\"pixel\"|\"overprint\" (overprint turns Overprint Preview on, pixel Pixel Preview in the app; default leaves both), alignNewObjectsToPixelGrid?: bool (Advanced Options › Align New Objects to Pixel Grid: paths drawn in the document are pixel-aligned; default on for the Mobile and Web presets, else off; document.setup changes it later), profile?: a category of file.newPresets|null (the New Document profile the document starts from, see file.newProfiles; default: a built-in preset's category, kept by the saved and Recent presets made from it; null or no preset: the defaults), created?: Unix seconds|null (File Info's created date; default now, recorded in the journal so a replay matches), size?: a preset's size label (a preset file.newPresets lists can be passed back; ignored)} → {index, previewMode, profile?: the profile applied, warnings?: [text] (a color profile the profile's file carries that can't be used), profileError?: {profile, reason} (its file is a link or a folder, could not be read, was larger than 64 MiB or is not a native document, or the request may not read the profiles folder, a reason that leaves out the folder's path: the document has the defaults)}; the size is remembered in file.newPresets' Recent", always, super::newdoc::file_new ), diff --git a/crates/engine/src/cmd/newdoc.rs b/crates/engine/src/cmd/newdoc.rs index 26c5d2bbac..c842674fb6 100644 --- a/crates/engine/src/cmd/newdoc.rs +++ b/crates/engine/src/cmd/newdoc.rs @@ -18,7 +18,7 @@ use serde_json::{Value, json}; use vectorcraft_doc::{Artboard, Background, ColorMode, CompositeFont, DEFAULT_GRAPHIC_STYLE, Document, GraphicStyle, LayerColor, Node, Unit}; use vectorcraft_geom::{Point, Rect}; -use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or}; +use super::{CommandSpec, Result, Session, always, bad, clock_date, cmd, date_param, has_doc, str_param, switch_or, text_param}; pub fn specs() -> Vec { vec![ @@ -860,10 +860,34 @@ pub fn find(s: &Session, name: &str) -> Option { /// The preset the `preset` param of `cmd` names, looked up in the category `presetCategory` names /// when it is given ([`category`]) and with [`find`] otherwise; the starting settings without -/// `preset`. +/// `preset`. A `preset` or `presetCategory` that is not a string, a `presetCategory` that names no +/// category, and a `presetCategory` without a `preset` are errors, except in a replay, which reads +/// a saved step as earlier versions did: such a value is left out, and an unknown category finds no +/// preset. fn preset_param(s: &Session, p: &Value, cmd: &str) -> Result { - let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; - let found = match str_param(p, "presetCategory") { + if s.replaying() { + let Some(name) = str_param(p, "preset") else { return Ok(s.default_settings()) }; + let found = match str_param(p, "presetCategory") { + Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), + None => find(s, name), + }; + return found.ok_or_else(|| bad(cmd, format!("no preset called `{name}` (see file.newPresets)"))); + } + let name = text_param(p, "preset", cmd)?; + let wanted = text_param(p, "presetCategory", cmd)? + .map(|c| { + category_names() + .find(|n| n.eq_ignore_ascii_case(c)) + .ok_or_else(|| bad(cmd, format!("unknown category `{c}` ({})", category_names().collect::>().join(", ")))) + }) + .transpose()?; + let Some(name) = name else { + return match wanted { + Some(_) => Err(bad(cmd, "presetCategory needs a preset")), + None => Ok(s.default_settings()), + }; + }; + let found = match wanted { Some(c) => category(s, c).and_then(|ps| ps.into_iter().find(|q| q.name.eq_ignore_ascii_case(name.trim()))), None => find(s, name), }; diff --git a/crates/engine/src/tests/newdoc.rs b/crates/engine/src/tests/newdoc.rs index 6e1623c00e..ac34216e2f 100644 --- a/crates/engine/src/tests/newdoc.rs +++ b/crates/engine/src/tests/newdoc.rs @@ -137,6 +137,45 @@ fn a_preset_starts_the_document_and_params_change_it() { assert_eq!(s.doc().unwrap().doc.units, Unit::Pixels); } +#[test] +fn a_bad_preset_or_preset_category_is_an_error() { + let s = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + assert!((s.doc().unwrap().doc.artboards[0].rect.height() - 841.89).abs() < 0.01); + for p in [ + json!({"preset": "A4", "presetCategory": "Napkins"}), + json!({"preset": "A4", "presetCategory": 5}), + json!({"preset": "A4", "presetCategory": ""}), + json!({"preset": "A4", "presetCategory": " Print "}), + json!({"presetCategory": "Print"}), + json!({"presetCategory": "Napkins"}), + json!({"preset": 5}), + json!({"preset": true, "presetCategory": "Print"}), + ] { + assert!(Session::new().execute("file.new", &p).is_err(), "file.new {p}"); + let mut save = p.clone(); + save["name"] = json!("Mine"); + assert!(Session::new().execute("file.newPresets.save", &save).is_err(), "file.newPresets.save {save}"); + } + let e = Session::new().execute("file.new", &json!({"preset": "A4", "presetCategory": "Napkins"})).unwrap_err().to_string(); + assert!(e.contains("unknown category `Napkins`"), "{e}"); + // Null leaves a param out. + Session::new().execute("file.new", &json!({"preset": null, "presetCategory": null})).unwrap(); + // A step this version took replays, and one an earlier version took still plays as it did then. + let recorded = new_doc(json!({"preset": "A4", "presetCategory": "print"})); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); + let mut recorded = new_doc(json!({})); + recorded.journal.last_mut().unwrap().1["presetCategory"] = json!("Print"); + let mut s = Session::new(); + for (id, p) in &recorded.journal { + s.replay(id, p).unwrap(); + } + assert_eq!(boards(&s), boards(&recorded)); +} + #[test] fn ppi_overprint_preview_and_bad_params() { // Overprint Preview is process-wide. diff --git a/docs/mcp.md b/docs/mcp.md index f3931f6fb1..59afba853a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -10987,7 +10987,7 @@ and goes back to Document Setup, whose OK runs `document.setup`; its Cancel goes `file.new` takes everything New Document sets: `preset` (a name from `file.newPresets`, a saved preset before a built-in one of the same name; with `presetCategory`, a category of `file.newPresets`, the preset of that name in -that category), `name`, `width`/`height` +that category; an unknown category, or `presetCategory` without `preset`, is an error), `name`, `width`/`height` (points, or lengths such as `"210 mm"`), `units`, `orientation`, `artboards` with `artboardLayout {layout, columns, rows, spacing, rightToLeft}` (`artboards`, `columns` and `rows` are whole numbers from 1 to 1000, and any other number is an error; `rows` gives a `gridByColumn` layout that many rows, at most one for each artboard, in place of `columns`, and is an error with another layout; a preset keeps the rows, and `file.newPresets` lists them as set even when there are