Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Typed schemas for Change Design Units (part of #2829) (#10934)

semmelrindebcac191847ec
diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs
index 96389deb5f..6f3d097501 100644
--- a/crates/engine/src/cmd/browser.rs
+++ b/crates/engine/src/cmd/browser.rs
@@ -16,11 +16,12 @@ use solidcraft_doc::{BrowserEntry, FeatureKind, MAX_GROUP_NESTING};
use super::CommandSpec;
use super::features::{add_feature, check_expr};
use crate::params::{bad, bool_, expr, str_};
-use crate::schema::browser::{RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn};
+use crate::schema::browser::{DocumentUnitsParams, DocumentUnitsResult, RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
const REPAIR_CONTRACT: TypedContract<RepairParams> = TypedContract::new();
+const UNITS_CONTRACT: TypedContract<DocumentUnitsParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("body.rename", "Rename Body", rename_body).icon("rename").params("body: its name, name: the new name (features that use the body follow)"),
@@ -42,8 +43,10 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("browser.rename_group", "Rename Group", rename_group).icon("rename").params("group: id, name"),
CommandSpec::new("browser.move", "Move Browser Items", move_items).icon("reorder")
.params("folder, component?, items: [keys (strings) and group ids (numbers)]; group?: id (into it; omit for the folder's top level); before?: key or group id (position in it; default the end). A group cannot go into itself or past 8 levels"),
- CommandSpec::new("document.units", "Change Design Units", document_units)
+ CommandSpec::new("document.units", "Change Design Units", crate::checked!("document.units", document_units))
.icon("settings")
+ .contract(&UNITS_CONTRACT)
+ .output(crate::schema::output_schema_for::<DocumentUnitsResult>)
.params("units: mm|cm|m|in|ft (display and unit-less parameters; values keep their meaning)"),
CommandSpec::new("view.save", "New Named View", view_save)
.icon("camera")
@@ -844,8 +847,11 @@ fn document_units(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`units` must be mm, cm, m, in or ft"));
}
let old = s.doc.units.clone();
+ let reply = |kept: Vec<String>| {
+ serde_json::to_value(DocumentUnitsResult { units: u.to_string(), kept, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
+ };
if old == u {
- return Ok(json!({ "units": u, "kept": [] }));
+ return reply(Vec::new());
}
// What the geometry reads: every feature's length inputs.
let matched_configuration = s.doc.configuration_matches().then(|| s.doc.configs.active.clone()).flatten();
@@ -886,7 +892,7 @@ fn document_units(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut().apply_configuration(&row)?;
}
s.settle_value_edit(&solved)?;
- Ok(json!({ "units": u, "kept": kept }))
+ reply(kept)
}
fn view_save(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/schema/browser.rs b/crates/engine/src/schema/browser.rs
index 03e0d1a961..9b76efcffa 100644
--- a/crates/engine/src/schema/browser.rs
+++ b/crates/engine/src/schema/browser.rs
@@ -1,7 +1,10 @@
//! Contracts and result types for the commands in `cmd/browser.rs`.
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
+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;
use super::types::{FeatureCommon, LengthExpr, feature_common};
@@ -112,6 +115,55 @@ pub struct RepairResult {
pub param_warnings: Vec<String>,
}
+/// The units a design can show lengths in.
+pub const DESIGN_UNITS: [&str; 5] = ["mm", "cm", "m", "in", "ft"];
+
+/// One of [`DESIGN_UNITS`], with `document.units`' message for anything else.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DesignUnits(pub String);
+
+impl<'de> Deserialize<'de> for DesignUnits {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(u) if DESIGN_UNITS.contains(&u.as_str()) => Ok(DesignUnits(u)),
+ _ => Err(D::Error::custom("must be mm, cm, m, in or ft")),
+ }
+ }
+}
+
+impl JsonSchema for DesignUnits {
+ fn schema_name() -> Cow<'static, str> {
+ "DesignUnits".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "The units the design shows lengths in.", "type": "string", "enum": DESIGN_UNITS})
+ }
+}
+
+/// Change the units the design shows lengths in, and reads a bare number in. Values keep their
+/// meaning: a unit-less parameter holding a bare number that lengths read is written with the
+/// old unit (`10` becomes `10 mm`) when that keeps those lengths where they were. One undo
+/// step; the same units again changes nothing.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct DocumentUnitsParams {
+ /// The design's new units: mm, cm, m, in or ft.
+ pub units: DesignUnits,
+}
+
+/// What `document.units` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DocumentUnitsResult {
+ /// The design's units now.
+ pub units: String,
+ /// The unit-less parameters now written with the old unit, so the lengths that read them
+ /// stay where they were. Empty when nothing needed it, or the units didn't change.
+ pub kept: Vec<String>,
+ /// 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 = "browser_tests.rs"]
mod tests;
diff --git a/crates/engine/src/schema/browser_tests.rs b/crates/engine/src/schema/browser_tests.rs
index 677355417a..07ba23de77 100644
--- a/crates/engine/src/schema/browser_tests.rs
+++ b/crates/engine/src/schema/browser_tests.rs
@@ -1,8 +1,8 @@
use serde_json::{Value, json};
-use super::{RepairParams, RepairResult};
+use super::{DocumentUnitsParams, DocumentUnitsResult, RepairParams, RepairResult};
use crate::Session;
-use crate::schema::tests::{assert_keys, conforms};
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
#[test]
@@ -26,3 +26,43 @@ fn replies_match_the_output_schema() {
let r = s.execute("body.repair", &json!({"body": "Box", "colour": "red"}));
assert!(r.is_err(), "nothing left to repair");
}
+
+#[test]
+fn units_schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<DocumentUnitsParams>(), &["units"]);
+}
+
+#[test]
+fn units_strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[("document.units", json!({})), ("document.units", json!({"units": "furlong"}))]);
+}
+
+/// A change that keeps a parameter's value with the old unit, one that keeps none, and the same
+/// units again, in Warn: each reply matches the output schema and carries no warning.
+#[test]
+fn units_replies_match_the_output_schema() {
+ let schema = output_schema_for::<DocumentUnitsResult>();
+ let schema = schema.as_value();
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let mut run = |p: Value| s.execute("document.units", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ let mut check = |p: Value| {
+ let reply = run(p.clone());
+ assert!(reply.get("param_warnings").is_none() && conforms(schema, schema, &reply), "{p}: {reply} doesn't match {schema}");
+ reply
+ };
+ check(json!({"units": "cm"}));
+ assert_eq!(check(json!({"units": "cm"}))["kept"], json!([]));
+ check(json!({"units": "in"}));
+}
+
+/// A unit-less parameter a length reads is kept with the old unit, and the reply names it.
+#[test]
+fn the_reply_names_the_parameters_kept_in_the_old_unit() {
+ let mut s = Session::default();
+ s.execute("parameters.add", &json!({"name": "w", "expression": "10", "unit": ""})).unwrap_or_else(|e| panic!("{e}"));
+ s.execute("solid.box", &json!({"length": "w", "width": 10, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
+ let reply = s.execute("document.units", &json!({"units": "in"})).unwrap_or_else(|e| panic!("{e}"));
+ let schema = output_schema_for::<DocumentUnitsResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}");
+ assert_eq!(reply["kept"], json!(["w"]), "{reply}");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 0d2ceb3497..c2cfd8758d 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -58,7 +58,6 @@ document.inspect
document.metadata
document.metadata.remove
document.metadata.set
-document.units
engine.commands
explode.create
explode.delete