SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: the geometric sketch constraints describe their exact parameters and reply (#12549) (#12603)
PeppaWutz046eba5ba30e
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex ba5a808c0c..8aff0e12f9 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -8,7 +8,11 @@ use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, Pointuse super::{CommandSpec, in_sketch};use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec3};-use crate::schema::sketch::{CancelResult, EditParams, EditResult, ExitParams, FinishResult};+use crate::schema::sketch::{+ CancelResult, CoincidentMade, CoincidentParams, CoincidentResult, CollinearParams, ConcentricParams, Constrained, ConstraintResult, EditParams,+ EditResult, EqualMade, EqualParams, EqualResult, ExitParams, FinishResult, FixOutcome, FixParams, FixResult, HorizontalVerticalParams,+ MidpointParams, ParallelParams, PerpendicularParams, SymmetryParams, SymmetryResult, TangentParams,+};use crate::schema::{TypedContract, output_schema_for};use crate::{EngineError, Result, Session, SketchEntry, Snapshot};@@ -38,6 +42,17 @@ macro_rules! model_operand_doc {const EDIT_CONTRACT: TypedContract<EditParams> = TypedContract::new();const EXIT_CONTRACT: TypedContract<ExitParams> = TypedContract::new();+const HORIZONTAL_VERTICAL_CONTRACT: TypedContract<HorizontalVerticalParams> = TypedContract::new();+const COINCIDENT_CONTRACT: TypedContract<CoincidentParams> = TypedContract::new();+const TANGENT_CONTRACT: TypedContract<TangentParams> = TypedContract::new();+const EQUAL_CONTRACT: TypedContract<EqualParams> = TypedContract::new();+const PARALLEL_CONTRACT: TypedContract<ParallelParams> = TypedContract::new();+const PERPENDICULAR_CONTRACT: TypedContract<PerpendicularParams> = TypedContract::new();+const FIX_CONTRACT: TypedContract<FixParams> = TypedContract::new();+const MIDPOINT_CONTRACT: TypedContract<MidpointParams> = TypedContract::new();+const CONCENTRIC_CONTRACT: TypedContract<ConcentricParams> = TypedContract::new();+const COLLINEAR_CONTRACT: TypedContract<CollinearParams> = TypedContract::new();+const SYMMETRY_CONTRACT: TypedContract<SymmetryParams> = TypedContract::new();pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sketch.create", "Create Sketch", create_sketch)@@ -143,60 +158,82 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("sketch.dimension", "Sketch Dimension", dimension).at("SKETCH", "CREATE").icon("dimension").key("D").enabled(in_sketch).params("entities: [refs] (a line midpoint is \"mid:line_id\"; a model edge or vertex, {edge: [x,y,z], body?} or {vertex: [x,y,z], body?}, is projected into the sketch first and measured there: a point against the projected edge measures the distance to it), type?: auto|distance|horizontal|distance_x|vertical|distance_y|length|radius|diameter|major|minor|angle, value?: number or expression (default: current; a bare number is in the design's units, e.g. 2 means 2 in in an inch design; give a unit such as \"50 mm\" to override), or `name = expression` (e.g. \"width = 40\"; also `#name = expression`), which adds the user parameter `name` with that expression and dimensions with `name` (refused when the name is taken or reserved; the reply's `defined` names it); text_at?: [x, y]. Two points or a line off the axes: with auto, text_at across from them (between the perpendiculars through them, or a tenth of their distance past) is the distance between them; pulled further past an end, up or down from it horizontal, sideways vertical. Two midpoints: placing text above or below their bounding box measures horizontally, beside it vertically, anywhere else (inside it or past its corners) the distance between them. Two lines: the angle between them (acute, or 180° − it when the value is nearer that) unless text_at picks a sector. A line and a circle or arc: the distance from the line to its edge (the gap, or how far the edge reaches past a line that cuts it; 0 is tangent); dimension the centre point for the distance to the centre. A point and a circle or arc: the distance from the point to its edge (or how far within it a point inside lies). Two circles or arcs: the gap between their edges (or how far they overlap when they cross, or the narrowest gap between them when one lies inside the other), or the centre-to-centre distance when they are the two caps of a slot. An ellipse: a half-axis, the distance from the centre to an axis end (major or minor; with auto, text_at pulled across the major axis gives the major half-axis, pulled out past an end of it the minor one, the minor without text_at; previous_axis?: major|minor, the half-axis an earlier placement chose, kept while text_at is near the boundary between them; the reply's axis names the one chosen; with auto, when a driving dimension already holds one half-axis (or its whole axis), the other one, wherever text_at is; without its major axis line the major half-axis goes to the ellipse's own major end, without its minor axis line the minor half-axis is the minor radius); any other type, radius among them, the minor radius; an ellipse's axis line with auto: its length, the whole axis, wherever text_at is; half_axes?: bool (default true; false: with auto, the minor radius wherever text_at is, as before half-axes, which the Dimension tool sends with Draw ellipses with their axes off). An arc and one of its end points: the arc's length (type arc_length does it from the arc alone). A dimension the sketch already determines is refused (naming what determines it); if_redundant?: \"driven\" places it as a driven (reference) dimension instead. scale_sketch?: bool (the dimension tool sends the Sketch preference, on by default): when this is the sketch's first length dimension and nothing in the sketch fixes a size (no other driving length dimension, nothing fixed or projected), the whole sketch scales about its origin to the value instead of distorting. Returns measured in unit (mm or deg), and scaled: the factor when the sketch was scaled",),- CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", c_horizontal_vertical)+ CommandSpec::new("sketch.constraint.horizontal_vertical", "Horizontal/Vertical", crate::checked!("sketch.constraint.horizontal_vertical", c_horizontal_vertical)).at("SKETCH", "CONSTRAINTS").icon("c_hv").enabled(in_sketch)+ .contract(&HORIZONTAL_VERTICAL_CONTRACT)+ .output(output_schema_for::<ConstraintResult>).params("line: id | points: [a, b] (point ids or {midpoint: line_id}; accepted midpoints reuse or create a point with a Midpoint constraint); mode?: horizontal|vertical"),- CommandSpec::new("sketch.constraint.coincident", "Coincident", c_coincident)+ CommandSpec::new("sketch.constraint.coincident", "Coincident", crate::checked!("sketch.constraint.coincident", c_coincident)).at("SKETCH", "CONSTRAINTS").icon("c_coincident").enabled(in_sketch)+ .contract(&COINCIDENT_CONTRACT)+ .output(output_schema_for::<CoincidentResult>).params(concat!("a, b: points (or a line's middle as {midpoint: line}, which becomes a point tied there), a point and a curve or sketch axis (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created), or two distinct lines (joins their closest endpoints), or two circles/arcs (the second lies on the first: concentric and equal, `constraints` lists both)", model_operand_doc!())),- CommandSpec::new("sketch.constraint.tangent", "Tangent", c_tangent)+ CommandSpec::new("sketch.constraint.tangent", "Tangent", crate::checked!("sketch.constraint.tangent", c_tangent)).at("SKETCH", "CONSTRAINTS").icon("c_tangent").enabled(in_sketch)+ .contract(&TANGENT_CONTRACT)+ .output(output_schema_for::<ConstraintResult>).params(concat!("a, b: curves or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),- CommandSpec::new("sketch.constraint.equal", "Equal", c_equal)+ CommandSpec::new("sketch.constraint.equal", "Equal", crate::checked!("sketch.constraint.equal", c_equal)).at("SKETCH", "CONSTRAINTS").icon("c_equal").enabled(in_sketch)+ .contract(&EQUAL_CONTRACT)+ .output(output_schema_for::<EqualResult>).params(concat!("a, b: lines or circles/arcs; or curves: [2 to 200 lines or circles/arcs], each made equal to the first, in one step", model_operand_doc!())),- CommandSpec::new("sketch.constraint.parallel", "Parallel", c_parallel)+ CommandSpec::new("sketch.constraint.parallel", "Parallel", crate::checked!("sketch.constraint.parallel", c_parallel)).at("SKETCH", "CONSTRAINTS").icon("c_parallel").enabled(in_sketch)+ .contract(&PARALLEL_CONTRACT)+ .output(output_schema_for::<ConstraintResult>).params(concat!("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),- CommandSpec::new("sketch.constraint.perpendicular", "Perpendicular", c_perpendicular)+ CommandSpec::new("sketch.constraint.perpendicular", "Perpendicular", crate::checked!("sketch.constraint.perpendicular", c_perpendicular)).at("SKETCH", "CONSTRAINTS").icon("c_perpendicular").enabled(in_sketch)+ .contract(&PERPENDICULAR_CONTRACT)+ .output(output_schema_for::<ConstraintResult>).params(concat!("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),- CommandSpec::new("sketch.constraint.fix", "Fix/Unfix", c_fix)+ CommandSpec::new("sketch.constraint.fix", "Fix/Unfix", crate::checked!("sketch.constraint.fix", c_fix)).at("SKETCH", "CONSTRAINTS").icon("c_fix").enabled(in_sketch)+ .contract(&FIX_CONTRACT)+ .output(output_schema_for::<FixResult>).params("entity: point or curve | entities: [points and curves]; fixed?: bool (default: fix them all unless all are fixed, then unfix)"),- CommandSpec::new("sketch.constraint.midpoint", "MidPoint", c_midpoint)+ CommandSpec::new("sketch.constraint.midpoint", "MidPoint", crate::checked!("sketch.constraint.midpoint", c_midpoint)).at("SKETCH", "CONSTRAINTS").icon("c_midpoint").enabled(in_sketch)+ .contract(&MIDPOINT_CONTRACT)+ .output(output_schema_for::<ConstraintResult>).params(concat!("point, line | a, b in pick order: a point and a line (either way round), or two lines whose midpoints meet (the first stays, the second moves)", model_operand_doc!())),- CommandSpec::new("sketch.constraint.concentric", "Concentric", c_concentric)+ CommandSpec::new("sketch.constraint.concentric", "Concentric", crate::checked!("sketch.constraint.concentric", c_concentric)).at("SKETCH", "CONSTRAINTS").icon("c_concentric").enabled(in_sketch)+ .contract(&CONCENTRIC_CONTRACT)+ .output(output_schema_for::<ConstraintResult>).params(concat!("a, b: two circles/arcs, or a circle/arc and a sketch point (including origin), in either order; the point and the curve's centre become coincident", model_operand_doc!())),- CommandSpec::new("sketch.constraint.collinear", "Collinear", c_collinear)+ CommandSpec::new("sketch.constraint.collinear", "Collinear", crate::checked!("sketch.constraint.collinear", c_collinear)).at("SKETCH", "CONSTRAINTS").icon("c_collinear").enabled(in_sketch)+ .contract(&COLLINEAR_CONTRACT)+ .output(output_schema_for::<ConstraintResult>).params(concat!("a, b: lines or sketch axes (x / y: the sketch's own axes, unless a curve has that id; an axis becomes a linked construction line on it, reported in created)", model_operand_doc!())),- CommandSpec::new("sketch.constraint.symmetry", "Symmetry", c_symmetry)+ CommandSpec::new("sketch.constraint.symmetry", "Symmetry", crate::checked!("sketch.constraint.symmetry", c_symmetry)).at("SKETCH", "CONSTRAINTS").icon("c_symmetry").enabled(in_sketch)+ .contract(&SYMMETRY_CONTRACT)+ .output(output_schema_for::<SymmetryResult>).params(concat!("a, b: two points or two curves (lines mirror their ends, circles/arcs their centres); line: symmetry line id, or x / y for the sketch's own axes (a curve with that id wins; an axis becomes a linked construction line on it, reported in created); or point (or a point id as line, \"origin\" too): symmetric about that point, each pair joined by a construction line it is the midpoint of", model_operand_doc!())),CommandSpec::new("sketch.construction", "Normal/Construction", construction).at("SKETCH", "CREATE")@@ -1947,7 +1984,27 @@ fn draw_point(s: &mut Session, p: &Value) -> Result<Value> {// ---------------------------------------------------------------------------------------------// Constraints-fn constrain(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Sketch) -> Result<ConstraintKind>) -> Result<Value> {+/// A command's reply as JSON: they build their replies from the types their output schemas+/// describe, so the two can't drift apart.+fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))+}++/// [`constrain`], replying as the commands that add one constraint do.+fn constrain_reply(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Sketch) -> Result<ConstraintKind>) -> Result<Value> {+ let made = constrain(s, p, cmd, f)?;+ reply(cmd, ConstraintResult { made, param_warnings: Vec::new() })+}++/// The constraint a command added and, when the sketch already determined it, what determines it+/// (see [`constraint_result`], which the other constraint commands build their reply with).+fn constrained(p: &Value, cmd: &str, id: String, info: Value, by: Option<Vec<String>>) -> Result<Constrained> {+ let Some(by) = by else { return Ok(Constrained { constraint: id, sketch: info, redundant: None, determined_by: None }) };+ keep_redundant(p, cmd, &by)?;+ Ok(Constrained { constraint: id, sketch: info, redundant: Some(true), determined_by: Some(by) })+}++fn constrain(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Sketch) -> Result<ConstraintKind>) -> Result<Constrained> {let mut before = None;let mut residual = None;let (id, info) = edit(s, p, cmd, true, |sk, _| {@@ -1966,7 +2023,7 @@ fn constrain(s: &mut Session, p: &Value, cmd: &str, f: impl FnOnce(&mut Sketch)Ok(id)})?;let by = redundancy(s, p, cmd, before, &info, residual, &id)?;- constraint_result(p, cmd, id, info, by, Value::Null)+ constrained(p, cmd, id, info, by)}/// A sketch entity a constraint is applied to.@@ -2310,7 +2367,7 @@ impl AlignmentTarget {fn c_horizontal_vertical(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.constraint.horizontal_vertical";let mode = str_(p, "mode").map(str::to_ascii_lowercase);- constrain(s, p, cmd, |sk| {+ constrain_reply(s, p, cmd, |sk| {if let Some(pts) = p.get("points").and_then(Value::as_array) {if pts.len() != 2 {return Err(bad(cmd, "`points` needs exactly two point references"));@@ -2375,7 +2432,8 @@ fn c_coincident(s: &mut Session, p: &Value) -> Result<Value> {&& let Some(c) = sk.constraints.iter().find(|c| matches!(c.kind, ConstraintKind::Coincident { p, q } if (p, q) == (a, b) || (p, q) == (b, a))){let rep = solve(&mut sk.clone());- return Ok(json!({"constraint": c.id, "existing": true, "sketch": report_json(&rep)}));+ let made = CoincidentMade::Existing { constraint: c.id.clone(), existing: true, sketch: report_json(&rep) };+ return reply(cmd, CoincidentResult { made, param_warnings: Vec::new() });}let pick = |sk: &mut Sketch| -> Result<ConstraintKind> {if let Some((a, b)) = line_points {@@ -2418,7 +2476,7 @@ fn c_coincident(s: &mut Session, p: &Value) -> Result<Value> {let c = curve_or_axis(sk, bref)?.ok_or_else(|| bad(cmd, format!("unknown entity `{bref}`")))?;Ok(ConstraintKind::PointOnCurve { p: a, c })};- constrain(s, p, cmd, |sk| {+ let made = constrain(s, p, cmd, |sk| {let k = pick(sk)?;// A line's two ends on each other shrink it to a point, as a line's own end at its// middle does (see `c_midpoint`).@@ -2428,7 +2486,8 @@ fn c_coincident(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, "a line's two ends can't be coincident: the line would shrink to a point"));}Ok(k)- })+ })?;+ reply(cmd, CoincidentResult { made: CoincidentMade::Added(made), param_warnings: Vec::new() })}/// `a` and `b` both circles or arcs (two different ones).@@ -2463,7 +2522,8 @@ fn coincident_circles(s: &mut Session, p: &Value, cmd: &str, a: usize, b: usize)apply_in_order(sk, &rep, &[Ent::Curve(a)], Ent::Curve(b), cmd, &ids)?;Ok(ids)})?;- Ok(json!({"constraint": ids[0], "constraints": ids, "sketch": info}))+ let constraint = ids.first().cloned().unwrap_or_default();+ reply(cmd, CoincidentResult { made: CoincidentMade::Circles { constraint, constraints: ids, sketch: info }, param_warnings: Vec::new() })}/// Four endpoint pairs, ordered independently of pick order when distances tie.@@ -2519,7 +2579,7 @@ fn two_curves_or_axes(sk: &mut Sketch, p: &Value, cmd: &str) -> Result<(usize, ufn c_tangent(s: &mut Session, p: &Value) -> Result<Value> {let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.tangent", &["a", "b"])?;- constrain(s, p, "sketch.constraint.tangent", |sk| {+ constrain_reply(s, p, "sketch.constraint.tangent", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.tangent").and_then(|ab| two_different("sketch.constraint.tangent", ab)).map(|(a, b)| ConstraintKind::Tangent { a, b })@@ -2530,11 +2590,9 @@ fn c_equal(s: &mut Session, p: &Value) -> Result<Value> {return equal_curves(s, p);}let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.equal", &["a", "b"])?;- constrain(s, p, "sketch.constraint.equal", |sk| {- two_curves(sk, p, "sketch.constraint.equal")- .and_then(|ab| two_different("sketch.constraint.equal", ab))- .map(|(a, b)| ConstraintKind::Equal { a, b })- })+ let cmd = "sketch.constraint.equal";+ let made = constrain(s, p, cmd, |sk| two_curves(sk, p, cmd).and_then(|ab| two_different(cmd, ab)).map(|(a, b)| ConstraintKind::Equal { a, b }))?;+ reply(cmd, EqualResult { made: EqualMade::Pair(made), param_warnings: Vec::new() })}/// Equal over a list of curves (#4985): each one is made equal to the first, in one edit (one@@ -2566,11 +2624,11 @@ fn equal_curves(s: &mut Session, p: &Value) -> Result<Value> {}Ok(out)})?;- Ok(json!({"constraints": out, "sketch": info}))+ reply(cmd, EqualResult { made: EqualMade::Curves { constraints: out, sketch: info }, param_warnings: Vec::new() })}fn c_parallel(s: &mut Session, p: &Value) -> Result<Value> {let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.parallel", &["a", "b"])?;- constrain(s, p, "sketch.constraint.parallel", |sk| {+ constrain_reply(s, p, "sketch.constraint.parallel", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.parallel").and_then(|ab| two_different("sketch.constraint.parallel", ab)).map(|(a, b)| ConstraintKind::Parallel { a, b })@@ -2578,7 +2636,7 @@ fn c_parallel(s: &mut Session, p: &Value) -> Result<Value> {}fn c_perpendicular(s: &mut Session, p: &Value) -> Result<Value> {let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.perpendicular", &["a", "b"])?;- constrain(s, p, "sketch.constraint.perpendicular", |sk| {+ constrain_reply(s, p, "sketch.constraint.perpendicular", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.perpendicular").and_then(|ab| two_different("sketch.constraint.perpendicular", ab)).map(|(a, b)| ConstraintKind::Perpendicular { a, b })@@ -2587,7 +2645,7 @@ fn c_perpendicular(s: &mut Session, p: &Value) -> Result<Value> {fn c_concentric(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "sketch.constraint.concentric";let p = &super::sketch_project::project_operands(s, p, cmd, &["a", "b"])?;- constrain(s, p, cmd, |sk| {+ constrain_reply(s, p, cmd, |sk| {let centre = |key: &str| {let curve = sk.curves.get(sk.curve_index(p.get(key)?.as_str()?)?)?;match curve.kind {@@ -2604,7 +2662,7 @@ fn c_concentric(s: &mut Session, p: &Value) -> Result<Value> {}fn c_collinear(s: &mut Session, p: &Value) -> Result<Value> {let p = &super::sketch_project::project_operands(s, p, "sketch.constraint.collinear", &["a", "b"])?;- constrain(s, p, "sketch.constraint.collinear", |sk| {+ constrain_reply(s, p, "sketch.constraint.collinear", |sk| {two_curves_or_axes(sk, p, "sketch.constraint.collinear").and_then(|ab| two_different("sketch.constraint.collinear", ab)).map(|(a, b)| ConstraintKind::Collinear { a, b })@@ -2648,7 +2706,7 @@ fn c_midpoint(s: &mut Session, p: &Value) -> Result<Value> {_ => Err(bad(cmd, "MidPoint needs a point and a line, or two lines")),}};- constrain(s, p, cmd, |sk| {+ constrain_reply(s, p, cmd, |sk| {let k = pick(sk)?;// A line's own end at its middle shrinks the line to a point; an angle, tangent or// parallel on it afterwards had no direction to hold and threw points millions of@@ -2764,7 +2822,7 @@ fn c_symmetry(s: &mut Session, p: &Value) -> Result<Value> {}Ok(out)})?;- Ok(json!({"constraints": ids, "sketch": info}))+ reply(cmd, SymmetryResult { constraints: ids, sketch: info, param_warnings: Vec::new() })}/// True when the ends of line `a` mirror (about the line `l`) closer onto the ends of `b` crossed@@ -2890,9 +2948,9 @@ fn c_fix(s: &mut Session, p: &Value) -> Result<Value> {sk.constraints.retain(|k| !matches!(k.kind, ConstraintKind::Fix { p } if ids.contains(&p)));}}- Ok(json!({"fixed": fix, "changed": n}))+ Ok(FixOutcome { fixed: fix, changed: n })})?;- Ok(json!({"result": n, "sketch": info}))+ reply(cmd, FixResult { result: n, sketch: info, param_warnings: Vec::new() })}// ---------------------------------------------------------------------------------------------diff --git a/crates/engine/src/schema/sketch.rs b/crates/engine/src/schema/sketch.rsindex c9e8df34c9..05973808da 100644--- a/crates/engine/src/schema/sketch.rs+++ b/crates/engine/src/schema/sketch.rs@@ -1,9 +1,26 @@//! Contracts and result types for sketch editing and completion in `cmd/sketch.rs`.+//!+//! The geometric constraints (`sketch.constraint.coincident`, `collinear`, `concentric`, `equal`,+//! `fix`, `horizontal_vertical`, `midpoint`, `parallel`, `perpendicular`, `symmetry` and+//! `tangent`, #12549) read their parameters from the raw JSON, in the forms and cases their+//! handlers do, so a key is read here only where its handler reads it (`line` of a Horizontal /+//! Vertical call that gives `points`, `a` and `b` of an Equal call that gives `curves`, `line` of+//! a Symmetry call that gives `point`, and so on): a call that works today gets no warning. Each+//! one is therefore read by hand, in the handler's order, and fails with the handler's message.+//! A key the handler refuses when it is left out is optional in the type and required in the+//! schema. Whether a curve or point exists, whether a model edge can be projected and whether+//! the constraint can be solved stay the handler's to check.-use schemars::JsonSchema;-use serde::{Deserialize, Serialize};+use std::borrow::Cow;-use super::types::{IdOrName, present};+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};+use serde::de::Error as _;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::{Map, Value, json};++use super::check::whole;+use super::motion::require;+use super::types::{IdOrName, Point3, present};#[derive(Debug, Deserialize, JsonSchema)]#[schemars(deny_unknown_fields)]@@ -49,3 +66,780 @@ pub struct CancelResult {#[serde(default, skip_serializing_if = "Vec::is_empty")]pub param_warnings: Vec<String>,}++// ---------------------------------------------------------------------------------------------+// The geometric constraints++type Fields = Map<String, Value>;+type Read<T> = Result<T, String>;++/// The handler's message, whole (the check puts no key in front of it).+fn refuse<T>(message: impl std::fmt::Display) -> Read<T> {+ Err(whole(message))+}++/// The sketch a command works in, as `sketch_store::target` reads `sketch`: a feature id (a whole+/// number) or a name. `null` is read as left out.+#[derive(Clone, Debug, PartialEq)]+pub enum SketchKey {+ Id(u64),+ Name(String),+}++impl JsonSchema for SketchKey {+ fn schema_name() -> Cow<'static, str> {+ "SketchKey".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A sketch's feature id (a whole number, 0 or more) or its name.",+ "anyOf": [{"type": "integer", "minimum": 0}, {"type": "string"}]+ })+ }+}++fn sketch_of(m: &Fields) -> Read<Option<SketchKey>> {+ match m.get("sketch") {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(name)) => Ok(Some(SketchKey::Name(name.clone()))),+ Some(Value::Number(n)) => match n.as_u64() {+ Some(id) => Ok(Some(SketchKey::Id(id))),+ None => refuse("`sketch` must be an id or a name"),+ },+ Some(_) => refuse("`sketch` must be an id or a name"),+ }+}++/// An optional text, as `str_` reads it (`null` is left out); anything else is refused, where+/// the handler would read it as left out.+fn text_of(m: &Fields, key: &str) -> Read<Option<String>> {+ match m.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::String(s)) => Ok(Some(s.clone())),+ Some(_) => refuse(format!("`{key}` must be text")),+ }+}++/// An optional flag, as `bool_` reads it (`null` is left out); anything else is refused, where+/// the handler would read it as left out.+fn flag_of(m: &Fields, key: &str) -> Read<Option<bool>> {+ match m.get(key) {+ None | Some(Value::Null) => Ok(None),+ Some(Value::Bool(b)) => Ok(Some(*b)),+ Some(_) => refuse(format!("`{key}` must be true or false")),+ }+}++/// `if_redundant`: `refuse` (in any case) turns a redundant constraint away instead of keeping+/// it; any other text keeps it.+fn if_redundant_of(m: &Fields) -> Read<Option<String>> {+ text_of(m, "if_redundant")+}++/// A model edge `{edge: [x, y, z], body?}` or vertex `{vertex: [x, y, z], body?}`, which+/// `project_operands` projects into the sketch before the handler reads its operands.+fn model_pick(v: &Value) -> bool {+ v.get("edge").is_some() || v.get("vertex").is_some()+}++fn model_pick_schema(generator: &mut SchemaGenerator) -> Value {+ let point = generator.subschema_for::<Point3>();+ json!({+ "type": "object",+ "properties": {"edge": point, "vertex": point, "body": {"type": "string"}},+ "anyOf": [{"required": ["edge"]}, {"required": ["vertex"]}]+ })+}++/// A sketch entity a constraint is applied to: its id, or a model edge or vertex, which is+/// projected into the sketch first (the projected curve or point is then the operand, and is+/// reported in `created`). Whether the id names something and whether the model geometry can+/// be projected is the handler's to check.+#[derive(Clone, Debug, PartialEq)]+pub enum Operand {+ Id(String),+ Model(Value),+}++impl JsonSchema for Operand {+ fn schema_name() -> Cow<'static, str> {+ "SketchOperand".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let model = model_pick_schema(generator);+ json_schema!({+ "description": "A sketch point or curve by its id, or a model edge {\"edge\": [x, y, z], \"body\"?} or vertex {\"vertex\": [x, y, z], \"body\"?}, projected into the sketch first.",+ "anyOf": [{"type": "string"}, model]+ })+ }+}++/// `key` as an operand; anything else is refused with `message`, the handler's. Left out is+/// the handler's to refuse.+fn operand_of(m: &Fields, key: &str, message: &str) -> Read<Option<Operand>> {+ match m.get(key) {+ None => Ok(None),+ Some(Value::String(id)) => Ok(Some(Operand::Id(id.clone()))),+ Some(v) if model_pick(v) => Ok(Some(Operand::Model(v.clone()))),+ Some(_) => refuse(message),+ }+}++/// A line's middle, as a point of a constraint: `{midpoint: line_id}`.+fn midpoint_schema() -> Value {+ json!({+ "type": "object",+ "properties": {"midpoint": {"type": "string"}},+ "required": ["midpoint"]+ })+}++/// A point of `sketch.constraint.coincident`: an id, a model edge or vertex, or a line's middle+/// as `{midpoint: line_id}`, which becomes a point tied there.+#[derive(Clone, Debug, PartialEq)]+pub enum PointOperand {+ Id(String),+ Model(Value),+ Midpoint(String),+}++impl JsonSchema for PointOperand {+ fn schema_name() -> Cow<'static, str> {+ "CoincidentOperand".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let model = model_pick_schema(generator);+ json_schema!({+ "description": "A sketch point, curve or axis by its id, a model edge or vertex (projected into the sketch first), or a line's middle {\"midpoint\": line_id}.",+ "anyOf": [{"type": "string"}, model, midpoint_schema()]+ })+ }+}++/// Why a Coincident operand was refused: its `midpoint` is not a curve id, or it has no form.+enum Wrong {+ Midpoint,+ Form,+}++fn point_operand(v: Option<&Value>) -> Result<Option<PointOperand>, Wrong> {+ match v {+ None => Ok(None),+ Some(Value::String(id)) => Ok(Some(PointOperand::Id(id.clone()))),+ Some(v) if model_pick(v) => Ok(Some(PointOperand::Model(v.clone()))),+ Some(v) => match v.get("midpoint") {+ Some(Value::String(line)) => Ok(Some(PointOperand::Midpoint(line.clone()))),+ Some(_) => Err(Wrong::Midpoint),+ None => Err(Wrong::Form),+ },+ }+}++/// One of the two points of `sketch.constraint.horizontal_vertical`'s `points`: a point id or a+/// line's middle as `{midpoint: line_id}`.+#[derive(Clone, Debug, PartialEq)]+pub enum AlignPoint {+ Id(String),+ Midpoint(String),+}++impl JsonSchema for AlignPoint {+ fn schema_name() -> Cow<'static, str> {+ "AlignPoint".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A sketch point by its id, or a line's middle {\"midpoint\": line_id} (it reuses the point a Midpoint constraint ties there, or makes one).",+ "anyOf": [{"type": "string"}, midpoint_schema()]+ })+ }+}++fn align_point(v: &Value) -> Read<AlignPoint> {+ match v.get("midpoint") {+ Some(Value::String(line)) => Ok(AlignPoint::Midpoint(line.clone())),+ Some(_) => refuse("`midpoint` must be a curve id"),+ None => match v {+ Value::String(id) => Ok(AlignPoint::Id(id.clone())),+ _ => refuse("`points` must be a point reference"),+ },+ }+}++/// Names, as `params::string_list` reads them: one name or a list of names, `null` for none,+/// with its messages.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Names(pub Vec<String>);++impl JsonSchema for Names {+ fn schema_name() -> Cow<'static, str> {+ "SketchNames".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "An id, or a list of ids.",+ "anyOf": [+ {"type": "string"},+ {"type": "array", "items": {"type": "string"}, "maxItems": crate::params::MAX_STRING_LIST}+ ]+ })+ }+}++/// `key` as the handler's `string_list` reads it, with its message for anything else.+fn names_of(m: &Fields, key: &str) -> Read<Option<Names>> {+ if m.get(key).is_none_or(Value::is_null) {+ return Ok(None);+ }+ let one: Fields = m.iter().filter(|(k, _)| *k == key).map(|(k, v)| (k.clone(), v.clone())).collect();+ match crate::params::string_list("", &Value::Object(one), key) {+ Ok(names) => Ok(Some(Names(names))),+ Err(crate::EngineError::BadParams { msg, .. }) => refuse(msg),+ Err(e) => refuse(e),+ }+}++/// The fields of a call.+fn fields<'de, D: Deserializer<'de>>(d: D) -> Result<Fields, D::Error> {+ Fields::deserialize(d)+}++/// Adds a key the type has optional so that the handler refuses it when it is left out, as+/// `require`, for every one of `keys`.+fn require_all(schema: &mut Schema, keys: &[&str]) {+ for key in keys {+ require(schema, key);+ }+}++/// Requires one of two sets of keys, for the commands that take two forms.+fn require_either(schema: &mut Schema, first: &[&str], second: &[&str]) {+ schema.insert("anyOf".into(), json!([{"required": first}, {"required": second}]));+}++fn a_and_b_required(schema: &mut Schema) {+ require_all(schema, &["a", "b"]);+}++/// What a command that adds one constraint returns: the constraint, the sketch's solve and, when+/// the sketch already determined the constraint, what determines it.+#[derive(Debug, Serialize, JsonSchema)]+pub struct Constrained {+ /// The new constraint's id.+ pub constraint: String,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// `true` when other constraints already determined it: it is kept, shown as redundant (not+ /// when `if_redundant` is `refuse`, which refuses the call instead). Absent otherwise.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub redundant: Option<bool>,+ /// With `redundant`: the constraints that determine it, as "id (Name)".+ #[serde(skip_serializing_if = "Option::is_none")]+ pub determined_by: Option<Vec<String>>,+}++/// What `sketch.constraint.horizontal_vertical`, `tangent`, `parallel`, `perpendicular`,+/// `collinear`, `concentric` and `midpoint` return.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ConstraintResult {+ #[serde(flatten)]+ pub made: Constrained,+ /// 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 `sketch.constraint.coincident` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct CoincidentResult {+ #[serde(flatten)]+ pub made: CoincidentMade,+ /// 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 a Coincident call did.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum CoincidentMade {+ /// A coincident (or point-on-curve) constraint was added.+ Added(Constrained),+ /// The two points (or two lines' closest ends) were already coincident: nothing was added.+ Existing {+ /// The constraint that already joins them.+ constraint: String,+ /// Always `true`.+ existing: bool,+ /// The sketch's solve: `{solved, dof}`.+ sketch: Value,+ },+ /// Two circles or arcs: the second now lies on the first (a Concentric and an Equal+ /// constraint; one of them is left out when it was already there).+ Circles {+ /// The first constraint added.+ constraint: String,+ /// Every constraint added.+ constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ sketch: Value,+ },+}++/// What `sketch.constraint.equal` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct EqualResult {+ #[serde(flatten)]+ pub made: EqualMade,+ /// 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 an Equal call added.+#[derive(Debug, Serialize, JsonSchema)]+#[serde(untagged)]+pub enum EqualMade {+ /// `a` and `b`: one Equal constraint.+ Pair(Constrained),+ /// `curves`: an Equal constraint from the first curve to each other one (a pair that was+ /// already equal is left out).+ Curves {+ /// The constraints added.+ constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ sketch: Value,+ },+}++/// What `sketch.constraint.symmetry` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct SymmetryResult {+ /// The constraints added: one Symmetric for two points, two for two lines, a Symmetric and an+ /// Equal for two circles or arcs; about a point, one Midpoint constraint for each pair, on+ /// a new construction line (reported in `created`).+ pub constraints: Vec<String>,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// 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 a Fix call did to the entities.+#[derive(Debug, Serialize, JsonSchema)]+pub struct FixOutcome {+ /// Whether they are fixed now (`false`: released).+ pub fixed: bool,+ /// How many points and curves changed; those already as asked, the origin, projected+ /// geometry and a point fixed by its own coordinates are not counted.+ pub changed: usize,+}++/// What `sketch.constraint.fix` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct FixResult {+ /// What the call did.+ pub result: FixOutcome,+ /// The sketch's solve: `{solved, dof}`.+ pub sketch: Value,+ /// 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>,+}++/// A command that takes two operands, `a` and `b`, in one form: the same keys, read with the+/// handler's message for each.+macro_rules! two_operands {+ (+ $(#[$meta:meta])* $name:ident,+ a: $a_doc:literal, b: $b_doc:literal, what: $what:literal+ ) => {+ $(#[$meta])*+ #[derive(Debug, JsonSchema)]+ #[schemars(deny_unknown_fields, transform = a_and_b_required)]+ pub struct $name {+ #[doc = $a_doc]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub a: Option<Operand>,+ #[doc = $b_doc]+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub b: Option<Operand>,+ /// `refuse` (in any case) refuses the call when the sketch already determines the new+ /// constraint, instead of keeping it as a redundant one (any other text keeps it).+ /// Read only when the constraint turns out redundant.+ #[serde(default)]+ pub if_redundant: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchKey>,+ }++ impl<'de> Deserialize<'de> for $name {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = fields(d)?;+ let read = || -> Read<Self> {+ let sketch = sketch_of(&m)?;+ let a = operand_of(&m, "a", &format!("`a` must be {}", $what))?;+ let b = operand_of(&m, "b", &format!("`b` must be {}", $what))?;+ Ok(Self { a, b, if_redundant: if_redundant_of(&m)?, sketch })+ };+ read().map_err(D::Error::custom)+ }+ }+ };+}++two_operands! {+ /// Make two curves, or a curve and a sketch axis, tangent. Two different curves are needed.+ TangentParams,+ a: "A curve's id, or `x` / `y` for the sketch's own axis (a curve with that id wins; an axis becomes a linked construction line, reported in `created`), or a model edge.",+ b: "The other curve, as `a`.",+ what: "a curve id, or x / y for a sketch axis"+}++two_operands! {+ /// Make two lines, or a line and a sketch axis, parallel. Two different lines are needed.+ ParallelParams,+ a: "A line's id, or `x` / `y` for the sketch's own axis (a curve with that id wins; an axis becomes a linked construction line, reported in `created`), or a model edge.",+ b: "The other line, as `a`.",+ what: "a curve id, or x / y for a sketch axis"+}++two_operands! {+ /// Make two lines, or a line and a sketch axis, perpendicular. Two different lines are+ /// needed.+ PerpendicularParams,+ a: "A line's id, or `x` / `y` for the sketch's own axis (a curve with that id wins; an axis becomes a linked construction line, reported in `created`), or a model edge.",+ b: "The other line, as `a`.",+ what: "a curve id, or x / y for a sketch axis"+}++two_operands! {+ /// Make two lines, or a line and a sketch axis, lie on one line. Two different lines are+ /// needed.+ CollinearParams,+ a: "A line's id, or `x` / `y` for the sketch's own axis (a curve with that id wins; an axis becomes a linked construction line, reported in `created`), or a model edge.",+ b: "The other line, as `a`.",+ what: "a curve id, or x / y for a sketch axis"+}++two_operands! {+ /// Give two circles or arcs one centre, or put a circle's or an arc's centre on a sketch point+ /// (the origin too), in either order.+ ConcentricParams,+ a: "A circle's or arc's id, or a sketch point's id, or a model edge or vertex.",+ b: "The other circle or arc, or the sketch point, as `a`.",+ what: "a curve id"+}++/// Make two curves equal (two lines the same length, two circles or arcs the same radius), or+/// each of a list of curves equal to the first, in one undo step.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = equal_required)]+pub struct EqualParams {+ /// A line, circle or arc, or a model edge. Read when `curves` is not given.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub a: Option<Operand>,+ /// The other line, circle or arc, as `a`. Read when `curves` is not given.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub b: Option<Operand>,+ /// 2 to 200 lines, circles or arcs (ids), each made equal to the first. When the key is given+ /// (`null` too), `a` and `b` are ignored, and so is `if_redundant`.+ #[serde(default)]+ pub curves: Option<Names>,+ /// `refuse` (in any case) refuses the call when the sketch already determines the new+ /// constraint, instead of keeping it as a redundant one (any other text keeps it). Read+ /// only with `a` and `b`, and when the constraint turns out redundant.+ #[serde(default)]+ pub if_redundant: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchKey>,+}++fn equal_required(schema: &mut Schema) {+ require_either(schema, &["a", "b"], &["curves"]);+}++impl<'de> Deserialize<'de> for EqualParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = fields(d)?;+ let read = || -> Read<Self> {+ if m.contains_key("curves") {+ let curves = names_of(&m, "curves")?;+ if !(2..=200).contains(&curves.as_ref().map_or(0, |c| c.0.len())) {+ return refuse("`curves` must list 2 to 200 lines or circles/arcs");+ }+ return Ok(Self { a: None, b: None, curves, if_redundant: None, sketch: sketch_of(&m)? });+ }+ let sketch = sketch_of(&m)?;+ let a = operand_of(&m, "a", "`a` must be a curve id")?;+ let b = operand_of(&m, "b", "`b` must be a curve id")?;+ Ok(Self { a, b, curves: None, if_redundant: if_redundant_of(&m)?, sketch })+ };+ read().map_err(D::Error::custom)+ }+}++/// Make two points coincident, put a point on a curve or a sketch axis, join the closest ends of+/// two lines, or put one circle or arc on another (concentric and equal).+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = a_and_b_required)]+pub struct CoincidentParams {+ /// A point, a curve or axis (`x` / `y`: the sketch's own axes, unless a curve has that id; an+ /// axis becomes a linked construction line on it, reported in `created`), a line's middle+ /// `{midpoint: line_id}` or a model edge or vertex.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "PointOperand")]+ pub a: Option<PointOperand>,+ /// The other one, as `a`. Two lines join their closest ends; two circles or arcs make the+ /// second lie on the first.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "PointOperand")]+ pub b: Option<PointOperand>,+ /// `refuse` (in any case) refuses the call when the sketch already determines the new+ /// constraint, instead of keeping it as a redundant one (any other text keeps it). Read+ /// only when a constraint is added for a point and a point, a point and a curve or two+ /// lines, and it turns out redundant.+ #[serde(default)]+ pub if_redundant: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchKey>,+}++impl<'de> Deserialize<'de> for CoincidentParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = fields(d)?;+ let read = || -> Read<Self> {+ let sketch = sketch_of(&m)?;+ let (a, b) = (point_operand(m.get("a")), point_operand(m.get("b")));+ // The handler looks at the middles first, then `b`, then `a`.+ if matches!(a, Err(Wrong::Midpoint)) || matches!(b, Err(Wrong::Midpoint)) {+ return refuse("`midpoint` must be a curve id");+ }+ let b = b.or_else(|_| refuse("`b` must be a point or curve"))?;+ // With no `b` the handler stops at `b` first, whatever `a` is.+ let a = a.or_else(|_| if b.is_none() { refuse("`b` must be a point or curve") } else { refuse("`a` must be a point reference") })?;+ Ok(Self { a, b, if_redundant: if_redundant_of(&m)?, sketch })+ };+ read().map_err(D::Error::custom)+ }+}++/// Make a line horizontal or vertical, or two points level (same height) or plumb (one above the+/// other), by `line` or by `points`.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = horizontal_vertical_required)]+pub struct HorizontalVerticalParams {+ /// A line's id. Read when `points` is not a list; ignored when it is.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "String")]+ pub line: Option<String>,+ /// Exactly two points: ids, or a line's middle as `{midpoint: line_id}`. When it is a list,+ /// `line` is ignored; anything else is ignored, as if the key were left out.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "[AlignPoint; 2]")]+ pub points: Option<[AlignPoint; 2]>,+ /// `horizontal` or `vertical` (in any case). Default, and for any other text: horizontal when+ /// the line or the two points are further apart across than up, else vertical.+ #[serde(default)]+ pub mode: Option<String>,+ /// `refuse` (in any case) refuses the call when the sketch already determines the new+ /// constraint, instead of keeping it as a redundant one (any other text keeps it). Read+ /// only when the constraint turns out redundant.+ #[serde(default)]+ pub if_redundant: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchKey>,+}++fn horizontal_vertical_required(schema: &mut Schema) {+ require_either(schema, &["line"], &["points"]);+}++impl<'de> Deserialize<'de> for HorizontalVerticalParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = fields(d)?;+ let read = || -> Read<Self> {+ let mode = text_of(&m, "mode")?;+ let sketch = sketch_of(&m)?;+ let if_redundant = if_redundant_of(&m)?;+ if let Some(list) = m.get("points").and_then(Value::as_array) {+ let [a, b] = list.as_slice() else { return refuse("`points` needs exactly two point references") };+ let points = Some([align_point(a)?, align_point(b)?]);+ return Ok(Self { line: None, points, mode, if_redundant, sketch });+ }+ let line = match m.get("line") {+ None => None,+ Some(Value::String(id)) => Some(id.clone()),+ Some(_) => return refuse("`line` must be a curve id"),+ };+ Ok(Self { line, points: None, mode, if_redundant, sketch })+ };+ read().map_err(D::Error::custom)+ }+}++/// Tie a point to the middle of a line, or make two lines' middles meet (the first stays, the+/// second moves), by `point` and `line` or by `a` and `b`.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = midpoint_required)]+pub struct MidpointParams {+ /// A point or a line, in pick order (a point and a line either way round, or two lines). When+ /// `a` or `b` is given (`null` too), `point` and `line` are ignored.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub a: Option<Operand>,+ /// The other one, as `a`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub b: Option<Operand>,+ /// The point. Read when neither `a` nor `b` is given.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub point: Option<Operand>,+ /// The line it goes to the middle of. Read when neither `a` nor `b` is given.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub line: Option<Operand>,+ /// `refuse` (in any case) refuses the call when the sketch already determines the new+ /// constraint, instead of keeping it as a redundant one (any other text keeps it). Read+ /// only when the constraint turns out redundant.+ #[serde(default)]+ pub if_redundant: Option<String>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchKey>,+}++fn midpoint_required(schema: &mut Schema) {+ require_either(schema, &["a", "b"], &["point", "line"]);+}++impl<'de> Deserialize<'de> for MidpointParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = fields(d)?;+ let read = || -> Read<Self> {+ let sketch = sketch_of(&m)?;+ let none = Self { a: None, b: None, point: None, line: None, if_redundant: None, sketch };+ if m.contains_key("a") || m.contains_key("b") {+ // A `null` is a value here, which the handler refuses.+ let a = operand_of(&m, "a", "`a` must be a point or line id")?;+ let b = operand_of(&m, "b", "`b` must be a point or line id")?;+ return Ok(Self { a, b, if_redundant: if_redundant_of(&m)?, ..none });+ }+ let point = operand_of(&m, "point", "`point` must be a point reference")?;+ let line = operand_of(&m, "line", "`line` must be a curve id")?;+ Ok(Self { point, line, if_redundant: if_redundant_of(&m)?, ..none })+ };+ read().map_err(D::Error::custom)+ }+}++/// Make two points, two lines or two circles or arcs mirror images about a line or a sketch axis+/// (`line`), or about a point (`point`): each pair then joined by a construction line that the+/// point is the middle of.+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = symmetry_required)]+pub struct SymmetryParams {+ /// The first point or curve (lines mirror their ends, circles and arcs their centres). It+ /// stays; the second moves onto its mirror image.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub a: Option<Operand>,+ /// The second point or curve, as `a`.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub b: Option<Operand>,+ /// The symmetry line's id, or `x` / `y` for the sketch's own axis (a curve with that id wins;+ /// an axis becomes a linked construction line, reported in `created`). A point's id (or+ /// `origin`) instead makes the symmetry about that point. Read when `point` is not given.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub line: Option<Operand>,+ /// The point the symmetry is about. When the key is given (`null` too), `line` is ignored.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ #[schemars(with = "Operand")]+ pub point: Option<Operand>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchKey>,+}++fn symmetry_required(schema: &mut Schema) {+ require_all(schema, &["a", "b"]);+ require_either(schema, &["line"], &["point"]);+}++impl<'de> Deserialize<'de> for SymmetryParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = fields(d)?;+ let read = || -> Read<Self> {+ let sketch = sketch_of(&m)?;+ let (mut point, mut line) = (None, None);+ if m.contains_key("point") {+ // A `null` is a value here, which the handler refuses.+ point = operand_of(&m, "point", "`point` must be a point reference")?;+ } else {+ line = operand_of(&m, "line", "`line` must be a curve id, or x / y for a sketch axis")?;+ }+ let a = operand_of(&m, "a", "`a` must be a point or curve")?;+ let b = operand_of(&m, "b", "`b` must be a point or curve")?;+ Ok(Self { a, b, line, point, sketch })+ };+ read().map_err(D::Error::custom)+ }+}++/// Fix points and curves where they are, or release them (a curve keeps its radius too; the+/// origin, projected geometry and a point fixed by its own coordinates are left as they are).+#[derive(Debug, JsonSchema)]+#[schemars(deny_unknown_fields, transform = fix_required)]+pub struct FixParams {+ /// One point or curve (an id). Goes first among `entities`.+ #[serde(default)]+ pub entity: Option<String>,+ /// Points and curves (ids): one, or a list of up to 10000. `entity` or `entities` must name+ /// at least one.+ #[serde(default)]+ pub entities: Option<Names>,+ /// `true` fixes them all, `false` releases them all. Default: fix them, unless all are+ /// fixed already, then release them.+ #[serde(default)]+ pub fixed: Option<bool>,+ /// The sketch (default: the one being edited).+ #[serde(default)]+ pub sketch: Option<SketchKey>,+}++fn fix_required(schema: &mut Schema) {+ require_either(schema, &["entity"], &["entities"]);+}++impl<'de> Deserialize<'de> for FixParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let m = fields(d)?;+ let read = || -> Read<Self> {+ let entities = names_of(&m, "entities")?;+ let fixed = flag_of(&m, "fixed")?;+ // The handler reads `entity` as text only; the refusal for none at all comes first.+ if entities.as_ref().is_none_or(|e| e.0.is_empty()) && !m.get("entity").is_some_and(Value::is_string) {+ return refuse("`entity` or `entities` must name sketch points or curves");+ }+ let entity = text_of(&m, "entity")?;+ Ok(Self { entity, entities, fixed, sketch: sketch_of(&m)? })+ };+ read().map_err(D::Error::custom)+ }+}++#[cfg(test)]+#[path = "sketch_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/sketch_tests.rs b/crates/engine/src/schema/sketch_tests.rsnew file mode 100644index 0000000000..5cb2c120df--- /dev/null+++ b/crates/engine/src/schema/sketch_tests.rs@@ -0,0 +1,478 @@+use serde_json::{Value, json};++use super::{+ CoincidentParams, CoincidentResult, CollinearParams, ConcentricParams, ConstraintResult, EqualParams, EqualResult, FixParams, FixResult,+ HorizontalVerticalParams, MidpointParams, Operand, ParallelParams, PerpendicularParams, PointOperand, SketchKey, SymmetryParams, SymmetryResult,+ TangentParams,+};+use crate::Session;+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};++const IDS: [&str; 11] = [+ "sketch.constraint.coincident",+ "sketch.constraint.collinear",+ "sketch.constraint.concentric",+ "sketch.constraint.equal",+ "sketch.constraint.fix",+ "sketch.constraint.horizontal_vertical",+ "sketch.constraint.midpoint",+ "sketch.constraint.parallel",+ "sketch.constraint.perpendicular",+ "sketch.constraint.symmetry",+ "sketch.constraint.tangent",+];++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, with lines `l1` to `l6`, circles `c1` to `c4` and points `p1` and `p2`.+fn scene(level: ParamCheck) -> Session {+ let mut s = Session { param_check: ParamCheck::Off, ..Session::default() };+ run(&mut s, "sketch.create", json!({"plane": "XY"}));+ for (id, a, b) in [+ ("l1", [0, 0], [20, 5]),+ ("l2", [30, 0], [50, 10]),+ ("l3", [0, 20], [20, 30]),+ ("l4", [30, 20], [50, 22]),+ ("l5", [0, 40], [20, 41]),+ ("l6", [30, 40], [49, 52]),+ ] {+ run(&mut s, "sketch.line", json!({"points": [a, b], "ids": [id]}));+ }+ for (id, c, r) in [("c1", [0, 70], 5), ("c2", [30, 70], 8), ("c3", [60, 70], 3), ("c4", [60, 80], 3)] {+ run(&mut s, "sketch.circle.center", json!({"center": c, "radius": r, "ids": [id]}));+ }+ run(&mut s, "sketch.point", json!({"point": [5, 100], "id": "p1"}));+ run(&mut s, "sketch.point", json!({"point": [15, 105], "id": "p2"}));+ s.param_check = level;+ s+}++fn output_conforms<T: schemars::JsonSchema>(r: &Value) {+ let schema = output_schema_for::<T>();+ let schema = schema.as_value();+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");+}++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<CoincidentParams>(), &["a", "b", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<CollinearParams>(), &["a", "b", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<ConcentricParams>(), &["a", "b", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<EqualParams>(), &["a", "b", "curves", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<FixParams>(), &["entities", "entity", "fixed", "sketch"]);+ assert_keys(input_schema_for::<HorizontalVerticalParams>(), &["if_redundant", "line", "mode", "points", "sketch"]);+ assert_keys(input_schema_for::<MidpointParams>(), &["a", "b", "if_redundant", "line", "point", "sketch"]);+ assert_keys(input_schema_for::<ParallelParams>(), &["a", "b", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<PerpendicularParams>(), &["a", "b", "if_redundant", "sketch"]);+ assert_keys(input_schema_for::<SymmetryParams>(), &["a", "b", "line", "point", "sketch"]);+ assert_keys(input_schema_for::<TangentParams>(), &["a", "b", "if_redundant", "sketch"]);+}++#[test]+fn the_commands_publish_their_schemas() {+ for id in IDS {+ let spec = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));+ assert!(spec.contract.is_some() && spec.output.is_some(), "{id}");+ }+}++/// Keys a handler refuses when they are left out are required in the schema (and optional in the+/// type, so that the handler's message is the one a caller sees).+#[test]+fn keys_the_handler_needs_are_required_in_the_schema() {+ let required = |schema: schemars::Schema| -> Vec<String> {+ schema.as_value()["required"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect()+ };+ assert_eq!(required(input_schema_for::<TangentParams>()), ["a", "b"]);+ assert_eq!(required(input_schema_for::<CoincidentParams>()), ["a", "b"]);+ assert_eq!(required(input_schema_for::<ConcentricParams>()), ["a", "b"]);+ assert_eq!(required(input_schema_for::<SymmetryParams>()), ["a", "b"]);+ // The forms that exclude each other are alternatives.+ let schema = input_schema_for::<EqualParams>();+ assert_eq!(schema.as_value()["anyOf"], json!([{"required": ["a", "b"]}, {"required": ["curves"]}]));+ let schema = input_schema_for::<MidpointParams>();+ assert_eq!(schema.as_value()["anyOf"], json!([{"required": ["a", "b"]}, {"required": ["point", "line"]}]));+ let schema = input_schema_for::<HorizontalVerticalParams>();+ assert_eq!(schema.as_value()["anyOf"], json!([{"required": ["line"]}, {"required": ["points"]}]));+ let schema = input_schema_for::<FixParams>();+ assert_eq!(schema.as_value()["anyOf"], json!([{"required": ["entity"]}, {"required": ["entities"]}]));+}++#[test]+fn strict_keeps_todays_errors() {+ // The sketch is named: after the scene the handler would otherwise stop at "no sketch is being+ // edited" before it looks at the rest.+ let on = |mut p: Value| {+ p["sketch"] = json!("Sketch1");+ p+ };+ assert_strict_keeps_todays_errors(&[+ ("sketch.constraint.tangent", on(json!({"a": 5, "b": "x"}))),+ ("sketch.constraint.tangent", on(json!({"a": "x", "b": ["y"]}))),+ ("sketch.constraint.tangent", on(json!({"a": null, "b": "x"}))),+ ("sketch.constraint.tangent", on(json!({"a": {"point": 1}, "b": "x"}))),+ ("sketch.constraint.tangent", on(json!({"b": "x"}))),+ ("sketch.constraint.parallel", on(json!({"a": true, "b": "x"}))),+ ("sketch.constraint.perpendicular", on(json!({"a": "x", "b": 3}))),+ ("sketch.constraint.collinear", on(json!({"a": [1], "b": "x"}))),+ ("sketch.constraint.equal", on(json!({"a": 5, "b": "l1"}))),+ ("sketch.constraint.equal", on(json!({"a": "l1", "b": null}))),+ ("sketch.constraint.equal", on(json!({"curves": ["a"]}))),+ ("sketch.constraint.equal", on(json!({"curves": null}))),+ ("sketch.constraint.equal", on(json!({"curves": 5}))),+ ("sketch.constraint.equal", on(json!({"curves": ["a", 5]}))),+ ("sketch.constraint.equal", on(json!({"curves": vec!["a"; 201]}))),+ ("sketch.constraint.concentric", on(json!({"a": 5, "b": "x"}))),+ ("sketch.constraint.concentric", on(json!({"a": "x", "b": 5}))),+ ("sketch.constraint.coincident", on(json!({"a": 5, "b": "x"}))),+ ("sketch.constraint.coincident", on(json!({"a": "x", "b": 5}))),+ ("sketch.constraint.coincident", on(json!({"a": "x"}))),+ ("sketch.constraint.coincident", on(json!({"a": 5}))),+ ("sketch.constraint.coincident", on(json!({"a": {"nothing": 1}}))),+ ("sketch.constraint.fix", on(json!({"fixed": "x", "entities": 5}))),+ ("sketch.constraint.coincident", on(json!({"a": {"midpoint": 5}, "b": "x"}))),+ ("sketch.constraint.coincident", on(json!({"a": {"nothing": 5}, "b": "x"}))),+ ("sketch.constraint.horizontal_vertical", on(json!({}))),+ ("sketch.constraint.horizontal_vertical", on(json!({"line": 5}))),+ ("sketch.constraint.horizontal_vertical", on(json!({"points": ["l1.start"]}))),+ ("sketch.constraint.horizontal_vertical", on(json!({"points": ["l1.start", 5]}))),+ ("sketch.constraint.horizontal_vertical", on(json!({"points": ["l1.start", {"midpoint": 5}]}))),+ ("sketch.constraint.horizontal_vertical", on(json!({"points": 5, "line": 5}))),+ ("sketch.constraint.midpoint", on(json!({"a": 5, "b": "l1"}))),+ ("sketch.constraint.midpoint", on(json!({"a": "l1", "b": null}))),+ ("sketch.constraint.midpoint", on(json!({"a": "l1"}))),+ ("sketch.constraint.midpoint", on(json!({"point": 5, "line": "l1"}))),+ ("sketch.constraint.midpoint", on(json!({"point": "p1", "line": 5}))),+ ("sketch.constraint.midpoint", on(json!({"point": "p1"}))),+ ("sketch.constraint.symmetry", on(json!({"a": 5, "b": "x", "line": "y"}))),+ ("sketch.constraint.symmetry", on(json!({"a": "x", "b": 5, "line": "y"}))),+ ("sketch.constraint.symmetry", on(json!({"a": "x", "b": "y", "line": 5}))),+ ("sketch.constraint.symmetry", on(json!({"a": "x", "b": "y", "point": 5}))),+ ("sketch.constraint.symmetry", on(json!({"a": "x", "b": "y", "point": null}))),+ ("sketch.constraint.fix", on(json!({}))),+ ("sketch.constraint.fix", on(json!({"entities": []}))),+ ("sketch.constraint.fix", on(json!({"entity": 5}))),+ ("sketch.constraint.fix", on(json!({"entities": 5}))),+ ("sketch.constraint.fix", on(json!({"entities": ["p1", 5]}))),+ ("sketch.constraint.fix", on(json!({"entity": "p1", "entities": {"x": 1}}))),+ ]);+ // `sketch` is read the way `sketch_store::target` reads it.+ let with_sketch = |sketch: Value| json!({"a": "l1", "b": "l2", "sketch": sketch});+ assert_strict_keeps_todays_errors(&[+ ("sketch.constraint.parallel", with_sketch(json!(true))),+ ("sketch.constraint.parallel", with_sketch(json!(-1))),+ ("sketch.constraint.parallel", with_sketch(json!(1.5))),+ ("sketch.constraint.parallel", with_sketch(json!(["Sketch1"]))),+ ("sketch.constraint.parallel", with_sketch(json!(999))),+ ("sketch.constraint.parallel", with_sketch(json!("nothing"))),+ ("sketch.constraint.fix", json!({"entity": "p1", "sketch": {}})),+ ]);+}++/// The types read each key as the handlers do: what a handler accepts, they accept (and give the+/// handler's message for what it refuses); keys a handler does not read in a case are not looked+/// at in that case.+#[test]+fn the_types_read_each_key_as_the_handlers_do() {+ fn parse<T: serde::de::DeserializeOwned>(v: Value) -> Result<T, String> {+ serde_json::from_value(v).map_err(|e| e.to_string())+ }+ fn whole_message(e: String) -> String {+ e.trim_start_matches(['\u{1}', '\u{2}', '\u{3}']).split(" at line ").next().unwrap_or_default().to_string()+ }++ // `sketch`: an id, a name or null.+ let p: TangentParams = parse(json!({"a": "x", "b": "y", "sketch": 3})).unwrap();+ assert_eq!(p.sketch, Some(SketchKey::Id(3)));+ let p: TangentParams = parse(json!({"a": "x", "b": "y", "sketch": "S"})).unwrap();+ assert_eq!(p.sketch, Some(SketchKey::Name("S".into())));+ let p: TangentParams = parse(json!({"a": "x", "b": "y", "sketch": null})).unwrap();+ assert_eq!(p.sketch, None);+ for bad in [json!(-1), json!(1.5), json!(true), json!([1]), json!({})] {+ let e = parse::<TangentParams>(json!({"a": "x", "b": "y", "sketch": bad})).map(|_| ()).unwrap_err();+ assert_eq!(whole_message(e), "`sketch` must be an id or a name", "{bad}");+ }++ // Operands: an id, or a model edge or vertex (projected before the handler reads them).+ let p: ParallelParams = parse(json!({"a": "l1", "b": {"edge": [0, 0, 0], "body": "Body1"}})).unwrap();+ assert_eq!((p.a, matches!(p.b, Some(Operand::Model(_)))), (Some(Operand::Id("l1".into())), true));+ let p: ParallelParams = parse(json!({"a": {"vertex": [1, 2, 3]}, "b": "y"})).unwrap();+ assert!(matches!(p.a, Some(Operand::Model(_))));+ let p: ParallelParams = parse(json!({})).unwrap();+ assert_eq!((p.a, p.b), (None, None), "left out: the handler's to refuse");+ let e = parse::<ParallelParams>(json!({"a": 5, "b": "y"})).map(|_| ()).unwrap_err();+ assert_eq!(whole_message(e), "`a` must be a curve id, or x / y for a sketch axis");+ let e = parse::<ConcentricParams>(json!({"a": "c1", "b": {"midpoint": "l1"}})).map(|_| ()).unwrap_err();+ assert_eq!(whole_message(e), "`b` must be a curve id");++ // `if_redundant` and the plain flags and texts.+ let e = parse::<TangentParams>(json!({"a": "x", "b": "y", "if_redundant": 5})).map(|_| ()).unwrap_err();+ assert_eq!(whole_message(e), "`if_redundant` must be text");+ assert!(parse::<TangentParams>(json!({"a": "x", "b": "y", "if_redundant": null})).is_ok());+ let e = parse::<FixParams>(json!({"entity": "p1", "fixed": "yes"})).map(|_| ()).unwrap_err();+ assert_eq!(whole_message(e), "`fixed` must be true or false");++ // Equal: with `curves`, `a`, `b` and `if_redundant` are not read.+ let p: EqualParams = parse(json!({"curves": ["c1", "c2"], "a": 5, "b": null, "if_redundant": 5})).unwrap();+ assert_eq!((p.curves.map(|c| c.0), p.a, p.b, p.if_redundant), (Some(vec!["c1".into(), "c2".into()]), None, None, None));+ assert_eq!(+ whole_message(parse::<EqualParams>(json!({"curves": ["c1"]})).map(|_| ()).unwrap_err()),+ "`curves` must list 2 to 200 lines or circles/arcs"+ );+ assert_eq!(+ whole_message(parse::<EqualParams>(json!({"curves": null, "a": "l1", "b": "l2"})).map(|_| ()).unwrap_err()),+ "`curves` must list 2 to 200 lines or circles/arcs"+ );+ assert_eq!(+ whole_message(parse::<EqualParams>(json!({"curves": ["c1", 7]})).map(|_| ()).unwrap_err()),+ "`curves` must list names; the entry 2 is 7"+ );+ assert_eq!(whole_message(parse::<EqualParams>(json!({"curves": 7})).map(|_| ()).unwrap_err()), "`curves` must be a list of names; it is 7");+ assert!(parse::<EqualParams>(json!({"curves": vec!["c"; 200]})).is_ok());+ assert!(parse::<EqualParams>(json!({"curves": vec!["c"; 201]})).is_err());+ // Without `curves`, `a` and `b` are read.+ assert_eq!(whole_message(parse::<EqualParams>(json!({"a": 5, "b": "l2"})).map(|_| ()).unwrap_err()), "`a` must be a curve id");++ // Coincident: the middle of a line is a point.+ let p: CoincidentParams = parse(json!({"a": {"midpoint": "l1"}, "b": "p1"})).unwrap();+ assert_eq!(p.a, Some(PointOperand::Midpoint("l1".into())));+ let msg = |v: Value| whole_message(parse::<CoincidentParams>(v).map(|_| ()).unwrap_err());+ assert_eq!(msg(json!({"a": {"midpoint": 3}, "b": "p1"})), "`midpoint` must be a curve id");+ assert_eq!(msg(json!({"a": "p1", "b": 3})), "`b` must be a point or curve");+ assert_eq!(msg(json!({"a": 3, "b": "p1"})), "`a` must be a point reference");+ // The handler reads `b` before `a`.+ assert_eq!(msg(json!({"a": 3, "b": 3})), "`b` must be a point or curve");++ // Horizontal / Vertical: `points` when it is a list, else `line`.+ let p: HorizontalVerticalParams = parse(json!({"points": ["l1.start", {"midpoint": "l2"}], "line": 5, "mode": "VERTICAL"})).unwrap();+ assert!(p.line.is_none() && p.points.is_some(), "`line` is not read when `points` is a list");+ let p: HorizontalVerticalParams = parse(json!({"points": "x", "line": "l1"})).unwrap();+ assert_eq!((p.line.as_deref(), p.points.is_some()), (Some("l1"), false), "a `points` that is not a list is not read");+ let p: HorizontalVerticalParams = parse(json!({"points": null, "line": "l1", "mode": "bogus"})).unwrap();+ assert_eq!(p.line.as_deref(), Some("l1"));+ let msg = |v: Value| whole_message(parse::<HorizontalVerticalParams>(v).map(|_| ()).unwrap_err());+ assert_eq!(msg(json!({"line": 5})), "`line` must be a curve id");+ assert_eq!(msg(json!({"points": "x", "line": 5})), "`line` must be a curve id");+ assert_eq!(msg(json!({"points": ["a"]})), "`points` needs exactly two point references");+ assert_eq!(msg(json!({"points": ["a", "b", "c"]})), "`points` needs exactly two point references");+ assert_eq!(msg(json!({"points": ["a", 3]})), "`points` must be a point reference");+ assert_eq!(msg(json!({"points": ["a", {"midpoint": 3}]})), "`midpoint` must be a curve id");+ assert_eq!(msg(json!({"points": [{"edge": [0, 0, 0]}, "b"]})), "`points` must be a point reference");++ // Midpoint: `a` and `b` when either is given (`null` too), else `point` and `line`.+ let p: MidpointParams = parse(json!({"a": "l1", "b": "l2", "point": 5, "line": 6})).unwrap();+ assert!(p.point.is_none() && p.line.is_none() && p.a.is_some(), "`point` and `line` are not read with `a` and `b`");+ let p: MidpointParams = parse(json!({"point": "p1", "line": "l1"})).unwrap();+ assert!(p.point.is_some() && p.line.is_some());+ let msg = |v: Value| whole_message(parse::<MidpointParams>(v).map(|_| ()).unwrap_err());+ assert_eq!(msg(json!({"a": "l1", "b": null, "point": "p1", "line": "l1"})), "`b` must be a point or line id");+ assert_eq!(msg(json!({"a": 5, "b": "l2"})), "`a` must be a point or line id");+ assert_eq!(msg(json!({"b": 5})), "`b` must be a point or line id");+ assert_eq!(msg(json!({"point": 5, "line": "l1"})), "`point` must be a point reference");+ assert_eq!(msg(json!({"point": "p1", "line": 5})), "`line` must be a curve id");++ // Symmetry: `point` when given (`null` too) and `line` is not read; else `line`.+ let p: SymmetryParams = parse(json!({"a": "p1", "b": "p2", "point": "origin", "line": 5})).unwrap();+ assert!(p.point.is_some() && p.line.is_none());+ let p: SymmetryParams = parse(json!({"a": "p1", "b": "p2", "line": "y"})).unwrap();+ assert!(p.line.is_some() && p.point.is_none());+ let msg = |v: Value| whole_message(parse::<SymmetryParams>(v).map(|_| ()).unwrap_err());+ assert_eq!(msg(json!({"a": "p1", "b": "p2", "point": null, "line": "y"})), "`point` must be a point reference");+ assert_eq!(msg(json!({"a": "p1", "b": "p2", "line": 5})), "`line` must be a curve id, or x / y for a sketch axis");+ assert_eq!(msg(json!({"a": 1, "b": "p2", "line": "y"})), "`a` must be a point or curve");+ assert_eq!(msg(json!({"a": "p1", "b": 2, "line": "y"})), "`b` must be a point or curve");++ // Fix: `entity` or `entities`, one at least.+ let p: FixParams = parse(json!({"entity": "p1"})).unwrap();+ assert_eq!(p.entity.as_deref(), Some("p1"));+ let p: FixParams = parse(json!({"entities": "p1", "fixed": false})).unwrap();+ assert_eq!((p.entities.map(|e| e.0), p.fixed), (Some(vec!["p1".into()]), Some(false)));+ let p: FixParams = parse(json!({"entities": null, "entity": "p1"})).unwrap();+ assert!(p.entities.is_none());+ let msg = |v: Value| whole_message(parse::<FixParams>(v).map(|_| ()).unwrap_err());+ assert_eq!(msg(json!({})), "`entity` or `entities` must name sketch points or curves");+ assert_eq!(msg(json!({"entities": []})), "`entity` or `entities` must name sketch points or curves");+ assert_eq!(msg(json!({"entity": 5})), "`entity` or `entities` must name sketch points or curves");+ assert_eq!(msg(json!({"entities": 5})), "`entities` must be a list of names; it is 5");+ assert_eq!(msg(json!({"entities": ["a", true]})), "`entities` must list names; the entry 2 is true");+ // A `entity` that is not text is ignored by the handler when `entities` names something;+ // the type refuses it, which is what warn and strict report.+ assert_eq!(msg(json!({"entity": 5, "entities": ["p1"]})), "`entity` must be text");+}++fn assert_clean<T: schemars::JsonSchema>(s: &mut Session, id: &str, p: Value) -> Value {+ let r = run(s, id, p.clone());+ assert!(r.get("param_warnings").is_none(), "{id} {p} warned: {r}");+ output_conforms::<T>(&r);+ r+}++#[test]+fn replies_match_the_output_schemas_and_real_calls_get_no_warnings() {+ let new = || scene(ParamCheck::Warn);++ // Horizontal / Vertical: a line, a line with a mode, two points, a line's middle, and a+ // `line` that `points` makes unread.+ let mut s = new();+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l1"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l2", "mode": "Vertical"}));+ assert_clean::<ConstraintResult>(+ &mut s,+ "sketch.constraint.horizontal_vertical",+ json!({"points": ["l3.start", "l3.end"], "mode": "horizontal"}),+ );+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["c1.center", {"midpoint": "l4"}]}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": ["l5.start", "l5.end"], "line": 7}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.horizontal_vertical", json!({"points": "not a list", "line": "l6", "mode": "x"}));++ // Coincident: two points, a point on a curve, a point on an axis, a line's middle, two lines,+ // two circles, and a pair that is joined already.+ let mut s = new();+ let r = assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "l1.end", "b": "l2.start"}));+ assert!(r.get("existing").is_none() && r.get("constraints").is_none(), "{r}");+ let r = assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "l1.end", "b": "l2.start"}));+ assert_eq!(r["existing"], true, "{r}");+ assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "p1", "b": "c1"}));+ assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "x", "b": "p2"}));+ assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": {"midpoint": "l3"}, "b": "l4.start"}));+ assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "l5", "b": "l6"}));+ let r = assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "c3", "b": "c4"}));+ assert!(r["constraints"].as_array().is_some_and(|c| c.len() == 2) && r.get("constraint").is_some(), "{r}");++ // Tangent, parallel, perpendicular, collinear.+ let mut s = new();+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.tangent", json!({"a": "l1", "b": "c1"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.parallel", json!({"a": "l2", "b": "l3"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.parallel", json!({"a": "l4", "b": "x"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.perpendicular", json!({"a": "l5", "b": "l6"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.perpendicular", json!({"a": "y", "b": "l1", "sketch": "Sketch1"}));+ let mut s = new();+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.collinear", json!({"a": "l1", "b": "l2"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.collinear", json!({"a": "l3", "b": "l4", "if_redundant": "refuse"}));++ // Concentric: two circles, and a circle and a point.+ let mut s = new();+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.concentric", json!({"a": "c1", "b": "c2"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.concentric", json!({"a": "p1", "b": "c3"}));++ // Equal: two curves, and a list, with the keys that list leaves unread.+ let mut s = new();+ let r = assert_clean::<EqualResult>(&mut s, "sketch.constraint.equal", json!({"a": "l1", "b": "l2"}));+ assert!(r.get("constraint").is_some() && r.get("constraints").is_none(), "{r}");+ let r = assert_clean::<EqualResult>(&mut s, "sketch.constraint.equal", json!({"curves": ["c1", "c2", "c3"], "a": 5, "if_redundant": 5}));+ assert!(r["constraints"].as_array().is_some_and(|c| c.len() == 2) && r.get("constraint").is_none(), "{r}");+ assert_clean::<EqualResult>(&mut s, "sketch.constraint.equal", json!({"curves": ["c3", "c4"]}));++ // Midpoint: a point and a line, two lines, and the `a` and `b` form with `point` and `line`+ // left unread.+ let mut s = new();+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.midpoint", json!({"point": "p1", "line": "l1"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.midpoint", json!({"a": "l2", "b": "l3"}));+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.midpoint", json!({"a": "p2", "b": "l4", "point": 1, "line": 2}));++ // Symmetry: about a sketch axis, a line, a point, two lines and two circles.+ let mut s = new();+ let r = assert_clean::<SymmetryResult>(&mut s, "sketch.constraint.symmetry", json!({"a": "l2.start", "b": "l2.end", "line": "y"}));+ assert_eq!(r["constraints"].as_array().map(Vec::len), Some(1), "{r}");+ assert_clean::<SymmetryResult>(&mut s, "sketch.constraint.symmetry", json!({"a": "p1", "b": "p2", "line": "l5"}));+ assert_clean::<SymmetryResult>(&mut s, "sketch.constraint.symmetry", json!({"a": "l3", "b": "l4", "point": "origin"}));+ assert_clean::<SymmetryResult>(&mut s, "sketch.constraint.symmetry", json!({"a": "c1", "b": "c2", "line": "y"}));+ assert_clean::<SymmetryResult>(&mut s, "sketch.constraint.symmetry", json!({"a": "l5", "b": "l6", "line": "l1"}));++ // Fix: one entity, a list, `fixed`, and a release.+ let mut s = new();+ let r = assert_clean::<FixResult>(&mut s, "sketch.constraint.fix", json!({"entity": "p1"}));+ assert_eq!(r["result"], json!({"fixed": true, "changed": 1}), "{r}");+ assert_clean::<FixResult>(&mut s, "sketch.constraint.fix", json!({"entities": ["l1", "c1"], "fixed": true}));+ assert_clean::<FixResult>(&mut s, "sketch.constraint.fix", json!({"entity": "p2", "entities": "l2"}));+ let r = assert_clean::<FixResult>(&mut s, "sketch.constraint.fix", json!({"entities": ["p1", "l1"], "fixed": false, "sketch": "Sketch1"}));+ assert_eq!(r["result"]["fixed"], false, "{r}");+}++/// A constraint the sketch already determines is kept as a redundant one, and the reply says what+/// determines it, unless `if_redundant` is `refuse`.+#[test]+fn a_redundant_constraint_is_reported() {+ let mut s = scene(ParamCheck::Warn);+ assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.parallel", json!({"a": "l1", "b": "l2"}));+ let r = assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.parallel", json!({"a": "l1", "b": "l2"}));+ assert_eq!(r["redundant"], true, "{r}");+ assert!(r["determined_by"].is_array(), "{r}");+ let e = s.execute("sketch.constraint.parallel", &json!({"a": "l1", "b": "l2", "if_redundant": "Refuse"})).unwrap_err().to_string();+ assert!(e.contains("is already determined by"), "{e}");+}++/// A key a call misspells is reported in warn, and the reply still matches its schema.+#[test]+fn a_misspelt_key_is_reported_in_warn() {+ let cases: [(&str, Value, &str); 11] = [+ ("sketch.constraint.coincident", json!({"a": "l1.end", "b": "l2.start", "if_redundent": "refuse"}), "if_redundant"),+ ("sketch.constraint.collinear", json!({"a": "l1", "b": "l2", "skech": "Sketch1"}), "sketch"),+ ("sketch.constraint.concentric", json!({"a": "c1", "b": "c2", "bb": "x"}), "b"),+ ("sketch.constraint.equal", json!({"curvs": ["c1", "c2"], "a": "l1", "b": "l2"}), "curves"),+ ("sketch.constraint.fix", json!({"entites": ["p1"], "entity": "p1"}), "entities"),+ ("sketch.constraint.horizontal_vertical", json!({"line": "l1", "mod": "vertical"}), "mode"),+ ("sketch.constraint.midpoint", json!({"point": "p1", "lines": "l1", "line": "l1"}), "line"),+ ("sketch.constraint.parallel", json!({"a": "l1", "b": "l2", "sketch_": "Sketch1"}), "sketch"),+ ("sketch.constraint.perpendicular", json!({"a": "l1", "b": "l2", "if_redundnt": "refuse"}), "if_redundant"),+ ("sketch.constraint.symmetry", json!({"a": "p1", "b": "p2", "lin": "y", "line": "y"}), "line"),+ ("sketch.constraint.tangent", json!({"a": "l1", "b": "c1", "if_redundant ": "refuse"}), "if_redundant"),+ ];+ for (id, p, nearest) in cases {+ let mut s = scene(ParamCheck::Warn);+ let r = run(&mut s, id, p.clone());+ let warnings = r["param_warnings"].as_array().unwrap_or_else(|| panic!("{id} {p}: no warning in {r}"));+ assert_eq!(warnings.len(), 1, "{id}: {warnings:?}");+ let w = warnings[0].as_str().unwrap_or_default();+ assert!(w.starts_with("unknown key `") && w.contains(&format!("did you mean `{nearest}`?")), "{id}: {w}");+ // And the check names it, without running anything.+ assert_eq!(issues(id, &p).len(), 1, "{id}");+ match id {+ "sketch.constraint.fix" => output_conforms::<FixResult>(&r),+ "sketch.constraint.symmetry" => output_conforms::<SymmetryResult>(&r),+ "sketch.constraint.coincident" => output_conforms::<CoincidentResult>(&r),+ "sketch.constraint.equal" => output_conforms::<EqualResult>(&r),+ _ => output_conforms::<ConstraintResult>(&r),+ }+ // In strict the call is refused, and the sketch stays as it was.+ let mut s = scene(ParamCheck::Strict);+ let before = s.doc.clone();+ let e = s.execute(id, &p).unwrap_err().to_string();+ assert!(e.contains("unknown key"), "{id}: {e}");+ assert!(std::sync::Arc::ptr_eq(&before, &s.doc) || *before == *s.doc, "{id}");+ }+}++/// With the check off, the replies are the ones the commands gave before: the same keys, and no+/// `param_warnings`.+#[test]+fn off_leaves_the_replies_as_they_were() {+ let mut s = scene(ParamCheck::Off);+ let r = run(&mut s, "sketch.constraint.horizontal_vertical", json!({"line": "l1", "if_redundnt": 1}));+ let mut keys: Vec<_> = r.as_object().into_iter().flat_map(|o| o.keys().cloned()).collect();+ keys.sort();+ assert_eq!(keys, ["constraint", "created", "sketch"], "{r}");+ let r = run(&mut s, "sketch.constraint.fix", json!({"entity": "p1"}));+ let mut keys: Vec<_> = r.as_object().into_iter().flat_map(|o| o.keys().cloned()).collect();+ keys.sort();+ assert_eq!(keys, ["created", "result", "sketch"], "{r}");+}++/// A model edge or vertex is an operand: projected into the sketch first, and the call gets no+/// warning.+#[test]+fn model_edges_and_vertices_are_operands() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 50]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "Base", "distance": "20 mm"}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "offset": "20 mm", "name": "Top"}));+ run(&mut s, "sketch.line", json!({"points": [[10, 10], [40, 25]], "ids": ["l1"]}));+ let r = assert_clean::<ConstraintResult>(&mut s, "sketch.constraint.parallel", json!({"a": "l1", "b": {"edge": [100, 25, 20], "body": "Body1"}}));+ assert_eq!(r["created"]["curves"].as_array().map(Vec::len), Some(1), "the projected edge is reported: {r}");+ assert_clean::<CoincidentResult>(&mut s, "sketch.constraint.coincident", json!({"a": "l1.end", "b": {"vertex": [100, 0, 20]}}));+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex c2fa952fec..72e9ee26a7 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -115,19 +115,8 @@ sketch.circle.two_pointsketch.circle.two_tangentsketch.conicsketch.constrainer-sketch.constraint.coincident-sketch.constraint.collinear-sketch.constraint.concentricsketch.constraint.curvature-sketch.constraint.equal-sketch.constraint.fix-sketch.constraint.horizontal_vertical-sketch.constraint.midpoint-sketch.constraint.parallel-sketch.constraint.perpendicularsketch.constraint.polygon-sketch.constraint.symmetry-sketch.constraint.tangentsketch.constructionsketch.createsketch.delete