From e3bbd8258a2ccc28aaca3dd3efbd440fb6634fee Mon Sep 17 00:00:00 2001 From: austin62jake Date: Mon, 2 Nov 2026 18:39:20 +0000 Subject: [PATCH] Typed schemas for Loose Ends and Tie Loose Ends (#10959) (#10960) * claim: #10959 Co-Authored-By: Claude Opus 5.5 * Loose Ends and Tie Loose Ends: input and output schemas (#10959) sketch.loose_ends and sketch.loose_ends.tie get typed contracts and reply types in schema/sketch_ends.rs and leave unconverted.txt. SketchTarget reads `sketch` as sketch_store::target does and PointIds reads `points` as the tie does, each with the handler's messages. The replies are built from the types, with the same JSON as before. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude --- crates/engine/src/cmd/sketch_ends.rs | 74 +++++--- crates/engine/src/schema/mod.rs | 1 + crates/engine/src/schema/sketch_ends.rs | 161 ++++++++++++++++++ crates/engine/src/schema/sketch_ends_tests.rs | 91 ++++++++++ crates/engine/src/schema/unconverted.txt | 2 - 5 files changed, 301 insertions(+), 28 deletions(-) create mode 100644 crates/engine/src/schema/sketch_ends.rs create mode 100644 crates/engine/src/schema/sketch_ends_tests.rs diff --git a/crates/engine/src/cmd/sketch_ends.rs b/crates/engine/src/cmd/sketch_ends.rs index 2f41d6fba..18e1dc2c5 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 = TypedContract::new(); +const TIE_CONTRACT: TypedContract = 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::) + .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::) + .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 { + 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 { + 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 { 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 = r.open.iter().map(|&p| json!({"point": point_id(sk, p), "curve": end_curve(sk, p), "at": at(sk, p)})).collect(); - let untied: Vec = 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 { + serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string())) } fn loose_ends_cmd(s: &mut Session, p: &Value) -> Result { 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 { @@ -86,11 +108,11 @@ fn tie_cmd(s: &mut Session, p: &Value) -> Result { }; 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.rs index c2a13cb88..b7a3d78e5 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.rs new file mode 100644 index 000000000..668098e77 --- /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: D) -> Result { + 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); + +impl<'de> Deserialize<'de> for PointIds { + fn deserialize>(d: D) -> Result { + 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::>>().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, +} + +/// 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, + /// 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, +} + +/// 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, + /// Ends that touch another curve only by position: the profile closes now, but nothing keeps + /// it closed when a dimension changes. + pub untied: Vec, + /// 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, +} + +/// An end that touches nothing. +#[derive(Debug, Serialize, JsonSchema)] +pub struct OpenEnd { + /// The end's point id. + pub point: Option, + /// The profile curve it ends. + pub curve: Option, + /// 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, + /// The curve it ends. + pub curve: Option, + /// 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), + /// A curve, by id. + Curve(Option), +} + +/// 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, + /// The sketch's solve: `{solved, dof}`. + pub sketch: Value, + /// The untied ends left. + pub untied: Vec, + /// 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, +} + +#[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.rs new file mode 100644 index 000000000..2eafcd74a --- /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::(), &["sketch"]); + assert_keys(input_schema_for::(), &["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::(), output_schema_for::()); + 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::>()); + 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.txt index deb201935..16c146efc 100644 --- a/crates/engine/src/schema/unconverted.txt +++ b/crates/engine/src/schema/unconverted.txt @@ -290,8 +290,6 @@ sketch.isoparametric_curve sketch.line sketch.line.midpoint sketch.line3d -sketch.loose_ends -sketch.loose_ends.tie sketch.mirror sketch.move sketch.move3d