diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs index ac500697be..55726c31c9 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 3dc7f579d8..4dee23bcda 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 a320b09b18..21cc4af602 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 581e252def..54a1ec5b0d 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -11257,7 +11257,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