SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: the canvas commands describe their exact parameters and reply (#12275) (#12338)
PeppaWutz1444801d9697
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex 8dd0443756..377a0113e2 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -108,6 +108,7 @@ mod sketch;pub(crate) use sketch::author_path_for_rebind;pub(crate) use sketch::collapse_reason;pub(crate) use sketch::created as sketch_created;+pub(crate) use sketch::{PLANE_REF_FORMS, custom_plane_form};mod canvas_sketch;mod sketch_3d;mod sketch_canvas;diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 630683777d..a06fb01b26 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -733,6 +733,22 @@ pub(crate) fn author_path_for_rebind(s: &Session, feature: &solidcraft_doc::FeatOk(path)}+/// The message for a `plane` that is none of the forms [`plane_ref`] takes.+pub(crate) const PLANE_REF_FORMS: &str = "`plane` must be XY, XZ, YZ, a construction plane name or id, or an object";++/// An explicit plane object `{origin?, x_dir, y_dir}` as [`plane_ref`] reads it before it looks at+/// the design, or its message. A missing origin is the world origin; one that is given but is not+/// three numbers (an expression, a number with a unit) is an error, not a silent [0, 0, 0].+pub(crate) fn custom_plane_form(v: &Value) -> std::result::Result<Plane, &'static str> {+ let origin = match v.get("origin") {+ None | Some(Value::Null) => Vec3::ZERO,+ Some(o) => vec3(o).ok_or("plane `origin` must be three numbers [x, y, z] in mm (expressions are not evaluated here)")?,+ };+ let x = v.get("x_dir").and_then(vec3).ok_or("plane needs x_dir")?;+ let y = v.get("y_dir").and_then(vec3).ok_or("plane needs y_dir")?;+ Plane::new(origin, x, y).ok_or("degenerate plane")+}+pub(super) fn plane_ref(s: &Session, p: &Value, cmd: &str) -> Result<PlaneRef> {let base = match p.get("plane") {None => PlaneRef::Origin { name: "XY".into() },@@ -742,19 +758,10 @@ pub(super) fn plane_ref(s: &Session, p: &Value, cmd: &str) -> Result<PlaneRef> {if o.contains_key("face") {face::capture(s, v, cmd)?} else {- // A missing origin is the world origin; one that is given but is not three numbers- // (an expression, a number with a unit) is an error, not a silent [0, 0, 0].- let origin = match v.get("origin") {- None | Some(Value::Null) => Vec3::ZERO,- Some(o) => vec3(o)- .ok_or_else(|| bad(cmd, "plane `origin` must be three numbers [x, y, z] in mm (expressions are not evaluated here)"))?,- };- let x = v.get("x_dir").and_then(vec3).ok_or_else(|| bad(cmd, "plane needs x_dir"))?;- let y = v.get("y_dir").and_then(vec3).ok_or_else(|| bad(cmd, "plane needs y_dir"))?;- PlaneRef::Custom { plane: Plane::new(origin, x, y).ok_or_else(|| bad(cmd, "degenerate plane"))? }+ PlaneRef::Custom { plane: custom_plane_form(v).map_err(|why| bad(cmd, why))? }}}- _ => return Err(bad(cmd, "`plane` must be XY, XZ, YZ, a construction plane name or id, or an object")),+ _ => return Err(bad(cmd, PLANE_REF_FORMS)),};Ok(match expr(p, "offset") {Some(d) => PlaneRef::Offset { base: Box::new(base), distance: d },diff --git a/crates/engine/src/cmd/sketch_canvas.rs b/crates/engine/src/cmd/sketch_canvas.rsindex 689fb5a76a..c732700391 100644--- a/crates/engine/src/cmd/sketch_canvas.rs+++ b/crates/engine/src/cmd/sketch_canvas.rs@@ -7,21 +7,53 @@ use solidcraft_geom::prelude::*;use super::CommandSpec;use crate::params::{bad, bool_, num, str_, vec2};+use crate::schema::canvas::{+ CanvasCalibrateParams, CanvasCalibrated, CanvasDecalParams, CanvasDeleteParams, CanvasDeleted, CanvasEditParams, CanvasEdited,+ CanvasInsertParams, CanvasPlaced,+};+use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};+const INSERT_CONTRACT: TypedContract<CanvasInsertParams> = TypedContract::new();+const DECAL_CONTRACT: TypedContract<CanvasDecalParams> = TypedContract::new();+const EDIT_CONTRACT: TypedContract<CanvasEditParams> = TypedContract::new();+const CALIBRATE_CONTRACT: TypedContract<CanvasCalibrateParams> = TypedContract::new();+const DELETE_CONTRACT: TypedContract<CanvasDeleteParams> = TypedContract::new();++/// A canvas command's reply, built from its schema's type so the two can't drift apart.+fn canvas_reply(cmd: &str, r: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))+}+pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("canvas.insert", "Canvas", add_canvas)+ CommandSpec::new("canvas.insert", "Canvas", crate::checked!("canvas.insert", add_canvas)).at("SKETCH", "INSERT").icon("canvas")+ .contract(&INSERT_CONTRACT)+ .output(output_schema_for::<CanvasPlaced>).params("path | data (base64 PNG or JPEG); plane?: XY|XZ|YZ|{face: [x,y,z]}|… (default XY); center?: [x,y] on the plane, or at?: [x,y,z]; width?: mm (default 100); angle?: deg; opacity?: 0…1 (default 0.5); flip?; name?"),- CommandSpec::new("canvas.decal", "Decal", add_decal)+ CommandSpec::new("canvas.decal", "Decal", crate::checked!("canvas.decal", add_decal)).at("SKETCH", "INSERT").icon("decal")+ .contract(&DECAL_CONTRACT)+ .output(output_schema_for::<CanvasPlaced>).params("path | data; face: [x,y,z] on a planar face (the image is centred there), or the picked face as sketch.create's plane takes it ({face, body, index, path?}); width?: mm; angle?: deg; opacity?: (default 1)"),- CommandSpec::new("canvas.edit", "Edit Canvas", edit_canvas).at("SKETCH", "INSERT").icon("canvas").params("canvas: id or name; center?, width?, angle?: deg, opacity?, flip?, visible?, name?"),- CommandSpec::new("canvas.calibrate", "Calibrate Canvas", calibrate).icon("measure")+ CommandSpec::new("canvas.edit", "Edit Canvas", crate::checked!("canvas.edit", edit_canvas))+ .at("SKETCH", "INSERT")+ .icon("canvas")+ .contract(&EDIT_CONTRACT)+ .output(output_schema_for::<CanvasEdited>)+ .params("canvas: id or name; center?, width?, angle?: deg, opacity?, flip?, visible?, name?"),+ CommandSpec::new("canvas.calibrate", "Calibrate Canvas", crate::checked!("canvas.calibrate", calibrate))+ .icon("measure")+ .contract(&CALIBRATE_CONTRACT)+ .output(output_schema_for::<CanvasCalibrated>).params("canvas: id or name; a, b: two points on the canvas plane [x,y]; distance: their true distance (mm): scales the image about a"),- CommandSpec::new("canvas.delete", "Delete Canvas", delete_canvas).icon("delete").params("canvas: id or name"),+ CommandSpec::new("canvas.delete", "Delete Canvas", crate::checked!("canvas.delete", delete_canvas))+ .icon("delete")+ .contract(&DELETE_CONTRACT)+ .output(output_schema_for::<CanvasDeleted>)+ .params("canvas: id or name"),];fn image_bytes(p: &Value, cmd: &str) -> Result<Vec<u8>> {@@ -79,7 +111,7 @@ fn make(s: &mut Session, p: &Value, cmd: &str, decal: bool) -> Result<Value> {visible: true,component,});- Ok(json!({"canvas": id, "name": name, "pixels": pixels}))+ canvas_reply(cmd, CanvasPlaced { canvas: id, name, pixels, param_warnings: Vec::new() })}fn add_canvas(s: &mut Session, p: &Value) -> Result<Value> {@@ -136,7 +168,7 @@ fn edit_canvas(s: &mut Session, p: &Value) -> Result<Value> {if let Some(n) = str_(p, "name").filter(|n| !n.trim().is_empty()) {c.name = n.to_string();}- Ok(json!({"canvas": c.id}))+ canvas_reply(cmd, CanvasEdited { canvas: c.id, param_warnings: Vec::new() })}fn calibrate(s: &mut Session, p: &Value) -> Result<Value> {@@ -153,13 +185,14 @@ fn calibrate(s: &mut Session, p: &Value) -> Result<Value> {let c = s.doc_mut().canvases.get_mut(i).ok_or_else(|| bad(cmd, "canvas"))?;c.width *= k;c.center = a + (c.center - a) * k;- Ok(json!({"canvas": c.id, "width": c.width}))+ canvas_reply(cmd, CanvasCalibrated { canvas: c.id, width: c.width, param_warnings: Vec::new() })}fn delete_canvas(s: &mut Session, p: &Value) -> Result<Value> {- let i = find(s, p, "canvas.delete")?;+ let cmd = "canvas.delete";+ let i = find(s, p, cmd)?;let c = s.doc_mut().canvases.remove(i);- Ok(json!({"deleted": c.id}))+ canvas_reply(cmd, CanvasDeleted { deleted: c.id, param_warnings: Vec::new() })}#[cfg(test)]diff --git a/crates/engine/src/schema/canvas.rs b/crates/engine/src/schema/canvas.rsnew file mode 100644index 0000000000..ef193c3132--- /dev/null+++ b/crates/engine/src/schema/canvas.rs@@ -0,0 +1,459 @@+//! Contracts and result types for the commands in `cmd/sketch_canvas.rs`: `canvas.insert`,+//! `canvas.decal`, `canvas.edit`, `canvas.calibrate` and `canvas.delete`.+//!+//! The handlers read their parameters from the raw JSON, so each key here reads as its handler+//! reads it and fails with the handler's message. Whether an image can be read, a canvas exists+//! or a face is there stays the handler's to check. A call with several problems may get a+//! different one first in strict than with the check off (the check goes key by key, the handlers+//! in their own order).++use std::borrow::Cow;++use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};+use serde::de::Error as _;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::{Value, json};++use super::check::whole;+use super::motion::require;+use super::types::{LengthExpr, Point2, Point3};+use crate::params;++/// Place an image on a plane as a reference to trace, kept in the design. Give the image as+/// `path` or as base64 `data`; only PNG and JPEG are taken, up to 16 MiB. The image goes into the+/// active component. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = image_required)]+pub struct CanvasInsertParams {+ /// A PNG or JPEG file to read (not blank, under 4096 characters). Used when `data` is not+ /// given.+ #[serde(default)]+ pub path: Option<String>,+ /// The image itself, a PNG or JPEG, as base64. Wins over `path`.+ #[serde(default)]+ pub data: Option<String>,+ /// The plane the image lies on. Default: XY. A picked face is read as `sketch.create` reads+ /// one.+ #[serde(default, deserialize_with = "super::present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CanvasPlane")]+ pub plane: Option<CanvasPlane>,+ /// Move the plane this far along its normal (mm or a length expression).+ #[serde(default)]+ pub offset: Option<LengthExpr>,+ /// Where the image's centre is, on the plane, in mm. Default: `at`; else the picked point when+ /// `plane` is a picked face; else the plane's origin.+ #[serde(default)]+ pub center: Option<Point2>,+ /// A point [x, y, z] in mm, projected onto the plane, for the centre when `center` is not+ /// given. Default: the picked point when `plane` is a picked face, else the plane's origin.+ #[serde(default)]+ pub at: Option<Point3>,+ /// The image's width on the plane, in mm (above 0, below 1e7); its height follows the+ /// image. Default: 100.+ #[serde(default)]+ pub width: Option<CanvasWidth>,+ /// Its rotation on the plane, in degrees (a number of 1e9 or more is ignored). Default: 0.+ #[serde(default)]+ pub angle: Option<f64>,+ /// Mirror it left to right. Default: false.+ #[serde(default)]+ pub flip: Option<bool>,+ /// Its name. Default: "Canvas" and the first number no canvas's name has.+ #[serde(default)]+ pub name: Option<String>,+ /// Its opacity, 0 (clear) to 1 (opaque); a value outside is clamped (a number of 1e9 or more is ignored, as if left out). Default: 0.5.+ #[serde(default)]+ pub opacity: Option<f64>,+}++/// Put an image on a planar face of the model, like a sticker, kept in the design. Give the image+/// as `path` or as base64 `data`; only PNG and JPEG are taken, up to 16 MiB. The image goes into+/// the active component. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = decal_required)]+pub struct CanvasDecalParams {+ /// A PNG or JPEG file to read (not blank, under 4096 characters). Used when `data` is not+ /// given.+ #[serde(default)]+ pub path: Option<String>,+ /// The image itself, a PNG or JPEG, as base64. Wins over `path`.+ #[serde(default)]+ pub data: Option<String>,+ // Optional in the type and required in the schema (`decal_required`): left out, the handler+ // refuses it with its own message, not the check's "is required".+ /// The face: a point [x, y, z] in mm on a planar face, where the image is centred, or a+ /// picked face as `sketch.create`'s `plane` takes it: `{face: [x, y, z], body?, index?,+ /// path?, fixed?}` (`body` and `index` go together).+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "DecalFace")]+ pub face: Option<DecalFace>,+ /// Move the face's plane this far along its normal (mm or a length expression).+ #[serde(default)]+ pub offset: Option<LengthExpr>,+ /// Where the image's centre is, on the face's plane, in mm. Default: `at`, or the picked+ /// point.+ #[serde(default)]+ pub center: Option<Point2>,+ /// A point [x, y, z] in mm, projected onto the plane, for the centre when `center` is not+ /// given. Default: the picked point.+ #[serde(default)]+ pub at: Option<Point3>,+ /// The image's width on the plane, in mm (above 0, below 1e7); its height follows the+ /// image. Default: 100.+ #[serde(default)]+ pub width: Option<CanvasWidth>,+ /// Its rotation on the plane, in degrees (a number of 1e9 or more is ignored). Default: 0.+ #[serde(default)]+ pub angle: Option<f64>,+ /// Mirror it left to right. Default: false.+ #[serde(default)]+ pub flip: Option<bool>,+ /// Its name. Default: "Decal" and the first number no canvas's name has.+ #[serde(default)]+ pub name: Option<String>,+ /// Its opacity, 0 (clear) to 1 (opaque); a value outside is clamped (a number of 1e9 or more is ignored, as if left out). Default: 1.+ #[serde(default)]+ pub opacity: Option<f64>,+}++/// Change a canvas or decal: its place, size, angle, opacity, mirroring, visibility or name. Keys+/// left out stay as they are. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = canvas_required)]+pub struct CanvasEditParams {+ /// The canvas, by id or name.+ // Optional in the type and required in the schema, as `face` above.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CanvasRef")]+ pub canvas: Option<CanvasRef>,+ /// The image's new centre on its plane, in mm.+ #[serde(default)]+ pub center: Option<Point2>,+ /// Its new width, in mm (above 0, below 1e7); its height follows the image.+ #[serde(default)]+ pub width: Option<CanvasWidth>,+ /// Its new rotation on the plane, in degrees (a number of 1e9 or more is ignored).+ #[serde(default)]+ pub angle: Option<f64>,+ /// Its new opacity, 0 (clear) to 1 (opaque); a value outside is clamped (a number of 1e9 or more is ignored, as if left out).+ #[serde(default)]+ pub opacity: Option<f64>,+ /// Mirror it left to right, or not.+ #[serde(default)]+ pub flip: Option<bool>,+ /// Show it or hide it.+ #[serde(default)]+ pub visible: Option<bool>,+ /// Its new name; blank text keeps the name.+ #[serde(default)]+ pub name: Option<String>,+}++/// Scale a canvas so that two points on it are a known distance apart: the image is scaled about+/// the first point. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = calibrate_required)]+pub struct CanvasCalibrateParams {+ /// The canvas, by id or name.+ // Optional in the types and required in the schema (`calibrate_required`), as `face` above.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CanvasRef")]+ pub canvas: Option<CanvasRef>,+ /// A point on the canvas's plane, in mm, [x, y]: the one the image is scaled about.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CalibrationPoint")]+ pub a: Option<CalibrationPoint>,+ /// Another point on the plane, in mm, [x, y], not the same as `a`.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CalibrationPoint")]+ pub b: Option<CalibrationPoint>,+ /// What the distance from `a` to `b` really is, in mm (above 0).+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Distance")]+ pub distance: Option<Distance>,+}++/// Remove a canvas or decal from the design. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = canvas_required)]+pub struct CanvasDeleteParams {+ /// The canvas, by id or name.+ // Optional in the type and required in the schema, as `face` above.+ #[serde(default, deserialize_with = "some", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CanvasRef")]+ pub canvas: Option<CanvasRef>,+}++/// A key that, once given (`null` included), must parse as `T`, as the handlers read it.+fn some<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result<Option<T>, D::Error> {+ T::deserialize(d).map(Some)+}++/// A canvas by its id (a number) or its name, as `find` in `cmd/sketch_canvas.rs` reads it.+#[derive(Clone, Debug, PartialEq)]+pub struct CanvasRef(pub String);++impl<'de> Deserialize<'de> for CanvasRef {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::Number(n) => Ok(CanvasRef(n.to_string())),+ Value::String(s) => Ok(CanvasRef(s)),+ _ => Err(D::Error::custom("must be an id or a name")),+ }+ }+}++impl JsonSchema for CanvasRef {+ fn schema_name() -> Cow<'static, str> {+ "CanvasRef".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A canvas's id (a number) or its name.", "type": ["number", "string"]})+ }+}++/// An image width in mm: above 0 and below 1e7, as `cmd/sketch_canvas.rs` requires.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct CanvasWidth(pub f64);++impl<'de> Deserialize<'de> for CanvasWidth {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::Number(n) => match n.as_f64() {+ Some(w) if w > 1e-6 && w < 1e7 => Ok(CanvasWidth(w)),+ _ => Err(D::Error::custom("must be positive")),+ },+ _ => Err(D::Error::custom("must be a number of mm")),+ }+ }+}++impl JsonSchema for CanvasWidth {+ fn schema_name() -> Cow<'static, str> {+ "CanvasWidth".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A width in mm: more than 0.000001 and below 10 000 000.",+ "type": "number", "exclusiveMinimum": 1e-6, "exclusiveMaximum": 1e7+ })+ }+}++/// `canvas.calibrate`'s `distance`: a number above 0 (and below 1e9), whatever else it is read+/// as `distance` must be positive.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Distance(pub f64);++impl<'de> Deserialize<'de> for Distance {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let n = match Value::deserialize(d)? {+ Value::Number(n) => n.as_f64().and_then(params::finite),+ _ => None,+ };+ n.filter(|d| *d > 1e-9).map(Distance).ok_or_else(|| D::Error::custom("must be positive"))+ }+}++impl JsonSchema for Distance {+ fn schema_name() -> Cow<'static, str> {+ "Distance".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A distance in mm: above 0 (more than 0.000000001) and below 1 000 000 000.",+ "type": "number", "exclusiveMinimum": 1e-9, "exclusiveMaximum": 1e9+ })+ }+}++/// A point of `canvas.calibrate`: `[x, y]` or `{x, y}` of numbers, with the handler's one message+/// for `a` and `b`.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct CalibrationPoint(pub solidcore_record::Vec2);++impl<'de> Deserialize<'de> for CalibrationPoint {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::vec2(&Value::deserialize(d)?).map(CalibrationPoint).ok_or_else(|| D::Error::custom(whole("`a` and `b` must be points [x,y]")))+ }+}++impl JsonSchema for CalibrationPoint {+ fn schema_name() -> Cow<'static, str> {+ "CalibrationPoint".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ generator.subschema_for::<Point2>()+ }+}++/// The plane of `canvas.insert`, as `sketch::plane_ref` reads it: an origin plane's name or alias,+/// a construction plane's name or feature id, a picked face `{face, …}`, or `{origin?, x_dir,+/// y_dir}`. Kept as given, for the handler. Whether a name or id names a plane is checked by the+/// handler, which has the design.+#[derive(Clone, Debug, PartialEq)]+pub struct CanvasPlane(pub Value);++impl<'de> Deserialize<'de> for CanvasPlane {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let v = Value::deserialize(d)?;+ let problem = match &v {+ Value::String(_) => None,+ Value::Number(n) if n.is_u64() => None,+ Value::Number(_) => Some(format!("`plane` must be {}", crate::cmd::PLANE_FORMS)),+ Value::Object(o) if o.contains_key("face") => crate::cmd::face_pick_form(&v).err().map(str::to_string),+ Value::Object(_) => crate::cmd::custom_plane_form(&v).err().map(str::to_string),+ _ => Some(crate::cmd::PLANE_REF_FORMS.to_string()),+ };+ match problem {+ Some(why) => Err(D::Error::custom(whole(why))),+ None => Ok(CanvasPlane(v)),+ }+ }+}++impl JsonSchema for CanvasPlane {+ fn schema_name() -> Cow<'static, str> {+ "CanvasPlane".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let point = generator.subschema_for::<Point3>();+ json_schema!({+ "description": "A plane: XY, XZ or YZ (or Top, Front or Right; any case), a construction plane's name or feature id, a picked planar face {\"face\": [x, y, z], \"body\"?, \"index\"?, \"path\"?, \"fixed\"?}, or an explicit plane {\"origin\"?, \"x_dir\", \"y_dir\"}: two directions [x, y, z] that aren't parallel and an origin in mm, numbers only (default: the origin).",+ "anyOf": [+ {"type": "string"},+ {"type": "integer", "minimum": 0, "maximum": u64::MAX},+ face_pick(&point),+ {+ "type": "object",+ "properties": {"origin": {"anyOf": [point, {"type": "null"}]}, "x_dir": point, "y_dir": point},+ "required": ["x_dir", "y_dir"],+ "not": {"required": ["face"]}+ }+ ]+ })+ }+}++/// The face of `canvas.decal`, as the handler reads it: a point on the face, or a picked face+/// `{face, body?, index?, path?, fixed?}`. Kept as given, for the handler.+#[derive(Clone, Debug, PartialEq)]+pub struct DecalFace(pub Value);++impl<'de> Deserialize<'de> for DecalFace {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let v = Value::deserialize(d)?;+ // A point alone is made a pick, as the handler does.+ let pick = if v.get("face").is_some() { v.clone() } else { json!({"face": v}) };+ match crate::cmd::face_pick_form(&pick) {+ Ok(_) => Ok(DecalFace(v)),+ Err(why) => Err(D::Error::custom(whole(why))),+ }+ }+}++impl JsonSchema for DecalFace {+ fn schema_name() -> Cow<'static, str> {+ "DecalFace".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let point = generator.subschema_for::<Point3>();+ json_schema!({+ "description": "A point [x, y, z] in mm on a planar face, or a picked face {\"face\": [x, y, z], \"body\"?, \"index\"?, \"path\"?, \"fixed\"?}: \"body\" (the picked body's world name) and \"index\" (the face's index in it) pick the face exactly and go together; \"path\" is the occurrence path of the body's placement (at most 64 nonzero ids); \"fixed\": true keeps the plane where the face is now.",+ "anyOf": [point, face_pick(&point)]+ })+ }+}++/// A picked face, as `sketch::face::face_pick_form` reads it.+fn face_pick(point: &Schema) -> Value {+ json!({+ "type": "object",+ "properties": {+ "face": point,+ "fixed": {"type": "boolean"},+ "body": {"type": "string", "minLength": 1, "description": "Goes with `index`: give both or neither."},+ "index": {"type": "integer", "minimum": 0, "description": "Goes with `body`: give both or neither."},+ "path": {"type": "array", "items": {"type": "integer", "minimum": 1}, "maxItems": 64}+ },+ "required": ["face"]+ })+}++/// `canvas.insert` and `canvas.decal` need `path` or `data`; the handler says so when both are+/// left out.+fn need_image(schema: &mut Schema) {+ schema.insert("anyOf".into(), json!([{"required": ["data"]}, {"required": ["path"]}]));+}++fn image_required(schema: &mut Schema) {+ need_image(schema);+}++fn decal_required(schema: &mut Schema) {+ need_image(schema);+ require(schema, "face");+}++fn canvas_required(schema: &mut Schema) {+ require(schema, "canvas");+}++fn calibrate_required(schema: &mut Schema) {+ for key in ["canvas", "a", "b", "distance"] {+ require(schema, key);+ }+}++/// What `canvas.insert` and `canvas.decal` return.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CanvasPlaced {+ /// The new canvas's id.+ pub canvas: u64,+ /// Its name.+ pub name: String,+ /// The image's size in pixels, [width, height].+ pub pixels: [u32; 2],+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// What `canvas.edit` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CanvasEdited {+ /// The canvas's id.+ pub canvas: u64,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// What `canvas.calibrate` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CanvasCalibrated {+ /// The canvas's id.+ pub canvas: u64,+ /// Its width now, in mm.+ pub width: f64,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++/// What `canvas.delete` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CanvasDeleted {+ /// The id the canvas had.+ pub deleted: u64,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}++#[cfg(test)]+#[path = "canvas_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/canvas_tests.rs b/crates/engine/src/schema/canvas_tests.rsnew file mode 100644index 0000000000..0d075bcbe7--- /dev/null+++ b/crates/engine/src/schema/canvas_tests.rs@@ -0,0 +1,243 @@+use serde_json::{Value, json};+use solidcraft_doc::canvas::base64_encode;++use super::{+ CanvasCalibrateParams, CanvasCalibrated, CanvasDecalParams, CanvasDeleteParams, CanvasDeleted, CanvasEditParams, CanvasEdited,+ CanvasInsertParams, CanvasPlaced, CanvasPlane, DecalFace,+};+use crate::Session;+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};++/// A PNG header: all the engine reads of an image is its size.+fn png() -> String {+ let mut b = b"\x89PNG\r\n\x1a\n\0\0\0\rIHDR".to_vec();+ b.extend(400u32.to_be_bytes());+ b.extend(200u32.to_be_bytes());+ b.extend([8, 6, 0, 0, 0, 0, 0, 0, 0]);+ base64_encode(&b)+}++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(+ input_schema_for::<CanvasInsertParams>(),+ &["angle", "at", "center", "data", "flip", "name", "offset", "opacity", "path", "plane", "width"],+ );+ assert_keys(+ input_schema_for::<CanvasDecalParams>(),+ &["angle", "at", "center", "data", "face", "flip", "name", "offset", "opacity", "path", "width"],+ );+ assert_keys(input_schema_for::<CanvasEditParams>(), &["angle", "canvas", "center", "flip", "name", "opacity", "visible", "width"]);+ assert_keys(input_schema_for::<CanvasCalibrateParams>(), &["a", "b", "canvas", "distance"]);+ assert_keys(input_schema_for::<CanvasDeleteParams>(), &["canvas"]);+}++/// Strict gives the handlers' messages for the calls they refuse for a key (a missing `canvas`,+/// `face` or `distance` included: the handler's words, not "is required").+#[test]+fn strict_keeps_todays_errors() {+ assert_strict_keeps_todays_errors(&[+ ("canvas.edit", json!({})),+ ("canvas.insert", json!({})),+ ("canvas.insert", json!({"path": " "})),+ ("canvas.decal", json!({"face": [1, 2, 3]})),+ ("canvas.edit", json!({"canvas": true})),+ ("canvas.edit", json!({"canvas": null})),+ ("canvas.delete", json!({})),+ ("canvas.delete", json!({"canvas": ["Canvas1"]})),+ ("canvas.calibrate", json!({})),+ ("canvas.calibrate", json!({"canvas": {}})),+ ("canvas.decal", json!({"data": png()})),+ ("canvas.decal", json!({"data": png(), "face": null})),+ ("canvas.decal", json!({"data": png(), "face": [1, 2]})),+ ("canvas.decal", json!({"data": png(), "face": "top"})),+ ("canvas.decal", json!({"data": png(), "face": {"face": [1, 2, 3], "body": "Box1"}})),+ ("canvas.decal", json!({"data": png(), "face": {"face": [1, 2, 3], "fixed": 1}})),+ ("canvas.decal", json!({"data": png(), "face": {"face": [1, 2, 3], "body": "Box1", "index": -1}})),+ ("canvas.decal", json!({"data": png(), "face": {"face": [1, 2, 3], "path": [0]}})),+ ("canvas.insert", json!({"data": png(), "plane": null})),+ ("canvas.insert", json!({"data": png(), "plane": true})),+ ("canvas.insert", json!({"data": png(), "plane": [1, 0, 0]})),+ ("canvas.insert", json!({"data": png(), "plane": -1})),+ ("canvas.insert", json!({"data": png(), "plane": 1.5})),+ ("canvas.insert", json!({"data": png(), "plane": {"x_dir": [1, 0, 0]}})),+ ("canvas.insert", json!({"data": png(), "plane": {"x_dir": [1, 0, 0], "y_dir": [0, 1]}})),+ ("canvas.insert", json!({"data": png(), "plane": {"x_dir": [1, 0, 0], "y_dir": [2, 0, 0]}})),+ ("canvas.insert", json!({"data": png(), "plane": {"origin": ["w", 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})),+ ("canvas.insert", json!({"data": png(), "plane": {"face": [1, 2]}})),+ ("canvas.insert", json!({"data": png(), "width": 0})),+ ("canvas.insert", json!({"data": png(), "width": -5})),+ ("canvas.insert", json!({"data": png(), "width": 1e7})),+ ]);+}++/// The same refusals for calls that need a canvas in the design (a missing one is refused first+/// with the check off).+#[test]+fn strict_keeps_todays_errors_with_a_canvas() {+ let cases = |c: u64| {+ [+ ("canvas.edit", json!({"canvas": c, "width": 0})),+ ("canvas.edit", json!({"canvas": "Canvas1", "width": -1})),+ ("canvas.calibrate", json!({"canvas": c, "b": [1, 0], "distance": 5})),+ ("canvas.calibrate", json!({"canvas": c, "a": [0, 0], "b": [1], "distance": 5})),+ ("canvas.calibrate", json!({"canvas": c, "a": null, "b": [1, 0], "distance": 5})),+ ("canvas.calibrate", json!({"canvas": c, "a": [0, 0], "b": [1, 0]})),+ ("canvas.calibrate", json!({"canvas": c, "a": [0, 0], "b": [1, 0], "distance": 0})),+ ("canvas.calibrate", json!({"canvas": c, "a": [0, 0], "b": [1, 0], "distance": "5"})),+ ("canvas.calibrate", json!({"canvas": c, "a": [0, 0], "b": [1, 0], "distance": -2})),+ ]+ };+ for index in 0..9 {+ let error = |level: ParamCheck| {+ let mut s = Session { param_check: level, ..Session::default() };+ let c = s.execute("canvas.insert", &json!({"data": png()})).unwrap()["canvas"].as_u64().unwrap();+ let (id, p) = cases(c).into_iter().nth(index).unwrap();+ s.execute(id, &p).err().map(|e| e.to_string())+ };+ let (id, p) = cases(1).into_iter().nth(index).unwrap();+ let off = error(ParamCheck::Off);+ assert!(off.is_some(), "{id} {p} should fail today");+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");+ }+}++/// What the contracts take and refuse in the schemas as well as the types: the image needs+/// `path` or `data`, a decal needs `face`, the plane forms and the calibration's keys.+#[test]+fn the_schemas_take_what_the_handlers_read() {+ let check = |schema: schemars::Schema, cases: &[(Value, bool)]| {+ let schema = schema.as_value().clone();+ for (p, takes) in cases {+ assert_eq!(conforms(&schema, &schema, p), *takes, "{p}");+ }+ };+ check(+ input_schema_for::<CanvasInsertParams>(),+ &[+ (json!({"data": "abc"}), true),+ (json!({"path": "a.png", "plane": "XZ", "width": 80, "center": [1, 2], "at": [1, 2, 3], "offset": "w / 2"}), true),+ (json!({"data": "abc", "plane": {"origin": [0, 0, 5], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}}), true),+ (json!({"data": "abc", "plane": {"face": [1, 2, 3], "body": "Box1", "index": 4}}), true),+ (json!({"data": "abc", "plane": 7}), true),+ (json!({"width": 80}), false),+ (json!({"data": "abc", "width": 0}), false),+ (json!({"data": "abc", "plane": {"origin": [0, 0, 0]}}), false),+ (json!({"data": "abc", "plane": {"origin": null, "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}}), true),+ (json!({"data": "abc", "plane": {"normal": [0, 0, 1]}}), false),+ (json!({"data": "abc", "opacity": "half"}), false),+ (json!({"data": "abc", "colour": 1}), false),+ ],+ );+ check(+ input_schema_for::<CanvasDecalParams>(),+ &[+ (json!({"data": "abc", "face": [1, 2, 3]}), true),+ (json!({"path": "a.png", "face": {"face": [1, 2, 3], "fixed": true}}), true),+ (json!({"data": "abc"}), false),+ (json!({"face": [1, 2, 3]}), false),+ (json!({"data": "abc", "face": "top"}), false),+ (json!({"data": "abc", "face": [1, 2, 3], "plane": "XY"}), false),+ ],+ );+ check(+ input_schema_for::<CanvasCalibrateParams>(),+ &[+ (json!({"canvas": "Canvas1", "a": [0, 0], "b": {"x": 20, "y": 0}, "distance": 50}), true),+ (json!({"canvas": 1, "a": [0, 0], "b": [20, 0]}), false),+ (json!({"a": [0, 0], "b": [20, 0], "distance": 50}), false),+ (json!({"canvas": 1, "a": [0, 0], "b": [20, 0], "distance": 0}), false),+ ],+ );+ check(input_schema_for::<CanvasEditParams>(), &[(json!({"canvas": 2, "visible": false}), true), (json!({"visible": false}), false)]);+ check(input_schema_for::<CanvasDeleteParams>(), &[(json!({"canvas": "Canvas1"}), true), (json!({}), false)]);+}++/// The plane and face types accept what the handlers read and refuse what they refuse.+#[test]+fn the_plane_and_face_types_read_like_the_handlers() {+ let plane = |v: Value| serde_json::from_value::<CanvasPlane>(v).is_ok();+ assert!(plane(json!("XZ")) && plane(json!("Sketch Plane 1")) && plane(json!(3)));+ assert!(plane(json!({"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]})));+ assert!(plane(json!({"origin": null, "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]})));+ assert!(plane(json!({"face": [1, 2, 3], "body": "Box1", "index": 0, "path": [2]})));+ assert!(!plane(json!(null)) && !plane(json!(true)) && !plane(json!(-1)) && !plane(json!([0, 0, 1])));+ assert!(!plane(json!({"normal": [0, 0, 1]})) && !plane(json!({"face": [1, 2]})));+ let face = |v: Value| serde_json::from_value::<DecalFace>(v).is_ok();+ assert!(face(json!([1, 2, 3])) && face(json!({"x": 1, "y": 2, "z": 3})) && face(json!({"face": [1, 2, 3]})));+ assert!(!face(json!(null)) && !face(json!([1, 2])) && !face(json!({"face": [1, 2, 3], "body": "Box1"})));+}++/// Every form of every canvas command replies as its output schema says, in Warn without+/// warnings; a misspelt key still gets its warning and the reply still matches, and strict refuses+/// it.+#[test]+fn replies_match_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ s.execute("solid.box", &json!({"length": 30, "width": 30, "height": 10})).unwrap();+ let run = |s: &mut Session, id: &str, p: Value| {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");+ r+ };+ fn matches(schema: schemars::Schema, r: &Value) {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");+ }+ let forms = [+ json!({"data": png()}),+ json!({"data": png(), "plane": "XZ", "width": 80, "name": "Plan", "angle": 15, "opacity": 0.2, "flip": true}),+ json!({"data": png(), "plane": {"origin": [0, 0, 5], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "center": [3, 4]}),+ json!({"data": png(), "plane": {"face": [15, 15, 10]}, "at": [5, 5, 10]}),+ json!({"data": png(), "plane": "XY", "offset": 12}),+ ];+ for p in forms {+ let r = run(&mut s, "canvas.insert", p);+ matches(output_schema_for::<CanvasPlaced>(), &r);+ assert_eq!(r["pixels"], json!([400, 200]), "{r}");+ }+ assert_eq!(s.doc.canvases[1].name, "Plan");+ assert_eq!(s.execute("canvas.insert", &json!({"data": png()})).unwrap()["name"], "Canvas5");+ for p in [+ json!({"data": png(), "face": [15, 15, 10], "width": 20}),+ json!({"data": png(), "face": {"face": [15, 15, 10], "fixed": true}, "name": "Logo", "opacity": 0.8, "flip": true, "angle": 90, "center": [1, 1]}),+ json!({"data": png(), "face": {"x": 10, "y": 10, "z": 10}, "at": [12, 12, 10], "offset": 0}),+ ] {+ let r = run(&mut s, "canvas.decal", p);+ matches(output_schema_for::<CanvasPlaced>(), &r);+ }+ let first = s.doc.canvases[0].id;+ for p in [+ json!({"canvas": first, "center": [5, 5], "width": 60, "angle": 10, "opacity": 0.9, "flip": false, "visible": false, "name": "Renamed"}),+ json!({"canvas": "Renamed", "visible": true}),+ json!({"canvas": "Renamed"}),+ ] {+ let r = run(&mut s, "canvas.edit", p);+ matches(output_schema_for::<CanvasEdited>(), &r);+ assert_eq!(r["canvas"], json!(first), "{r}");+ }+ let r = run(&mut s, "canvas.calibrate", json!({"canvas": "Renamed", "a": [0, 0], "b": {"x": 20, "y": 0}, "distance": 50}));+ matches(output_schema_for::<CanvasCalibrated>(), &r);+ assert!((r["width"].as_f64().unwrap_or_default() - 150.0).abs() < 1e-9, "{r}");+ let r = run(&mut s, "canvas.delete", json!({"canvas": first}));+ matches(output_schema_for::<CanvasDeleted>(), &r);+ assert_eq!(r, json!({"deleted": first}));+ let second = s.doc.canvases[0].id;+ let r = run(&mut s, "canvas.edit", json!({"canvas": second, "opacity": 7, "name": ""}));+ assert_eq!(r, json!({"canvas": second}));+ assert_eq!((s.doc.canvases[0].opacity, s.doc.canvases[0].name.as_str()), (1.0, "Plan"));+ let r = run(&mut s, "canvas.insert", json!({"data": png(), "name": ""}));+ assert_eq!(r["name"], "");+ assert_eq!(r.as_object().map(|o| o.keys().cloned().collect::<Vec<_>>()), Some(vec!["canvas".into(), "name".into(), "pixels".into()]));+ let r = run(&mut s, "canvas.calibrate", json!({"canvas": second, "a": [0, 0], "b": [1, 0], "distance": 2}));+ assert_eq!(r.as_object().map(|o| o.len()), Some(2), "{r}");+ // A misspelt key runs in warn and says so; the reply still matches. Strict refuses it.+ let p = json!({"canvas": "Canvas2", "widht": 5});+ let r = s.execute("canvas.edit", &p).unwrap();+ assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()), "{r}");+ matches(output_schema_for::<CanvasEdited>(), &r);+ s.param_check = ParamCheck::Strict;+ let error = s.execute("canvas.edit", &p).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(error.contains("`widht`"), "{error}");+}diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex 4624f9fcb1..609ffcfe8f 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -57,6 +57,7 @@ mod tests;pub mod appearance;pub mod bom;pub mod browser;+pub mod canvas;pub mod clearance;pub mod compare;pub mod component;diff --git a/crates/engine/src/schema/motion.rs b/crates/engine/src/schema/motion.rsindex d4ab868a56..88924c15cf 100644--- a/crates/engine/src/schema/motion.rs+++ b/crates/engine/src/schema/motion.rs@@ -278,7 +278,7 @@ fn contact_set_schema(_: &mut SchemaGenerator) -> Schema {/// Adds `key` to the schema's `required` list: for a key the type has optional so that the/// handler, not the check, refuses it when it's left out.-fn require(schema: &mut Schema, key: &str) {+pub(super) fn require(schema: &mut Schema, key: &str) {match schema.get_mut("required") {Some(Value::Array(required)) => {if !required.iter().any(|k| k == key) {diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 2756b7866e..bfe59f6096 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -2,11 +2,6 @@# (coverage_tests.rs). This list only shrinks: when you give a command its contract and output# type, remove its line. Never add one: a new command comes with both schemas. Sorted, one id# per line.-canvas.calibrate-canvas.decal-canvas.delete-canvas.edit-canvas.insertcomponent.activatecomponent.capture_positioncomponent.create