mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 09:21:55 +01:00
document.export, document.exportSelection, document.serialize, app.export
and file.export took {noSuchOption: true} and wrote the file with no
warning. They now refuse a key that no format lists in document.formats,
and name the nearest key when one is close. document.exportPdf,
document.pdfSettings and pdf.preset.save refuse a key PDF doesn't take,
document.exportEps one EPS doesn't take and document.exportDxf one DXF
doesn't take. Each refuses an unknown key inside an option object it takes,
such as marks.useDocumentBleed, and names its path.
A key that only another format reads, such as {format: pdf, quality: 80},
is still ignored: docs/mcp.md says one object can carry several formats'
options. The check runs for callers (the control channel, MCP, the CLI).
A journal or a recorded action isn't checked, and a saved PDF preset with
a key that is no longer read still loads.
document.formats now also lists PDF's thumbnails, fastWebView and
viewAfterSaving.
321 lines
17 KiB
Rust
321 lines
17 KiB
Rust
//! The params descriptions name the keys their commands accept (#1442).
|
|
|
|
use serde_json::json;
|
|
|
|
use crate::cmd::params::{UNCHECKED, check_effect_params, check_keys, check_params, doc_keys};
|
|
use crate::{EngineError, Session, command_specs, find_command};
|
|
|
|
fn keys(doc: &str) -> Vec<&str> {
|
|
doc_keys(doc).unwrap().keys
|
|
}
|
|
|
|
#[test]
|
|
fn a_description_names_its_keys() {
|
|
assert_eq!(keys("{} → {id}"), Vec::<&str>::new());
|
|
assert_eq!(
|
|
keys("{x, y, width?: pt=612|\"210 mm\", sides=6, name?|title?: a name (default: Untitled-N)} → {index}"),
|
|
["x", "y", "width", "sides", "name", "title"]
|
|
);
|
|
// Brackets, quotes and backticks keep their commas and bars; a nested object isn't listed.
|
|
assert_eq!(
|
|
keys("{at: [x, y] (page, not view), stops: [{position: pt, leader?: \", \"}], csv?: a `|, ` in a label is a break, on?: bool}"),
|
|
["at", "stops", "csv", "on"]
|
|
);
|
|
// Alternatives after a note are keys when they have their own `?` or `:`; else values.
|
|
assert_eq!(
|
|
keys("{steps?: n | distance?: pt | smooth?: bool, spacing?: smooth|steps|distance, path? | data?: text | dataBase64?}"),
|
|
["steps", "distance", "smooth", "spacing", "path", "data", "dataBase64"]
|
|
);
|
|
let more = doc_keys("{name, …settings as file.new, …the format's options}").unwrap();
|
|
assert_eq!((more.keys, more.more), (vec!["name"], vec!["settings as file.new", "the format's options"]));
|
|
for bad in ["same as paint.setFill", "{a, b", "{opacity? 0..1}", "{path | name+dataBase64}", "{kind?: Group, Path or Type}"] {
|
|
assert!(doc_keys(bad).is_err(), "{bad}");
|
|
}
|
|
}
|
|
|
|
/// Every command's description reads as a params object, so none is left unchecked by accident.
|
|
#[test]
|
|
fn every_description_parses() {
|
|
let bad: Vec<String> = command_specs().iter().filter_map(|c| doc_keys(c.params).err().map(|e| format!("{}: {e}", c.id))).collect();
|
|
assert!(bad.is_empty(), "{} descriptions don't parse:\n{}", bad.len(), bad.join("\n"));
|
|
let stale: Vec<_> = UNCHECKED.iter().filter(|id| find_command(id).is_none()).collect();
|
|
assert!(stale.is_empty() && UNCHECKED.is_sorted(), "UNCHECKED: sorted ids of commands; not commands: {stale:?}");
|
|
}
|
|
|
|
fn refusal(id: &str, params: serde_json::Value) -> String {
|
|
match check_params(id, ¶ms) {
|
|
Err(EngineError::BadParams { cmd, msg }) if cmd == id => msg,
|
|
other => panic!("{id} {params}: {other:?}"),
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn an_unknown_key_is_named_with_the_nearest_accepted_one() {
|
|
assert_eq!(refusal("file.new", json!({"widht": 300})), "unknown parameter `widht`; did you mean `width`?");
|
|
assert_eq!(refusal("file.new", json!({"Width": 300})), "unknown parameter `Width`; did you mean `width`?");
|
|
assert_eq!(refusal("select.all", json!({"zzz": 1})), "unknown parameter `zzz`; the command takes no parameters");
|
|
assert_eq!(
|
|
refusal("shape.line", json!({"x1": 0, "y1": 0, "x2": 5, "y2": 5, "colour": "red"})),
|
|
"unknown parameter `colour`; the command takes: x1, y1, x2, y2, fill"
|
|
);
|
|
for (id, ok) in [
|
|
("file.new", json!({"width": 300, "title": "a", "artboardLayout": {"anything": 1}})),
|
|
("file.new", json!({})),
|
|
("file.new", json!(null)),
|
|
// Keys listed by reference, and any key where the description says so.
|
|
("file.newPresets.save", json!({"name": "a", "width": 300})),
|
|
("document.export", json!({"format": "png", "styling": "style"})),
|
|
// Not a command: running it says so.
|
|
("no.such", json!({"x": 1})),
|
|
] {
|
|
assert!(check_params(id, &ok).is_ok(), "{id} {ok}");
|
|
}
|
|
assert!(check_keys("x", "{a, …as file.new}", &json!({"a": 1, "width": 2})).is_ok());
|
|
assert!(check_keys("x", "{a, …as file.new}", &json!({"b": 1})).is_err());
|
|
}
|
|
|
|
/// An export's options: a key no format reads is refused, at the top level and in the PDF objects,
|
|
/// under each command that takes them.
|
|
#[test]
|
|
fn export_options_refuse_a_key_no_format_reads() {
|
|
for id in ["document.export", "document.exportSelection", "document.serialize"] {
|
|
assert_eq!(
|
|
refusal(id, json!({"format": "pdf", "standard": "pdfX4", "noSuchOption": true})),
|
|
"unknown parameter `noSuchOption`; no format takes it (see document.formats)"
|
|
);
|
|
assert_eq!(refusal(id, json!({"format": "pdf", "standardd": "pdfX4"})), "unknown parameter `standardd`; did you mean `standard`?");
|
|
assert_eq!(
|
|
refusal(id, json!({"format": "pdf", "options": {"standard": "pdfX4"}})),
|
|
"unknown parameter `options`; no format takes it (see document.formats)"
|
|
);
|
|
}
|
|
// A command that writes one format refuses another format's option, and says which format.
|
|
for (id, why) in [
|
|
("document.exportPdf", "PDF doesn't take it"),
|
|
("document.pdfSettings", "PDF doesn't take it"),
|
|
("pdf.preset.save", "PDF doesn't take it"),
|
|
("document.exportEps", "EPS doesn't take it"),
|
|
("document.exportDxf", "DXF doesn't take it"),
|
|
] {
|
|
for key in ["noSuchOption", "quality"] {
|
|
assert_eq!(refusal(id, json!({key: 1})), format!("unknown parameter `{key}`; {why} (see document.formats)"));
|
|
}
|
|
}
|
|
assert_eq!(
|
|
refusal("document.exportEps", json!({"flattener": {"balanse": 50}})),
|
|
"unknown parameter `flattener.balanse`; did you mean `flattener.balance`?"
|
|
);
|
|
assert!(refusal("document.exportDxf", json!({"flattener": {}})).contains("DXF doesn't take it"));
|
|
assert!(refusal("document.exportEps", json!({"marks": {}})).contains("EPS doesn't take it"));
|
|
for id in ["document.pdfSettings", "pdf.preset.save"] {
|
|
assert!(refusal(id, json!({"marks": {"useDocumentBleed": true}})).starts_with("unknown parameter `marks.useDocumentBleed`;"), "{id}");
|
|
}
|
|
for (given, message) in [
|
|
(json!({"marks": {"useDocumentBleed": true}}), "unknown parameter `marks.useDocumentBleed`; `marks` takes:"),
|
|
(json!({"bleed": {"useDocumen": true}}), "unknown parameter `bleed.useDocumen`; did you mean `bleed.useDocument`?"),
|
|
(json!({"output": {"intent": "x"}}), "unknown parameter `output.intent`;"),
|
|
(json!({"advanced": {"outlineTxt": true}}), "unknown parameter `advanced.outlineTxt`; did you mean `advanced.outlineText`?"),
|
|
(json!({"security": {"openPasswrd": "x"}}), "unknown parameter `security.openPasswrd`; did you mean `security.openPassword`?"),
|
|
(json!({"compression": {"color": {"dpi": 300}}}), "unknown parameter `compression.color.dpi`;"),
|
|
(json!({"flattener": {"balanse": 50}}), "unknown parameter `flattener.balanse`; did you mean `flattener.balance`?"),
|
|
] {
|
|
for id in ["document.export", "document.exportPdf"] {
|
|
let got = refusal(id, given.clone());
|
|
assert!(got.starts_with(message), "{id} {given}: {got}");
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The check passes each key `document.formats` lists, each key a command's own description names,
|
|
/// and each field of the PDF settings and the flattener options. A key an encoder reads that none
|
|
/// of these names is outside this test.
|
|
#[test]
|
|
fn export_options_pass_every_listed_key() {
|
|
use crate::cmd::fileio::{FORMATS, dxf, eps, pdf::OPTIONS};
|
|
for f in FORMATS.iter().filter(|f| f.write) {
|
|
for o in f.options {
|
|
let params = json!({"format": f.id, o.name: null});
|
|
assert!(check_params("document.export", ¶ms).is_ok(), "{params}");
|
|
}
|
|
}
|
|
for (id, options) in [("document.exportEps", eps::OPTIONS), ("document.exportDxf", dxf::OPTIONS), ("document.exportPdf", OPTIONS)] {
|
|
for o in options {
|
|
assert!(check_params(id, &json!({o.name: null})).is_ok(), "{id} {}", o.name);
|
|
}
|
|
}
|
|
for id in [
|
|
"document.export",
|
|
"document.exportSelection",
|
|
"document.serialize",
|
|
"document.exportPdf",
|
|
"document.pdfSettings",
|
|
"pdf.preset.save",
|
|
"document.exportEps",
|
|
"document.exportDxf",
|
|
] {
|
|
// An export reads these two when it writes over the file a lossy document came from. The
|
|
// PDF settings and preset commands take them through document.exportPdf's description.
|
|
check_params(id, &json!({"path": "a", "acknowledgeLoss": true})).unwrap_or_else(|e| panic!("{id}: {e}"));
|
|
let keys = doc_keys(find_command(id).unwrap().params).unwrap().keys;
|
|
let refused: Vec<&str> = keys.into_iter().filter(|key| check_params(id, &json!({*key: null})).is_err()).collect();
|
|
// `document.exportPdf`'s description explains the page boxes as `BleedBox = …` between its
|
|
// keys, which reads as two more keys.
|
|
let prose = if id == "document.exportPdf" { vec!["BleedBox", "MediaBox"] } else { vec![] };
|
|
assert_eq!(refused, prose, "{id} names and refuses these");
|
|
}
|
|
let settings = serde_json::to_value(vectorcraft_pdf::PdfSettings::default()).unwrap();
|
|
for key in settings.as_object().unwrap().keys() {
|
|
assert!(OPTIONS.iter().any(|o| o.name == key), "document.formats doesn't list the PDF option `{key}`");
|
|
}
|
|
let mut every = settings;
|
|
every["flattener"] = serde_json::to_value(crate::cmd::flatten::FlattenOptions::default()).unwrap();
|
|
every["security"]["openPassword"] = json!("a");
|
|
every["security"]["permissionsPassword"] = json!("b");
|
|
every["preset"] = json!("High Quality Print");
|
|
for id in ["document.export", "document.exportPdf", "document.pdfSettings", "pdf.preset.save"] {
|
|
check_params(id, &every).unwrap_or_else(|e| panic!("{id}: {e}"));
|
|
}
|
|
}
|
|
|
|
/// `stroke.set` names every key it reads (its own, `item`, and `ids`/`id`/`target`), so a
|
|
/// misnamed one is refused instead of answering `objects: 1` with nothing changed.
|
|
#[test]
|
|
fn stroke_set_refuses_an_unknown_key() {
|
|
assert!(!UNCHECKED.contains(&"stroke.set"));
|
|
let e = refusal("stroke.set", json!({"ids": [7], "width": 0.5}));
|
|
assert!(e.starts_with("unknown parameter `width`") && e.contains("weight"), "{e}");
|
|
for ok in [
|
|
json!({"ids": [7], "weight": 0.5}),
|
|
json!({"id": 7, "weight": 1, "cap": "round", "join": "bevel", "miterLimit": 4, "align": "inside"}),
|
|
json!({"dash": [6, 3], "dashOffset": 1, "alignDashes": true, "startArrow": "Arrow", "endArrow": null, "arrowAlign": "tip"}),
|
|
json!({"profile": "lens", "item": null, "target": "contents"}),
|
|
// `item_target` reads `aligned` for an explicit item.
|
|
json!({"item": 1, "aligned": true, "weight": 2}),
|
|
// What document.inspect reports in strokeOptions reads back unchanged.
|
|
json!({"widthPoints": null, "gradientMode": "within"}),
|
|
] {
|
|
assert!(check_params("stroke.set", &ok).is_ok(), "{ok}");
|
|
}
|
|
}
|
|
|
|
/// A command that takes the keys of one that isn't checked yet isn't checked either.
|
|
#[test]
|
|
fn a_reference_to_an_unchecked_command_is_unchecked() {
|
|
assert!(UNCHECKED.contains(&"paint.setFill") && !UNCHECKED.contains(&"paint.setStroke"), "pick another pair");
|
|
assert!(check_params("paint.setStroke", &json!({"zzz": 1})).is_ok());
|
|
assert!(check_keys("x", "{a, …as paint.setFill}", &json!({"zzz": 1})).is_ok());
|
|
}
|
|
|
|
#[test]
|
|
fn a_batch_checks_its_steps() {
|
|
let step = |params| json!({"commands": [{"command": "select.all"}, {"command": "file.new", "params": params}]});
|
|
assert!(check_params("command.batch", &step(json!({"width": 300}))).is_ok());
|
|
match check_params("command.batch", &step(json!({"widht": 300}))) {
|
|
Err(EngineError::BadParams { cmd, msg }) => {
|
|
assert_eq!((cmd.as_str(), msg.as_str()), ("file.new", "unknown parameter `widht`; did you mean `width`?"))
|
|
}
|
|
other => panic!("{other:?}"),
|
|
}
|
|
assert_eq!(refusal("command.batch", json!({"steps": []})), "unknown parameter `steps`; the command takes: label, commands, artboard");
|
|
}
|
|
|
|
/// #1592: the `params` of an effect are held to the effect's own keys and types, where the effect
|
|
/// is named (`effect.apply`) and where the document says which it is (`effect.setParams`).
|
|
#[test]
|
|
fn effect_params_are_the_effects_own() {
|
|
use vectorcraft_render::effects::effect_catalog;
|
|
for e in effect_catalog() {
|
|
doc_keys(e.params).unwrap_or_else(|why| panic!("{}: {why}", e.id));
|
|
check_effect_params("effect.apply", e.id, &e.defaults).unwrap_or_else(|why| panic!("{}'s defaults: {why}", e.id));
|
|
}
|
|
let apply = |effect: &str, params| json!({"effect": effect, "params": params});
|
|
assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"blurr": 3}))), "unknown parameter `blurr`; the command takes: radius, linear");
|
|
assert_eq!(
|
|
refusal("appearance.addEffect", apply("stylize.dropShadow", json!({"opacty": 50}))),
|
|
"unknown parameter `opacty`; did you mean `opacity`?"
|
|
);
|
|
assert_eq!(refusal("effect.apply", apply("blur.gaussian", json!({"radius": "big"}))), "`radius` must be a number");
|
|
assert_eq!(refusal("effect.apply", apply("threeD.revolve", json!({"shade": 1}))), "`shade` must be true or false");
|
|
assert_eq!(refusal("effect.apply", apply("threeD.revolve", json!({"edge": 1}))), "`edge` must be a string");
|
|
// Out of range is the effect's to clamp; a key only its description names is one it takes;
|
|
// a plug-in's are its manifest's; an unknown effect is the command's to report.
|
|
for (effect, params) in [
|
|
("stylize.dropShadow", json!({"opacity": 500, "x": -3, "color": "#ff0000"})),
|
|
("stylize.dropShadow", json!({"color": [1, 0, 0]})),
|
|
("threeD.revolve", json!({"segments": 100000})),
|
|
("path.outlineStroke", json!({"width": 2})),
|
|
("plugin.anything", json!({"whatever": 1})),
|
|
("no.such", json!({"whatever": 1})),
|
|
] {
|
|
assert!(check_params("effect.apply", &apply(effect, params.clone())).is_ok(), "{effect} {params}");
|
|
}
|
|
// `effect.setParams` names an index: the session knows the effect there.
|
|
let mut s = Session::new();
|
|
s.execute("file.new", &json!({})).unwrap();
|
|
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
|
|
s.execute("effect.apply", &apply("blur.gaussian", json!({"radius": 2}))).unwrap();
|
|
for (params, why) in [(json!({"blurr": 3}), "unknown parameter `blurr`"), (json!({"radius": true}), "`radius` must be a number")] {
|
|
let e = s.execute("effect.setParams", &json!({"index": 0, "params": params})).unwrap_err().to_string();
|
|
assert!(e.contains(why), "{e}");
|
|
}
|
|
s.execute("effect.setParams", &json!({"index": 0, "params": {"radius": 1e9}, "visible": false})).unwrap();
|
|
// No effect at the index: the command says so, not the check.
|
|
assert!(s.check_params("effect.setParams", &json!({"index": 7, "params": {"blurr": 3}})).is_ok());
|
|
}
|
|
|
|
/// The Transform effect (`distort.transform`) is held to its params description: `effect.apply`
|
|
/// and `effect.setParams` refuse each of its on/off options given as text, such as `reflectX:
|
|
/// "false"`, and each of its numbers given as text, such as `copies: "0"`, and leave the effect
|
|
/// as it was; true, false and numbers pass. The loop takes the keys from the effect's defaults, so
|
|
/// an option the effect gains is checked too.
|
|
#[test]
|
|
fn transform_effect_refuses_a_boolean_or_number_given_as_text() {
|
|
let info = vectorcraft_render::effects::effect_info("distort.transform").unwrap();
|
|
let one = |key: &str, v: serde_json::Value| serde_json::Value::Object([(key.to_string(), v)].into_iter().collect());
|
|
let apply = |params| json!({"effect": "distort.transform", "params": params});
|
|
let mut s = Session::new();
|
|
s.execute("file.new", &json!({})).unwrap();
|
|
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
|
|
s.execute("effect.apply", &apply(json!({"moveH": 20}))).unwrap();
|
|
let state = |s: &Session| {
|
|
let st = s.doc().unwrap();
|
|
(st.history.undo.len(), st.doc.layers[0].children().unwrap()[0].appearance.effects[0].params.clone())
|
|
};
|
|
let before = state(&s);
|
|
let mut switches = vec![];
|
|
for (key, default) in info.defaults.as_object().unwrap() {
|
|
let why = match default {
|
|
serde_json::Value::Bool(_) => format!("`{key}` must be true or false"),
|
|
serde_json::Value::Number(_) => format!("`{key}` must be a number"),
|
|
_ => continue,
|
|
};
|
|
if default.is_boolean() {
|
|
switches.push(key.as_str());
|
|
}
|
|
let text = json!(default.to_string());
|
|
assert_eq!(refusal("effect.apply", apply(one(key, text.clone()))), why);
|
|
let e = s.execute("effect.setParams", &json!({"index": 0, "params": one(key, text)})).unwrap_err().to_string();
|
|
assert!(e.contains(&why), "{e}");
|
|
assert!(check_params("effect.apply", &apply(one(key, default.clone()))).is_ok(), "{key}");
|
|
}
|
|
assert!(["reflectX", "reflectY", "random"].iter().all(|k| switches.contains(k)), "{switches:?}");
|
|
assert_eq!(state(&s), before);
|
|
s.execute("effect.setParams", &json!({"index": 0, "params": {"reflectX": true, "random": false, "copies": 2}})).unwrap();
|
|
}
|
|
|
|
/// What a command notes for its journal entry is a key its description names, so the entry
|
|
/// passes the check a caller's params get.
|
|
#[test]
|
|
fn journal_entries_pass_the_check() {
|
|
let mut s = Session::new();
|
|
s.execute("file.new", &json!({})).unwrap();
|
|
s.execute("shape.rectangle", &json!({"x": 10, "y": 10, "width": 50, "height": 40})).unwrap();
|
|
s.execute("select.all", &json!({})).unwrap();
|
|
s.execute("object.scale", &json!({"sx": 150})).unwrap();
|
|
s.execute("text.create", &json!({"x": 10, "y": 100, "text": "a"})).unwrap();
|
|
assert!(s.journal.iter().count() >= 5);
|
|
for (id, params) in s.journal.iter() {
|
|
assert!(check_params(id, params).is_ok(), "{id} {params}");
|
|
}
|
|
}
|