From 1bce7de465d3fe358e99840805f151a53377264a Mon Sep 17 00:00:00 2001 From: AlPaka1234 <356241429+AlPaka1234@users.noreply.github.com> Date: Tue, 1 Dec 2026 19:50:41 +0000 Subject: [PATCH] file.new: validate ruler units and document point-sized parameters (#3198) --- crates/engine/src/cmd/file/new.rs | 50 ++++++++++++++++++++++++++ crates/engine/src/cmd/file/registry.rs | 6 ++-- crates/mcp/src/tests.rs | 17 +++++++++ crates/mcp/src/tools.rs | 13 +++---- docs/agents.md | 2 +- docs/mcp.md | 6 ++-- 6 files changed, 81 insertions(+), 13 deletions(-) diff --git a/crates/engine/src/cmd/file/new.rs b/crates/engine/src/cmd/file/new.rs index d4aade25a..116a08939 100644 --- a/crates/engine/src/cmd/file/new.rs +++ b/crates/engine/src/cmd/file/new.rs @@ -20,6 +20,7 @@ fn new_document_settings(s: &Session, p: &Value) -> Result { None => s.default_new_document(), }; check_binding("file.new", p)?; + check_units("file.new", p)?; apply_settings(&mut nd, p); check_size("file.new", &nd)?; Ok(nd) @@ -144,6 +145,7 @@ pub(super) fn save_preset(s: &mut Session, p: &Value) -> Result { return Err(bad("file.savePreset", format!("`{name}` is a built-in preset"))); } check_binding("file.savePreset", p)?; + check_units("file.savePreset", p)?; let mut nd = NewDocument::default(); apply_settings(&mut nd, p); check_size("file.savePreset", &nd)?; @@ -169,6 +171,7 @@ fn apply_settings(nd: &mut NewDocument, p: &Value) { if let Some(intent) = p.get("intent").and_then(|v| serde_json::from_value(v.clone()).ok()) { nd.intent = intent; } + // Checked by `check_units` before the settings are applied. if let Some(units) = p.get("units").and_then(|v| serde_json::from_value(v.clone()).ok()) { nd.units = units; } @@ -213,6 +216,21 @@ fn check_binding(cmd: &str, p: &Value) -> Result<()> { } } +/// `units`, when given, must be a valid ruler unit (`Unit`): an unknown value like `"mm"` or +/// `"furlongs"` is refused rather than silently keeping the default. +fn check_units(cmd: &str, p: &Value) -> Result<()> { + match p.get("units") { + None | Some(Value::Null) => Ok(()), + Some(v) if serde_json::from_value::(v.clone()).is_ok() => Ok(()), + Some(v) => Err(bad( + cmd, + format!( + "units must be a ruler unit (points, picas, inches, inchesDecimal, millimeters, centimeters, ciceros, agates, pixels, q, ha), not {v}" + ), + )), + } +} + /// A bleed or slug parameter: one width for every edge, or [top, bottom, inside, outside]. fn edges(p: &Value, key: &str) -> Option<[f64; 4]> { let clean = |v: f64| if v.is_finite() { v.clamp(0.0, 1296.0) } else { 0.0 }; @@ -264,6 +282,38 @@ mod new_document_tests { assert!(s.doc().unwrap().doc.settings.right_to_left_binding); } + /// `units` sets the document's ruler units (numeric sizes stay in points); invalid values like + /// `"mm"` or `"furlongs"` are refused instead of silently keeping the default. + #[test] + fn new_documents_refuse_invalid_units_and_keep_sizes_in_points() { + let mut s = Session::new(); + let preview = s.preview_new_document(&json!({"width": 300, "height": 200})).unwrap(); + let docs = s.documents().len(); + for bad in [json!("mm"), json!("Millimeters"), json!("furlongs"), json!(12), json!(true)] { + assert!(s.execute("file.new", &json!({"units": bad})).is_err(), "{bad}"); + assert!(s.execute("file.savePreset", &json!({"name": "Bad", "units": bad})).is_err(), "{bad}"); + assert!(s.preview_new_document(&json!({"units": bad})).is_err(), "{bad}"); + } + assert_eq!(s.documents().len(), docs); + assert_eq!(s.new_document_preview(), Some(preview), "a refused unit keeps the preview"); + assert!(s.prefs.document_presets.is_empty()); + assert_eq!(s.end_new_document_preview(), Some(preview)); + + // Explicit `null` keeps the preset or default units. + s.execute("file.new", &json!({"preset": "A4", "units": null})).unwrap(); + assert_eq!(s.doc().unwrap().doc.settings.horizontal_units, designcraft_geom::Unit::Millimeters); + + // Every ruler unit is accepted and sets ruler units only; sizes remain in points. + for unit in designcraft_geom::Unit::ALL { + s.execute("file.new", &json!({"units": unit, "width": 210, "height": 210, "bleed": 9, "margins": 18})).unwrap(); + let d = &s.doc().unwrap().doc; + assert_eq!((d.settings.horizontal_units, d.settings.vertical_units), (unit, unit)); + assert_eq!((d.settings.page_width, d.settings.page_height), (210.0, 210.0)); + assert_eq!(d.settings.bleed, [9.0; 4]); + assert_eq!(d.page(0).unwrap().margins.top, 18.0); + } + } + #[test] fn saved_presets_make_documents_by_name() { let mut s = Session::new(); diff --git a/crates/engine/src/cmd/file/registry.rs b/crates/engine/src/cmd/file/registry.rs index 56580604b..ddfe8f1e1 100644 --- a/crates/engine/src/cmd/file/registry.rs +++ b/crates/engine/src/cmd/file/registry.rs @@ -9,10 +9,10 @@ use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, st pub fn specs() -> Vec { vec![ cmd!(noundo "file.new", "Document…", ["File", "New"], Some("Cmd+N"), - "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|millimeters|…, width?, height?, pages?, startPage?, facingPages?, binding?: leftToRight|rightToLeft (anything else is refused), columns?, gutter?, margins?: number|{top,bottom,inside,outside}, bleed?, slug?: n | [top, bottom, inside, outside], title?, primaryTextFrame?: bool}", + "{preset?: \"Letter\"|\"A4\"|… or a saved preset (file.savePreset), intent?: print|web|mobile, units?: points|picas|inches|inchesDecimal|millimeters|centimeters|ciceros|agates|pixels|q|ha (ruler units only; anything else is refused), width? (pt), height? (pt), pages?, startPage?, facingPages?, binding?: leftToRight|rightToLeft (anything else is refused), columns?, gutter? (pt), margins?: number|{top,bottom,inside,outside} (pt), bleed?, slug?: n | [top, bottom, inside, outside] (pt), title?, primaryTextFrame?: bool} — all size parameters (width, height, gutter, margins, bleed, slug) are in points (72 pt = 1 in, 72/25.4 pt = 1 mm); `units` sets the document's ruler units only", always, file_new), cmd!(noundo "file.newSample", "Sample Document", ["Help"], None, "{} — a multi-page magazine sample", always, file_sample), - cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}], then the saved ones (with `saved: true` and their `binding`: leftToRight|rightToLeft)", always, |s, _| { + cmd!(query "file.presets", "Document Presets", [], None, "{} → the built-in presets [{name, intent, width, height, units}] (width and height in pt; units is the ruler unit), then the saved ones (with `saved: true` and their `binding`: leftToRight|rightToLeft)", always, |s, _| { let mut presets: Vec = PRESETS.iter().map(|p| serde_json::to_value(p).unwrap_or_default()).collect(); presets.extend( s.prefs @@ -26,7 +26,7 @@ pub fn specs() -> Vec { Ok(Value::Array(presets)) }), cmd!(noundo "file.savePreset", "Save Document Preset", [], None, - "{name, …the settings as file.new} — kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused", + "{name, …the settings as file.new} — sizes in points, `units` sets ruler units; kept with the preferences; `file.new {preset: name}` uses it. A saved preset of that name is replaced; built-in names are refused", always, save_preset), cmd!(noundo "file.deletePreset", "Delete Document Preset", [], None, "{name} — a saved document preset", always, |s, p| { let name = str_param(p, "name").unwrap_or_default().trim().to_string(); diff --git a/crates/mcp/src/tests.rs b/crates/mcp/src/tests.rs index d95078c1b..fbaef61c9 100644 --- a/crates/mcp/src/tests.rs +++ b/crates/mcp/src/tests.rs @@ -868,3 +868,20 @@ fn stdio_cancel_and_batch_transcript() { assert_eq!(replies[2], json!([{"jsonrpc": "2.0", "id": 2, "result": {}}])); assert_eq!(replies[3], json!({"jsonrpc": "2.0", "id": 3, "result": {}})); } + +#[test] +fn new_document_refuses_invalid_units_and_lists_ruler_units() { + let defs = tool_definitions(); + let new_doc = defs.iter().find(|t| t["name"] == "new_document").unwrap(); + assert_eq!(new_doc["inputSchema"]["properties"]["units"]["enum"], json!(designcraft_geom::Unit::ALL)); + + let mut s = server(); + let before = ok(&mut s, "inspect_document", json!({})); + let r = call(&mut s, "new_document", json!({"units": "mm", "width": 210, "height": 210})); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains("`units` must be one of"), "{r}"); + let r = call(&mut s, "execute", json!({"command": "file.new", "params": {"units": "mm", "width": 210, "height": 210}})); + assert_eq!(r["isError"], true, "{r}"); + assert!(text_of(&r).contains("units must be a ruler unit"), "{r}"); + assert_eq!(ok(&mut s, "inspect_document", json!({})), before); +} diff --git a/crates/mcp/src/tools.rs b/crates/mcp/src/tools.rs index 3890eacc5..f7d6ae469 100644 --- a/crates/mcp/src/tools.rs +++ b/crates/mcp/src/tools.rs @@ -123,9 +123,9 @@ pub fn tool_definitions() -> Vec { "Execute command", "Run any DesignCraft command by id with JSON params (ids and params from list_commands). Examples: \ {\"command\":\"frame.create\",\"params\":{\"rect\":[36,36,576,300],\"content\":\"text\",\"text\":\"Hello\"}} → {id, story}; \ - {\"command\":\"type.char\",\"params\":{\"size\":24}}; {\"command\":\"edit.undo\"}. Coordinates are points in spread space. \ - In the desktop app the UI-only commands (view.*, window.*, help.*, edit.dynamicSpelling, and app.* except app.links, \ - which works everywhere) work too.", + {\"command\":\"type.char\",\"params\":{\"size\":24}}; {\"command\":\"edit.undo\"}. All lengths and coordinates are in points \ + (72 pt = 1 in, 72/25.4 pt = 1 mm) in spread space. In the desktop app the UI-only commands (view.*, window.*, help.*, \ + edit.dynamicSpelling, and app.* except app.links, which works everywhere) work too.", obj(json!({"command": string("Command id, e.g. frame.create"), "params": params_schema()}), &["command"]), false, ), @@ -182,8 +182,9 @@ pub fn tool_definitions() -> Vec { tool( "new_document", "New document", - "Create a new document and make it active. Sizes are in points (72 pt = 1 in). sample:true opens the multi-page \ - magazine sample instead.", + "Create a new document and make it active. All size parameters (width, height, gutter, margins, bleed, slug) are in \ + points (72 pt = 1 in, 72/25.4 pt = 1 mm); `units` sets the document's ruler units only. sample:true opens the \ + multi-page magazine sample instead.", obj( json!({ "preset": string("Page size preset, e.g. \"Letter\", \"A4\", \"Tabloid\""), @@ -198,7 +199,7 @@ pub fn tool_definitions() -> Vec { "bleed": {"description": "Bleed on all sides (pt) or [top, bottom, inside, outside]", "anyOf": [{"type": "number"}, {"type": "array", "items": {"type": "number"}}]}, "title": string("Document title"), "intent": {"type": "string", "enum": ["print", "web", "mobile"], "description": "Document intent"}, - "units": string("Ruler units, e.g. \"points\", \"picas\", \"millimeters\""), + "units": {"type": "string", "enum": designcraft_geom::Unit::ALL, "description": "Document ruler units only (does not convert width, height, gutter, margins, bleed, or slug, which are always in points)"}, "startPage": {"type": "integer", "minimum": 1, "description": "Number of the first page"}, "slug": {"description": "Slug on all sides (pt) or [top, bottom, inside, outside]", "anyOf": [{"type": "number"}, {"type": "array", "items": {"type": "number"}}]}, "primaryTextFrame": boolean("Put a primary text frame on the parent page"), diff --git a/docs/agents.md b/docs/agents.md index 8058510e6..7cd06068e 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -16,7 +16,7 @@ designcraft-cli commands footnote # every command whose id/label/menu men designcraft-cli describe xref.insert # label, menu path, shortcut and parameters of one command ``` -Parameters are documented on each command (`params`), e.g. `{anchor? | paragraph?: text to find | story? + para?, format?}`. +Parameters are documented on each command (`params`), e.g. `{anchor? | paragraph?: text to find | story? + para?, format?}`. All numeric lengths and coordinates are in points (72 pt = 1 in, 72 / 25.4 pt = 1 mm); `units` on `file.new` sets the document's ruler units only. ## Scripts: several commands, later ones using earlier results diff --git a/docs/mcp.md b/docs/mcp.md index c6b0ab163..6b5c013ae 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -196,8 +196,8 @@ nonnegative integers; `null` and values of other types return an error. ## Coordinates -Points (1/72 in), y down, in **spread** space: on a single-page spread the page's top-left is (0, 0); on a facing -spread the right page starts at x = page width. `inspect_document` lists page bounds per spread. Page indices in +Points (1/72 in; 72 / 25.4 pt = 1 mm), y down, in **spread** space: on a single-page spread the page's top-left is (0, 0); on a facing +spread the right page starts at x = page width. All command length parameters — including `width`, `height`, `gutter`, `margins`, `bleed` and `slug` on `file.new` / `new_document` — are in points; `units` on `file.new` sets the document's ruler units only. `inspect_document` lists page bounds per spread. Page indices in `render_page` / `export_png` are 0-based. Commands that create items take `spread`: a body spread index, or `{"kind": "parent", "index": 0}` for a parent spread (its index in `parents` of `inspect_document`); any other value is an error. `pointer` events in connected mode may use `"space": "screen"` (egui points, @@ -264,7 +264,7 @@ Use `execute` with `object.fit` to fit a selected graphic frame (or pass `ids`): | `inspect_document` | Pages, spreads, items (ids, bounds, fill, story), stories (overset), layers, styles, swatches, selection | | `get_story` | Text, frames, paragraphs, lines, overset of a story (`story` or text `frame`) | | `set_story_text` | Replace a story's text (`\n` = new paragraph) | -| `new_document` | `file.new` (preset, intent, units, width, height, pages, startPage, facingPages, binding, columns, gutter, margins, bleed, slug, title, primaryTextFrame) or `sample: true` | +| `new_document` | `file.new` (preset, intent, units [ruler units only], width, height, pages, startPage, facingPages, binding, columns, gutter, margins, bleed, slug, title, primaryTextFrame — all sizes in pt) or `sample: true` | | `open_document` / `save_document` | Native `.designcraft` files | | `place_image` | Image from `path` or `base64` into `frame`, the selected frame, or a new frame at x, y, width | | `render_page` | Render a page → MCP image content (PNG, base64); optional `path` to also save it |