SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Typed schemas for Loose Ends and Tie Loose Ends (#10959) (#10960)
austin62jakee3bbd8258a2c
diff --git a/crates/engine/src/cmd/sketch_ends.rs b/crates/engine/src/cmd/sketch_ends.rsindex 2f41d6fbae..18e1dc2c57 100644--- a/crates/engine/src/cmd/sketch_ends.rs+++ b/crates/engine/src/cmd/sketch_ends.rs@@ -1,63 +1,85 @@//! Loose ends of a sketch's profile curves: the ones that touch nothing (open) and the ones that//! touch another curve only by position (untied), and tying the untied ones.-use serde_json::{Value, json};+use serde_json::Value;use solidcraft_sketch::{ConstraintKind, EndReport, EndTouch, Sketch, loose_ends};use super::sketch::{add_c, edit};use super::sketch_store;use super::{CommandSpec, in_sketch};use crate::params::{bad, string_list};+use crate::schema::sketch_ends::{LooseEnds, LooseEndsParams, OpenEnd, TieLooseEndsParams, TiedLooseEnds, Touches, UntiedEnd};+use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session};+const LOOSE_ENDS_CONTRACT: TypedContract<LooseEndsParams> = TypedContract::new();+const TIE_CONTRACT: TypedContract<TieLooseEndsParams> = TypedContract::new();+pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("sketch.loose_ends", "Loose Ends", loose_ends_cmd).icon("c_coincident").enabled(in_sketch).noundo().params(+ CommandSpec::new("sketch.loose_ends", "Loose Ends", crate::checked!("sketch.loose_ends", loose_ends_cmd))+ .icon("c_coincident")+ .enabled(in_sketch)+ .noundo()+ .contract(&LOOSE_ENDS_CONTRACT)+ .output(output_schema_for::<LooseEnds>)+ .params("sketch?: id|name (default active): the ends of profile curves (not construction, projected or text) that can make a profile fail. open: [{point, curve, at}] ends that touch no other profile curve (no profile runs through them); untied: [{point, curve, at, touches: {point}|{curve}}] ends that touch another curve only by position (the profile closes now, but nothing keeps it closed when a dimension changes)",- ),- CommandSpec::new("sketch.loose_ends.tie", "Tie Loose Ends", tie_cmd).icon("c_coincident").enabled(in_sketch).params(+ ),+ CommandSpec::new("sketch.loose_ends.tie", "Tie Loose Ends", crate::checked!("sketch.loose_ends.tie", tie_cmd))+ .icon("c_coincident")+ .enabled(in_sketch)+ .contract(&TIE_CONTRACT)+ .output(output_schema_for::<TiedLooseEnds>)+ .params("sketch?: id|name (default active); points?: [point ids] (default: every untied end): ties each untied end to what it touches, coincident with another curve's end or on another curve. Returns constraints: [ids added], and the untied ends left",- ),+ ),];-fn point_id(sk: &Sketch, i: usize) -> Value {- sk.points.get(i).map_or(Value::Null, |p| json!(p.id))+fn point_id(sk: &Sketch, i: usize) -> Option<String> {+ sk.points.get(i).map(|p| p.id.clone())}-fn curve_id(sk: &Sketch, i: usize) -> Value {- sk.curves.get(i).map_or(Value::Null, |c| json!(c.id))+fn curve_id(sk: &Sketch, i: usize) -> Option<String> {+ sk.curves.get(i).map(|c| c.id.clone())}-fn at(sk: &Sketch, i: usize) -> Value {- sk.point(i).map_or(Value::Null, |v| json!([v.x, v.y]))+fn at(sk: &Sketch, i: usize) -> Option<[f64; 2]> {+ sk.point(i).map(|v| [v.x, v.y])}/// The point that is an end of curve `c` (for `curve` in the report).-fn end_curve(sk: &Sketch, p: usize) -> Value {+fn end_curve(sk: &Sketch, p: usize) -> Option<String> {let c = sk.curves.iter().position(|c| c.kind.ends().is_some_and(|(a, b)| a == p || b == p) && !(c.construction || c.centerline || c.infinite));- c.map_or(Value::Null, |c| curve_id(sk, c))+ c.and_then(|c| curve_id(sk, c))}-fn report_json(sk: &Sketch, r: &EndReport) -> Value {- let open: Vec<Value> = r.open.iter().map(|&p| json!({"point": point_id(sk, p), "curve": end_curve(sk, p), "at": at(sk, p)})).collect();- let untied: Vec<Value> = r+fn ends_report(sk: &Sketch, r: &EndReport) -> LooseEnds {+ let open = r.open.iter().map(|&p| OpenEnd { point: point_id(sk, p), curve: end_curve(sk, p), at: at(sk, p) }).collect();+ let untied = r.untied.iter()- .map(|u| {- let touches = match u.touches {- EndTouch::Point(q) => json!({"point": point_id(sk, q)}),- EndTouch::Curve(c) => json!({"curve": curve_id(sk, c)}),- };- json!({"point": point_id(sk, u.point), "curve": curve_id(sk, u.curve), "at": at(sk, u.point), "touches": touches})+ .map(|u| UntiedEnd {+ point: point_id(sk, u.point),+ curve: curve_id(sk, u.curve),+ at: at(sk, u.point),+ touches: match u.touches {+ EndTouch::Point(q) => Touches::Point(point_id(sk, q)),+ EndTouch::Curve(c) => Touches::Curve(curve_id(sk, c)),+ },}).collect();- json!({"open": open, "untied": untied})+ LooseEnds { open, untied, param_warnings: Vec::new() }+}++fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))}fn loose_ends_cmd(s: &mut Session, p: &Value) -> Result<Value> {let id = sketch_store::target(s, p, "sketch.loose_ends")?;let st = s.model.state();let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch has not been evaluated".into()))?;- Ok(report_json(&ss.sketch, &ss.ends))+ reply("sketch.loose_ends", ends_report(&ss.sketch, &ss.ends))}fn tie_cmd(s: &mut Session, p: &Value) -> Result<Value> {@@ -86,11 +108,11 @@ fn tie_cmd(s: &mut Session, p: &Value) -> Result<Value> {};added.push(add_c(sk, kind)?);}- let left = report_json(sk, &loose_ends(sk)).get("untied").cloned().unwrap_or(Value::Null);+ let left = ends_report(sk, &loose_ends(sk)).untied;Ok((added, left))})?;let (added, left) = added;- Ok(json!({"constraints": added, "sketch": info, "untied": left}))+ reply(cmd, TiedLooseEnds { constraints: added, sketch: info, untied: left, param_warnings: Vec::new() })}#[cfg(test)]diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex c2a13cb88a..b7a3d78e5e 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -73,6 +73,7 @@ pub mod sheet;pub mod sketch;pub mod sketch_constraints;pub mod sketch_create;+pub mod sketch_ends;pub mod sketch_equation;pub mod surface_analysis;pub mod ui_prefs;diff --git a/crates/engine/src/schema/sketch_ends.rs b/crates/engine/src/schema/sketch_ends.rsnew file mode 100644index 0000000000..668098e777--- /dev/null+++ b/crates/engine/src/schema/sketch_ends.rs@@ -0,0 +1,161 @@+//! Contracts and result types for the commands in `cmd/sketch_ends.rs`: a sketch's loose ends,+//! and tying them (#10959).++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::check::whole;++/// The most names `params::string_list` takes, which the tie command reads its points with.+const MAX_POINTS: usize = 10_000;++/// A sketch, as `sketch_store::target` reads one: its feature id or its name, with its message.+/// Whether a sketch has that id or name is the handler's to check.+#[derive(Clone, Debug, PartialEq)]+pub struct SketchTarget(pub String);++impl<'de> Deserialize<'de> for SketchTarget {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::Number(n) if n.is_u64() => Ok(SketchTarget(n.to_string())),+ Value::String(s) => Ok(SketchTarget(s)),+ _ => Err(D::Error::custom("must be an id or a name")),+ }+ }+}++impl JsonSchema for SketchTarget {+ fn schema_name() -> Cow<'static, str> {+ "SketchTarget".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "The sketch: its feature id or its name (default: the one being edited).",+ "anyOf": [{"type": "integer", "minimum": 0}, {"type": "string"}]+ })+ }+}++/// Point ids, as the tie command reads them: a list of ids (a single id isn't taken), at most+/// 10 000, with its messages.+#[derive(Clone, Debug, PartialEq)]+pub struct PointIds(pub Vec<String>);++impl<'de> Deserialize<'de> for PointIds {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let fail = || D::Error::custom("must be a list of point ids");+ let Value::Array(a) = Value::deserialize(d)? else {+ return Err(fail());+ };+ let ids = a.into_iter().map(|v| if let Value::String(s) = v { Some(s) } else { None }).collect::<Option<Vec<_>>>().ok_or_else(fail)?;+ if ids.len() > MAX_POINTS {+ return Err(D::Error::custom(whole(format!("`points` must list at most {} names", MAX_POINTS))));+ }+ Ok(PointIds(ids))+ }+}++impl JsonSchema for PointIds {+ fn schema_name() -> Cow<'static, str> {+ "PointIds".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "Point ids, such as `p3`.",+ "type": "array",+ "items": {"type": "string"},+ "maxItems": MAX_POINTS+ })+ }+}++/// The ends of a sketch's profile curves (not construction, projected or text curves) that can+/// make a profile fail.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct LooseEndsParams {+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// Tie each untied end to what it touches: coincident with another curve's end, or on another+/// curve. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct TieLooseEndsParams {+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+ /// The untied ends to tie, by point id (default: every untied end). An id that isn't an+ /// untied end is left as it is.+ #[serde(default)]+ pub points: Option<PointIds>,+}++/// What `sketch.loose_ends` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct LooseEnds {+ /// Ends that touch no other profile curve: no profile runs through them.+ pub open: Vec<OpenEnd>,+ /// Ends that touch another curve only by position: the profile closes now, but nothing keeps+ /// it closed when a dimension changes.+ pub untied: Vec<UntiedEnd>,+ /// 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>,+}++/// An end that touches nothing.+#[derive(Debug, Serialize, JsonSchema)]+pub struct OpenEnd {+ /// The end's point id.+ pub point: Option<String>,+ /// The profile curve it ends.+ pub curve: Option<String>,+ /// Where it is, in sketch coordinates.+ pub at: Option<[f64; 2]>,+}++/// An end that touches another curve only by position.+#[derive(Debug, Serialize, JsonSchema)]+pub struct UntiedEnd {+ /// The end's point id.+ pub point: Option<String>,+ /// The curve it ends.+ pub curve: Option<String>,+ /// Where it is, in sketch coordinates.+ pub at: Option<[f64; 2]>,+ /// What it touches: another curve's end, or a curve.+ pub touches: Touches,+}++/// What an untied end touches.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum Touches {+ /// Another curve's end, by point id.+ Point(Option<String>),+ /// A curve, by id.+ Curve(Option<String>),+}++/// What `sketch.loose_ends.tie` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct TiedLooseEnds {+ /// The ids of the constraints added, one per end tied.+ pub constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// The untied ends left.+ pub untied: Vec<UntiedEnd>,+ /// 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 = "sketch_ends_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/sketch_ends_tests.rs b/crates/engine/src/schema/sketch_ends_tests.rsnew file mode 100644index 0000000000..2eafcd74a7--- /dev/null+++ b/crates/engine/src/schema/sketch_ends_tests.rs@@ -0,0 +1,91 @@+use serde_json::{Value, json};++use super::{LooseEnds, LooseEndsParams, TieLooseEndsParams, TiedLooseEnds};+use crate::Session;+use crate::schema::tests::{assert_keys, conforms};+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};++fn run(s: &mut Session, id: &str, p: Value) -> Value {+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))+}++/// A sketch being edited, as these commands need: a square of four separate lines, closed by+/// position only, so its four corners are untied.+fn loose_square(s: &mut Session) {+ run(s, "sketch.create", json!({"plane": "XY", "name": "Square"}));+ let c = [[0, 0], [10, 0], [10, 10], [0, 10]];+ for i in 0..4 {+ run(s, "sketch.line", json!({"points": [c[i], c[(i + 1) % 4]], "infer": false, "connect": false}));+ }+}++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<LooseEndsParams>(), &["sketch"]);+ assert_keys(input_schema_for::<TieLooseEndsParams>(), &["points", "sketch"]);+}++/// A call that fails today gets the same message in strict. These commands run only while a+/// sketch is being edited, so each call runs in one (`assert_strict_keeps_todays_errors` runs+/// after a finished sketch).+#[test]+fn strict_keeps_todays_errors() {+ let many = vec!["p1"; 10_001];+ for (id, p) in [+ ("sketch.loose_ends", json!({"sketch": true})),+ ("sketch.loose_ends", json!({"sketch": -1})),+ ("sketch.loose_ends", json!({"sketch": 1.5})),+ ("sketch.loose_ends", json!({"sketch": "Nope"})),+ ("sketch.loose_ends.tie", json!({"sketch": {}})),+ ("sketch.loose_ends.tie", json!({"points": "p1"})),+ ("sketch.loose_ends.tie", json!({"points": [1]})),+ ("sketch.loose_ends.tie", json!({"points": ["nope"]})),+ ("sketch.loose_ends.tie", json!({"points": many})),+ ] {+ let error = |level: ParamCheck| {+ let mut s = Session { param_check: level, ..Session::default() };+ loose_square(&mut s);+ s.execute(id, &p).err().map(|e| e.to_string())+ };+ let off = error(ParamCheck::Off);+ assert!(off.is_some(), "{id} {p} should fail today");+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");+ }+}++/// #10959: the report and the tie reply as their output schemas say, in Warn without warnings+/// for good calls and with them for a misspelt key, with open ends, untied ends touching a+/// point and a curve, and ties of some ends and then the rest.+#[test]+fn loose_end_commands_reply_with_their_schemas() {+ let (report, tied) = (output_schema_for::<LooseEnds>(), output_schema_for::<TiedLooseEnds>());+ let matches = |schema: &schemars::Schema, r: &Value, warned: bool| {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");+ assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");+ };+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ loose_square(&mut s);+ // A line from the middle of the top side: one end touches a curve, the other nothing.+ run(&mut s, "sketch.line", json!({"points": [[5, 10], [5, 20]], "infer": false, "connect": false}));+ let r = run(&mut s, "sketch.loose_ends", json!({}));+ matches(&report, &r, false);+ let untied = r["untied"].as_array().cloned().unwrap_or_default();+ assert_eq!(r["open"].as_array().map(Vec::len), Some(1), "{r}");+ assert!(untied.iter().any(|u| u["touches"]["point"].is_string()) && untied.iter().any(|u| u["touches"]["curve"].is_string()), "{r}");+ for u in &untied {+ let touches = u["touches"].as_object().map(|t| t.keys().cloned().collect::<Vec<_>>());+ assert!(matches!(touches.as_deref(), Some([k]) if k == "point" || k == "curve"), "{u}");+ }+ matches(&report, &run(&mut s, "sketch.loose_ends", json!({"sketch": "Square"})), false);+ matches(&report, &run(&mut s, "sketch.loose_ends", json!({"skech": "Square"})), true);++ let first = untied.first().map(|u| u["point"].clone()).unwrap_or_default();+ let r = run(&mut s, "sketch.loose_ends.tie", json!({"points": [first]}));+ matches(&tied, &r, false);+ assert_eq!(r["constraints"].as_array().map(Vec::len), Some(1), "{r}");+ let r = run(&mut s, "sketch.loose_ends.tie", json!({"point": []}));+ matches(&tied, &r, true);+ assert_eq!(r["untied"], json!([]), "every end is tied: {r}");+ matches(&tied, &run(&mut s, "sketch.loose_ends.tie", json!({"sketch": "Square", "points": null})), false);+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex deb2019356..16c146efcc 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -290,8 +290,6 @@ sketch.isoparametric_curvesketch.linesketch.line.midpointsketch.line3d-sketch.loose_ends-sketch.loose_ends.tiesketch.mirrorsketch.movesketch.move3d