mirror of
https://github.com/storytold/designcraft.git
synced 2026-12-02 20:21:15 -05:00
Merge pull request #3475 from AlPaka1234/fix/3198-file-new-units
file.new: validate ruler units and document point-sized parameters (#3198)
This commit is contained in:
6 files changed
+81
-13
No files matched your search
@@ -20,6 +20,7 @@ fn new_document_settings(s: &Session, p: &Value) -> Result<NewDocument> {
|
||||
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<Value> {
|
||||
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::<designcraft_geom::Unit>(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();
|
||||
|
||||
@@ -9,10 +9,10 @@ use super::{CommandSpec, PRESETS, Value, always, bad, cmd, has_doc, json, ok, st
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
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<Value> = 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<CommandSpec> {
|
||||
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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -123,9 +123,9 @@ pub fn tool_definitions() -> Vec<Value> {
|
||||
"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<Value> {
|
||||
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<Value> {
|
||||
"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"),
|
||||
|
||||
+1
-1
@@ -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
|
||||
|
||||
|
||||
+3
-3
@@ -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 |
|
||||
|
||||
Reference in new issue
Block a user