Skip to content

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

Agents and scripts: the tangent arcs and circles, slots, splines, conics, ellipses and sketch text describe their exact parameters and reply (#12550) (#12604)

PeppaWutzdbbfa437a5ca
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index 53002222d3..a96158d30f 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -120,6 +120,7 @@ pub mod sketch_clipboard;
mod sketch_constraints;
mod sketch_construction;
mod sketch_create;
+pub(crate) use sketch_create::{AT_MUST, MAX_TEXT_EDITS};
mod sketch_divide;
mod sketch_ends;
mod sketch_equation;
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index 9c38f8d999..0fda65c5ed 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -1956,6 +1956,12 @@ fn polygon_edge(s: &mut Session, p: &Value) -> Result<Value> {
}
pub(super) fn slot(s: &mut Session, p: &Value, cmd: &str, c0: Vec2, c1: Vec2, w: f64) -> Result<Value> {
+ let (out, info) = slot_parts(s, p, cmd, c0, c1, w)?;
+ Ok(result(out, info))
+}
+
+/// What [`slot`] adds: the curve and constraint ids, and the sketch's solve.
+pub(super) fn slot_parts(s: &mut Session, p: &Value, cmd: &str, c0: Vec2, c1: Vec2, w: f64) -> Result<((Vec<String>, Vec<String>), Value)> {
let h = w / 2.0;
let d = (c1 - c0).normalized().ok_or_else(|| bad(cmd, "the slot ends must differ"))?;
let n = d.perp();
@@ -1974,7 +1980,7 @@ pub(super) fn slot(s: &mut Session, p: &Value, cmd: &str, c0: Vec2, c1: Vec2, w:
cons.push(add_c(sk, ConstraintKind::Equal { a: a0, b: a1 })?);
Ok((ids_of(sk, &[l1, a1, l2, a0]), cons))
})?;
- Ok(result(out, info))
+ Ok((out, info))
}
fn slot_c2c(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/cmd/sketch_create.rs b/crates/engine/src/cmd/sketch_create.rs
index 5d756b460b..35430f3d50 100644
--- a/crates/engine/src/cmd/sketch_create.rs
+++ b/crates/engine/src/cmd/sketch_create.rs
@@ -13,11 +13,16 @@ macro_rules! text_style_doc {
};
}
-use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg, result, slot};
+use super::sketch::{add_c, circumcircle, edit, ids_of, mark_construction, req_parg, slot_parts};
use super::sketch_store;
use super::{CommandSpec, in_sketch};
use crate::params::{bad, num, req_vec2, str_, string_list};
-use crate::schema::sketch_create::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult};
+use crate::schema::sketch_create::{
+ ArcSlotCenterParams, ArcSlotResult, ArcSlotThreePointParams, ArcTangentParams, BlendCurveParams, CenterlineParams, ConicParams,
+ ControlPointSplineParams, DrawResult, EditTextParams, EditTextResult, EllipseParams, FitPointSplineParams, InfiniteLineParams, LineTypeResult,
+ MidpointLineParams, SketchTextParams, SlotCenterPointParams, SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams,
+ SplineReverseResult, TextChange, TextEditsResult, TextExpressions, TextResult, ThreeTangentCircleParams, TwoTangentCircleParams,
+};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
@@ -29,62 +34,108 @@ mod text_move_tests;
#[path = "sketch_text_expr_tests.rs"]
mod text_expr_tests;
+const MIDPOINT_LINE_CONTRACT: TypedContract<MidpointLineParams> = TypedContract::new();
+const ARC_TANGENT_CONTRACT: TypedContract<ArcTangentParams> = TypedContract::new();
+const TWO_TANGENT_CONTRACT: TypedContract<TwoTangentCircleParams> = TypedContract::new();
+const THREE_TANGENT_CONTRACT: TypedContract<ThreeTangentCircleParams> = TypedContract::new();
+const SLOT_CENTER_POINT_CONTRACT: TypedContract<SlotCenterPointParams> = TypedContract::new();
+const ARC_SLOT_THREE_CONTRACT: TypedContract<ArcSlotThreePointParams> = TypedContract::new();
+const ARC_SLOT_CENTER_CONTRACT: TypedContract<ArcSlotCenterParams> = TypedContract::new();
+const ELLIPSE_CONTRACT: TypedContract<EllipseParams> = TypedContract::new();
+const SPLINE_FIT_CONTRACT: TypedContract<FitPointSplineParams> = TypedContract::new();
+const SPLINE_CONTROL_CONTRACT: TypedContract<ControlPointSplineParams> = TypedContract::new();
+const CONIC_CONTRACT: TypedContract<ConicParams> = TypedContract::new();
+const BLEND_CONTRACT: TypedContract<BlendCurveParams> = TypedContract::new();
+const CENTERLINE_CONTRACT: TypedContract<CenterlineParams> = TypedContract::new();
+const INFINITE_CONTRACT: TypedContract<InfiniteLineParams> = TypedContract::new();
+const TEXT_CONTRACT: TypedContract<SketchTextParams> = TypedContract::new();
+const EDIT_TEXT_CONTRACT: TypedContract<EditTextParams> = TypedContract::new();
const SPLINE_REVERSE_CONTRACT: TypedContract<SplineReverseParams> = TypedContract::new();
const SPLINE_REMOVE_POINT_CONTRACT: TypedContract<SplineRemovePointParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("sketch.line.midpoint", "Midpoint Line", midpoint_line)
+ CommandSpec::new("sketch.line.midpoint", "Midpoint Line", crate::checked!("sketch.line.midpoint", midpoint_line))
.at("SKETCH", "CREATE")
.icon("line_mid")
.enabled(in_sketch)
+ .contract(&MIDPOINT_LINE_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("mid: [x,y], point ref or snap (\"mid:<line>\", \"on:<curve>:x,y\", model vertex/edge); end: [x,y]; construction?", created_doc!())),
- CommandSpec::new("sketch.arc.tangent", "Tangent Arc", arc_tangent).at("SKETCH", "CREATE").icon("arc_tangent").enabled(in_sketch).params(concat!(
+ CommandSpec::new("sketch.arc.tangent", "Tangent Arc", crate::checked!("sketch.arc.tangent", arc_tangent))
+ .at("SKETCH", "CREATE")
+ .icon("arc_tangent")
+ .enabled(in_sketch)
+ .contract(&ARC_TANGENT_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
+ .params(concat!(
"start: end point of a line or arc (\"l1.end\"), end: [x,y] or an existing point's id (\"l2.start\": the arc ends on that point); curve?: the curve to be tangent to (default: the one ending at start)",
created_doc!()
)),
- CommandSpec::new("sketch.circle.two_tangent", "2-Tangent Circle", circle_tan_tan)
+ CommandSpec::new("sketch.circle.two_tangent", "2-Tangent Circle", crate::checked!("sketch.circle.two_tangent", circle_tan_tan))
.at("SKETCH", "CREATE")
.icon("circle_tt")
.enabled(in_sketch)
+ .contract(&TWO_TANGENT_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("curves: [two lines/circles/arcs], radius | diameter: expr, near: [x,y] (which of the solutions)", created_doc!())),
- CommandSpec::new("sketch.circle.three_tangent", "3-Tangent Circle", circle_three_tan)
+ CommandSpec::new("sketch.circle.three_tangent", "3-Tangent Circle", crate::checked!("sketch.circle.three_tangent", circle_three_tan))
.at("SKETCH", "CREATE")
.icon("circle_ttt")
.enabled(in_sketch)
+ .contract(&THREE_TANGENT_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("curves: [three lines/circles/arcs], near: [x,y] (which of the solutions)", created_doc!())),
- CommandSpec::new("sketch.slot.center_point", "Center Point Slot", slot_center_point)
+ CommandSpec::new("sketch.slot.center_point", "Center Point Slot", crate::checked!("sketch.slot.center_point", slot_center_point))
.at("SKETCH", "CREATE")
.icon("slot_center")
.enabled(in_sketch)
+ .contract(&SLOT_CENTER_POINT_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("center: slot centre, end: one arc centre, width", created_doc!())),
- CommandSpec::new("sketch.slot.arc_three_point", "Three Point Arc Slot", arc_slot_three)
+ CommandSpec::new("sketch.slot.arc_three_point", "Three Point Arc Slot", crate::checked!("sketch.slot.arc_three_point", arc_slot_three))
.at("SKETCH", "CREATE")
.icon("arc_slot")
.enabled(in_sketch)
+ .contract(&ARC_SLOT_THREE_CONTRACT)
+ .output(output_schema_for::<ArcSlotResult>)
.params(concat!("start, through, end: points on the centre arc, width", created_doc!())),
- CommandSpec::new("sketch.slot.arc_center", "Center Point Arc Slot", arc_slot_center)
+ CommandSpec::new("sketch.slot.arc_center", "Center Point Arc Slot", crate::checked!("sketch.slot.arc_center", arc_slot_center))
.at("SKETCH", "CREATE")
.icon("arc_slot_center")
.enabled(in_sketch)
+ .contract(&ARC_SLOT_CENTER_CONTRACT)
+ .output(output_schema_for::<ArcSlotResult>)
.params(concat!("center, start: centre arc start, end: direction of the centre arc end (counter-clockwise) or sweep: degrees (0 < sweep < 360), width; returns centre_arc", created_doc!())),
- CommandSpec::new("sketch.ellipse", "Ellipse", ellipse).at("SKETCH", "CREATE").icon("ellipse").enabled(in_sketch).params(concat!(
+ CommandSpec::new("sketch.ellipse", "Ellipse", crate::checked!("sketch.ellipse", ellipse))
+ .at("SKETCH", "CREATE")
+ .icon("ellipse")
+ .enabled(in_sketch)
+ .contract(&ELLIPSE_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
+ .params(concat!(
"center, major: end of the major axis [x,y], minor: a point the ellipse passes through on the minor side [x,y] | minor_radius. Also adds its major and minor axes as construction lines through the centre (their ends: the major end and the point opposite it, and the two ends of the minor axis on the ellipse), held by midpoint, perpendicular and point-on-curve constraints, so a half-axis is the distance from the centre to an axis end and an axis line's length is a full axis; axes?: bool (default true; false: the ellipse alone, as the Ellipse tool draws it with Draw ellipses with their axes off)",
created_doc!()
)),
- CommandSpec::new("sketch.spline.fit_point", "Fit Point Spline", spline_fit)
+ CommandSpec::new("sketch.spline.fit_point", "Fit Point Spline", crate::checked!("sketch.spline.fit_point", spline_fit))
.at("SKETCH", "CREATE")
.icon("spline")
.enabled(in_sketch)
+ .contract(&SPLINE_FIT_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("points: [[x,y] or point refs…] (2…500): the spline passes through them, periodic?: boolean (default false); periodic cubic fit closes smoothly through at least 3 distinct samples", created_doc!())),
- CommandSpec::new("sketch.spline.control_point", "Control Point Spline", spline_cv3)
+ CommandSpec::new("sketch.spline.control_point", "Control Point Spline", crate::checked!("sketch.spline.control_point", spline_cv3))
.at("SKETCH", "CREATE")
.icon("spline_cv")
.enabled(in_sketch)
+ .contract(&SPLINE_CONTROL_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("points: control points (2…500), cubic", created_doc!())),
- CommandSpec::new("sketch.spline.control_point_5", "Control Point Spline (Degree 5)", spline_cv5)
+ CommandSpec::new("sketch.spline.control_point_5", "Control Point Spline (Degree 5)", crate::checked!("sketch.spline.control_point_5", spline_cv5))
.at("SKETCH", "CREATE")
.icon("spline_cv")
.enabled(in_sketch)
+ .contract(&SPLINE_CONTROL_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("points: control points (2…500), degree 5", created_doc!())),
CommandSpec::new("sketch.spline.insert_point", "Add Spline Point", spline_insert_point)
.icon("spline")
@@ -102,36 +153,54 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&SPLINE_REVERSE_CONTRACT)
.output(output_schema_for::<SplineReverseResult>)
.params("curve: spline id (fit point, control point or closed): its last point becomes its first and the curve runs the other way along the same path; its points and the constraints on them stay. Refused for a projected spline and for one an offset uses or makes. Returns curve"),
- CommandSpec::new("sketch.conic", "Conic Curve", conic)
+ CommandSpec::new("sketch.conic", "Conic Curve", crate::checked!("sketch.conic", conic))
.at("SKETCH", "CREATE")
.icon("conic")
.enabled(in_sketch)
+ .contract(&CONIC_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!("start, end, apex: [x,y] or point refs; rho?: 0…1 (default 0.5: parabola)", created_doc!())),
- CommandSpec::new("sketch.blend_curve", "Blend Curve", blend)
+ CommandSpec::new("sketch.blend_curve", "Blend Curve", crate::checked!("sketch.blend_curve", blend))
.at("SKETCH", "MODIFY")
.icon("blend")
.enabled(in_sketch)
+ .contract(&BLEND_CONTRACT)
+ .output(output_schema_for::<DrawResult>)
.params(concat!(
"a, b: end points of two curves (\"l1.end\", \"a2.start\"), continuity?: g1|g2|g3|g4 (default g1: a tangent spline; g2…g4 match the reference curves' curvature, curvature rate and 4th derivative as well, as one Bézier of degree 5, 7 or 9)",
created_doc!()
)),
- CommandSpec::new("sketch.centerline", "Centerline", centerline)
+ CommandSpec::new("sketch.centerline", "Centerline", crate::checked!("sketch.centerline", centerline))
.at("SKETCH", "CREATE")
.icon("centerline")
.enabled(in_sketch)
+ .contract(&CENTERLINE_CONTRACT)
+ .output(output_schema_for::<LineTypeResult>)
.params("curves: [line ids], value?: bool (default toggles): centerline line type (not in profiles; an axis)"),
- CommandSpec::new("sketch.infinite", "Infinite Line", infinite_line).icon("infinite")
+ CommandSpec::new("sketch.infinite", "Infinite Line", crate::checked!("sketch.infinite", infinite_line))
+ .icon("infinite")
.enabled(in_sketch)
+ .contract(&INFINITE_CONTRACT)
+ .output(output_schema_for::<LineTypeResult>)
.params("curves: [line ids], value?: bool (default toggles): infinite line type (#1359): construction geometry drawn across the whole view through the line's two points; off, a normal line"),
- CommandSpec::new("sketch.text", "Text", text).at("SKETCH", "CREATE").icon("sketch_text").enabled(in_sketch).params(concat!(
+ CommandSpec::new("sketch.text", "Text", crate::checked!("sketch.text", text))
+ .at("SKETCH", "CREATE")
+ .icon("sketch_text")
+ .enabled(in_sketch)
+ .contract(&TEXT_CONTRACT)
+ .output(output_schema_for::<TextResult>)
+ .params(concat!(
"text: string (\\n breaks lines), or text_expression: the words built from text parameters (parameters.add with unit text), number parameters and quoted texts joined by + (\"Label + '-L'\", \"'W' + Width\"; a number parameter shows its value in the design's units, \"85 mm\", an angle in degrees, \"30°\"; number(Width) is the number alone and number(Width, 2) has 2 decimals): the text keeps it, its words follow the parameters (a parameter edit or a configuration row relabels it) and `exprs` returns it as `text`; at: baseline start [x,y], height?: capital height mm (default 5), angle?: deg; at's x and y, height and angle each take a number or an expression over the design's parameters as a string (\"plate_width / 2\", \"label_size\"): the text keeps the expression, follows the parameters, and returns it in `exprs`; an expression naming no parameter is the number it comes to, a bare number in one is in the design's units, \
font?: an installed font's family or full name, or a .ttf/.otf file path (~ and %VAR% expand; default: the built-in Liberation Sans), ",
text_style_doc!(),
created_doc!()
)),
- CommandSpec::new("sketch.edit_text", "Edit Text", edit_text).icon("edit")
+ CommandSpec::new("sketch.edit_text", "Edit Text", crate::checked!("sketch.edit_text", edit_text))
+ .icon("edit")
.enabled(in_sketch)
.live(edit_text_live)
+ .contract(&EDIT_TEXT_CONTRACT)
+ .output(output_schema_for::<EditTextResult>)
.params(concat!(
"link: the text's link id (or entity: one of its curves), text? or text_expression? (as in sketch.text; typed words replace the expression), at?, height?, angle?: deg (numbers or expressions as in sketch.text; a number replaces an expression, and so does moving the text), font?: family or file path (empty: the built-in font), ",
text_style_doc!(),
@@ -141,6 +210,20 @@ pub static COMMANDS: &[CommandSpec] = &[
)),
];
+/// A reply made of a typed value, which is also what its output schema describes.
+fn reply<T: serde::Serialize>(value: T) -> Result<Value> {
+ serde_json::to_value(value).map_err(|e| EngineError::Other(e.to_string()))
+}
+
+/// What a drawing command returns: the curves and constraints it made, and the sketch's solve.
+fn drawn_result(out: (Vec<String>, Vec<String>), info: Value) -> DrawResult {
+ DrawResult { curves: out.0, constraints: out.1, sketch: info, created: None, param_warnings: Vec::new() }
+}
+
+fn drawn(out: (Vec<String>, Vec<String>), info: Value) -> Result<Value> {
+ reply(drawn_result(out, info))
+}
+
/// The style a command's parameters give, over `old`.
fn text_style(p: &Value, cmd: &str, old: TextStyle) -> Result<TextStyle> {
let mut style = old;
@@ -181,7 +264,7 @@ fn text_style(p: &Value, cmd: &str, old: TextStyle) -> Result<TextStyle> {
}
/// What a text's `at` must be.
-const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or an expression";
+pub(crate) const AT_MUST: &str = "`at` must be the baseline start [x, y], each a number or an expression";
/// One number of a text, from a command's parameter `key`. A number is that number (mm, or
/// degrees for the angle). A string is an expression over the design's parameters: a bare number
@@ -278,15 +361,17 @@ fn text_source(doc: &solidcraft_doc::Document, p: &Value, cmd: &str, old: Option
}
/// The expressions behind a text's numbers, for a command's reply (`{"height": "plate_h / 10"}`).
-fn text_exprs_json(src: &LinkSource) -> Option<Value> {
+fn text_exprs(src: &LinkSource) -> Option<TextExpressions> {
let LinkSource::Text { exprs, .. } = src else { return None };
- let mut out = serde_json::Map::new();
- for (key, e) in [("x", &exprs.x), ("y", &exprs.y), ("height", &exprs.height), ("angle", &exprs.angle), ("text", &exprs.text)] {
- if let Some(e) = e {
- out.insert(key.into(), json!(e));
- }
- }
- (!out.is_empty()).then_some(Value::Object(out))
+ let out = TextExpressions {
+ x: exprs.x.clone(),
+ y: exprs.y.clone(),
+ height: exprs.height.clone(),
+ angle: exprs.angle.clone(),
+ text: exprs.text.clone(),
+ };
+ let any = [&out.x, &out.y, &out.height, &out.angle, &out.text].iter().any(|e| e.is_some());
+ any.then_some(out)
}
fn text(s: &mut Session, p: &Value) -> Result<Value> {
@@ -296,7 +381,7 @@ fn text(s: &mut Session, p: &Value) -> Result<Value> {
}
let src = text_source(&s.doc, p, cmd, None)?;
let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
- let exprs = text_exprs_json(&src);
+ let exprs = text_exprs(&src);
let (l, curves, guide) = sketch_store::update(s, id, |_, _, sk| {
// A text needs nothing outside its sketch (a path is one of its curves).
let geom = sk.text_source_geometry(&src).map_err(|e| bad(cmd, e.to_string()))?;
@@ -308,11 +393,7 @@ fn text(s: &mut Session, p: &Value) -> Result<Value> {
let curves = ids_of(sk, &sk.link_curves(&l));
Ok((l, curves, guide))
})?;
- let mut out = json!({"link": l, "curves": curves, "guide": guide});
- if let Some(exprs) = exprs {
- out["exprs"] = exprs;
- }
- Ok(out)
+ reply(TextResult { change: TextChange { link: l, curves, guide, exprs }, created: None, param_warnings: Vec::new() })
}
/// A text's path is its guide: the curve it follows becomes construction. Left as it was, it
@@ -378,17 +459,18 @@ pub(super) fn move_text(sk: &mut Sketch, link: &str, translate: Vec2, rotation:
}
/// The most texts one `sketch.edit_text {edits}` changes.
-const MAX_TEXT_EDITS: usize = 1000;
+pub(crate) const MAX_TEXT_EDITS: usize = 1000;
fn edit_text(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.edit_text";
let id = sketch_store::active(s).ok_or_else(|| bad(cmd, "no sketch is being edited"))?;
- sketch_store::update(s, id, |_, doc, sk| {
+ let edited = sketch_store::update(s, id, |_, doc, sk| {
// The numbers its expressions give now (a parameter may have changed since the sketch was
// last stored); one that cannot be evaluated is left as it was, to be replaced by this edit.
let _ = doc.apply_text_values(&doc.param_values().0, sk);
apply_text_edits(sk, doc, p)
- })
+ })?;
+ reply(edited)
}
/// One frame of an interactive resize or rotation: the sketch is solved and shown, the
@@ -399,21 +481,24 @@ fn edit_text_live(s: &mut Session, p: &Value) -> Result<(Value, Option<crate::Li
let (out, report) = super::sketch::edit_solved(s, id, false, solidcraft_sketch::Analysis::Full, |sk, doc| {
Ok((apply_text_edits(sk, doc, p)?, super::sketch::Left::Unsolved))
})?;
- Ok((out, report.map(|report| crate::LiveEdit { sketch: id, report })))
+ Ok((reply(out)?, report.map(|report| crate::LiveEdit { sketch: id, report })))
}
/// `sketch.edit_text`'s change: one text's (`link` or `entity`), or each of `edits` in turn.
/// One command, so the features after the sketch are rebuilt once for all of them.
-fn apply_text_edits(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<Value> {
+fn apply_text_edits(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<EditTextResult> {
let cmd = "sketch.edit_text";
match p.get("edits") {
- None | Some(Value::Null) => apply_text_edit(sk, doc, p),
+ None | Some(Value::Null) => {
+ let change = apply_text_edit(sk, doc, p)?;
+ Ok(EditTextResult::One(TextResult { change, created: None, param_warnings: Vec::new() }))
+ }
Some(Value::Array(edits)) => {
if edits.is_empty() || edits.len() > MAX_TEXT_EDITS {
return Err(bad(cmd, format!("`edits` must hold 1 to {MAX_TEXT_EDITS} edits")));
}
let outs = edits.iter().map(|e| apply_text_edit(sk, doc, e)).collect::<Result<Vec<_>>>()?;
- Ok(json!({"edits": outs}))
+ Ok(EditTextResult::Many(TextEditsResult { edits: outs, created: None, param_warnings: Vec::new() }))
}
Some(_) => Err(bad(cmd, "`edits` must be a list of edits")),
}
@@ -421,7 +506,7 @@ fn apply_text_edits(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value)
/// `sketch.edit_text`'s change to its sketch: the text source's new values and its outlines
/// regenerated from them.
-fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<Value> {
+fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -> Result<TextChange> {
let cmd = "sketch.edit_text";
let l = match (str_(p, "link"), str_(p, "entity")) {
(Some(l), _) => l.to_string(),
@@ -438,15 +523,11 @@ fn apply_text_edit(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value) -
return Err(bad(cmd, "the text makes no outline"));
}
let guide = guide(sk, &src);
- let exprs = text_exprs_json(&src);
+ let exprs = text_exprs(&src);
sk.set_link_source(&l, src.clone());
sk.update_link(&l, &geom)?;
let curves = ids_of(sk, &sk.link_curves(&l));
- let mut out = json!({"link": l, "curves": curves, "guide": guide});
- if let Some(exprs) = exprs {
- out["exprs"] = exprs;
- }
- Ok(out)
+ Ok(TextChange { link: l, curves, guide, exprs })
}
/// The curve ending at point `pi` and the direction leaving it there.
@@ -552,7 +633,7 @@ fn blend(s: &mut Session, p: &Value) -> Result<Value> {
solve_new_only(sk, first_new);
Ok((ids_of(sk, &[sp]), cons))
})?;
- Ok(result(out, info))
+ drawn(out, info)
}
fn centerline(s: &mut Session, p: &Value) -> Result<Value> {
@@ -577,7 +658,7 @@ fn centerline(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(ids.len())
})?;
- Ok(json!({"changed": n, "sketch": info}))
+ reply(LineTypeResult { changed: n, sketch: info, created: None, param_warnings: Vec::new() })
}
fn infinite_line(s: &mut Session, p: &Value) -> Result<Value> {
@@ -601,7 +682,7 @@ fn infinite_line(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok(ids.len())
})?;
- Ok(json!({"changed": n, "sketch": info}))
+ reply(LineTypeResult { changed: n, sketch: info, created: None, param_warnings: Vec::new() })
}
fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
@@ -659,7 +740,7 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
];
Ok((ids_of(sk, &[e]), cons))
})?;
- Ok(result(out, info))
+ drawn(out, info)
}
fn point_list(sk: &mut Sketch, doc: &solidcraft_doc::Document, p: &Value, cmd: &str) -> Result<Vec<usize>> {
@@ -704,7 +785,7 @@ fn spline(s: &mut Session, p: &Value, cmd: &str, control: bool, degree: u8) -> R
mark_construction(sk, &[c], p);
Ok((ids_of(sk, &[c]), Vec::new()))
})?;
- Ok(result(out, info))
+ drawn(out, info)
}
fn spline_fit(s: &mut Session, p: &Value) -> Result<Value> {
@@ -790,7 +871,7 @@ fn conic(s: &mut Session, p: &Value) -> Result<Value> {
mark_construction(sk, &[c], p);
Ok((ids_of(sk, &[c]), Vec::new()))
})?;
- Ok(result(out, info))
+ drawn(out, info)
}
fn midpoint_line(s: &mut Session, p: &Value) -> Result<Value> {
@@ -812,7 +893,7 @@ fn midpoint_line(s: &mut Session, p: &Value) -> Result<Value> {
mark_construction(sk, &[l], p);
Ok((ids_of(sk, &[l]), vec![k]))
})?;
- Ok(result(out, info))
+ drawn(out, info)
}
/// Direction leaving curve `ci` at its end point `pi` (continuing the curve past that end).
@@ -966,7 +1047,7 @@ fn arc_tangent(s: &mut Session, p: &Value) -> Result<Value> {
let k = add_c(sk, ConstraintKind::Tangent { a: ci, b: a })?;
Ok((ids_of(sk, &[a]), vec![k]))
})?;
- Ok(result(out, info))
+ drawn(out, info)
}
/// Initial radius for a circle near `at` touching the curves: the mean distance to them.
@@ -1052,7 +1133,7 @@ fn tangent_circle(s: &mut Session, p: &Value, cmd: &str, n: usize, radius: Optio
if info["solved"] != json!(true) {
return Err(bad(cmd, "no tangent circle there"));
}
- Ok(result(out, info))
+ drawn(out, info)
}
fn circle_tan_tan(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1079,7 +1160,8 @@ fn slot_center_point(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.slot.center_point";
let (c, e) = (req_vec2(cmd, p, "center")?, req_vec2(cmd, p, "end")?);
let w = width(p, cmd)?;
- slot(s, p, cmd, c * 2.0 - e, e, w)
+ let (out, info) = slot_parts(s, p, cmd, c * 2.0 - e, e, w)?;
+ drawn(out, info)
}
/// Arc slot around `o` (centre-line radius `r`) from angle `t0` sweeping `sweep` (> 0).
@@ -1117,9 +1199,7 @@ fn arc_slot(s: &mut Session, p: &Value, cmd: &str, o: Vec2, r: f64, t0: f64, swe
}
Ok((ids_of(sk, &[outer, cap_e, inner, cap_s]), cons))
})?;
- let mut out = result(out, info);
- out["centre_arc"] = json!(centre_arc);
- Ok(out)
+ reply(ArcSlotResult { drawn: drawn_result(out, info), centre_arc })
}
fn arc_slot_three(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/schema/sketch_create.rs b/crates/engine/src/schema/sketch_create.rs
index 7c6d1971e6..7453e00d78 100644
--- a/crates/engine/src/schema/sketch_create.rs
+++ b/crates/engine/src/schema/sketch_create.rs
@@ -1,10 +1,31 @@
-//! Contracts and result types for the commands in `cmd/sketch_create.rs`.
+//! Contracts and result types for the commands in `cmd/sketch_create.rs`: the construction lines,
+//! the spline edits, and (#12550) the tangent arcs and circles, slots, splines, conics, ellipses,
+//! blend curves, line types and sketch text.
+//!
+//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
+//! reads it and fails with the handler's message. What only the design can tell (a curve or point
+//! that does not exist, an expression that does not evaluate, a font that is not installed) stays
+//! the handler's to check. A key the handler refuses when it is left out is optional in the type
+//! and required in the schema, so that the handler's message, not the check's "is required", is
+//! what a caller sees. A key the handler reads only in some cases (`diameter` when there is no
+//! `radius`, `end` when there is no `sweep`, the keys of a text outside `edits`) is read here
+//! only in those cases, so that a call that works is not warned about. A call with several
+//! problems may get a different one first in strict than with the check off (the check goes key
+//! by key, the handlers in their own order).
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
+use std::borrow::Cow;
-use super::types::{AngleExpr, LengthExpr, SketchRef, present};
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Value, json};
+use solidcore_record::Vec2;
+
+use super::check::{located, parse_issue, whole};
+use super::motion::require;
+use super::sketch_ends::SketchTarget;
+use super::types::{AngleExpr, LengthExpr, Point2, Point3, SketchRef, not_blank_pattern, present};
+use crate::params;
/// Create a reference line in the active sketch: infinite, or a segment of a given length.
#[derive(Debug, Deserialize, JsonSchema)]
@@ -144,6 +165,1436 @@ pub struct SplineReverseResult {
pub param_warnings: Vec<String>,
}
+// ---------------------------------------------------------------------------------------------
+// The creation commands of `cmd/sketch_create.rs` (#12550)
+
+/// A value a handler reads with `null` as absent: `read` turns it into `T`, or into the handler's
+/// message, which is passed on whole.
+fn nullable<'de, D: Deserializer<'de>, T>(d: D, read: impl FnOnce(Value) -> Result<T, String>) -> Result<Option<T>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Null => Ok(None),
+ v => read(v).map(Some).map_err(|message| D::Error::custom(whole(message))),
+ }
+}
+
+/// `message` as the `Err` of a reader.
+fn refuse<T>(message: impl Into<String>) -> Result<T, String> {
+ Err(message.into())
+}
+
+/// The error of a handler's reader, as the message it gives.
+fn message_of(e: crate::EngineError) -> String {
+ match e {
+ crate::EngineError::BadParams { msg, .. } => msg,
+ other => other.to_string(),
+ }
+}
+
+/// `params::string_list`'s reading of `v` as the list `key`, with its messages.
+fn name_list(v: &Value, key: &str) -> Result<Vec<String>, String> {
+ let mut p = serde_json::Map::new();
+ p.insert(key.to_string(), v.clone());
+ params::string_list("", &Value::Object(p), key).map_err(message_of)
+}
+
+/// Adds properties to an object schema.
+fn add_properties(schema: &mut Schema, properties: Value) {
+ if let (Some(Value::Object(have)), Value::Object(more)) = (schema.get_mut("properties"), properties) {
+ have.extend(more);
+ }
+}
+
+/// A point `[x, y]` or `{x, y}` in mm, as `params::req_vec2` reads it: the handlers say `` `key`
+/// must be a point [x, y] `` for a missing one too.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct PointXY(pub Vec2);
+
+impl<'de> Deserialize<'de> for PointXY {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ params::vec2(&Value::deserialize(d)?).map(PointXY).ok_or_else(|| D::Error::custom("must be a point [x, y]"))
+ }
+}
+
+impl JsonSchema for PointXY {
+ fn schema_name() -> Cow<'static, str> {
+ "PointXY".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ generator.subschema_for::<Point2>()
+ }
+}
+
+/// The forms of a point argument: [`SketchPoint`] and [`SnapPoint`] differ in the snaps.
+fn point_arg_schema(generator: &mut SchemaGenerator, snaps: bool) -> Schema {
+ let point = generator.subschema_for::<Point2>();
+ let coordinate = generator.subschema_for::<LengthExpr>();
+ let mut forms = vec![
+ json!(point),
+ json!({
+ "description": "[x, y] where a coordinate may be an expression over the design's parameters, such as [\"w / 2\", 5]: a point that follows the parameters.",
+ "type": "array", "items": coordinate, "minItems": 2, "maxItems": 2
+ }),
+ json!({"description": "An existing point's id such as \"l1.end\" or \"p3\", or a snap such as \"mid:l1\".", "type": "string"}),
+ json!({"description": "An existing point by id.", "type": "object", "properties": {"ref": {"type": "string"}}, "required": ["ref"]}),
+ json!({"description": "A point by place.", "type": "object", "properties": {"at": point}, "required": ["at"]}),
+ ];
+ let description = if snaps {
+ let model = generator.subschema_for::<Point3>();
+ forms.push(json!({"description": "A model vertex [x, y, z] in mm, projected into the sketch.", "type": "object", "properties": {"vertex": model}, "required": ["vertex"]}));
+ forms.push(json!({"description": "A point on a model edge [x, y, z] in mm, projected into the sketch.", "type": "object", "properties": {"on_edge": model}, "required": ["on_edge"]}));
+ "A sketch point: [x, y] in mm (a coordinate may be an expression), an existing point's id (\"l1.end\"), {ref} or {at}, a snap as text (\"mid:<line>\", \"on:<curve>:x,y\", \"x:<a>+<b>:x,y\", \"vertex:x,y,z\"), or a model {vertex} or {on_edge}."
+ } else {
+ "A sketch point: [x, y] in mm (a coordinate may be an expression over the design's parameters), an existing point's id such as \"l1.end\", or {ref} or {at}."
+ };
+ json_schema!({"description": description, "anyOf": forms})
+}
+
+/// A point argument as `sketch::parg` reads it: a place `[x, y]` (a coordinate may be an
+/// expression), an existing point's id, `{ref}` or `{at}`. Kept as given, for the handler, which
+/// has the design to find a point and evaluate an expression.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SketchPoint(pub Value);
+
+impl<'de> Deserialize<'de> for SketchPoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ crate::cmd::point_arg_form(&v, false).map(|()| SketchPoint(v)).map_err(|why| D::Error::custom(whole(why)))
+ }
+}
+
+impl JsonSchema for SketchPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchPoint".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ point_arg_schema(generator, false)
+ }
+}
+
+/// A point argument of a command that snaps its points (`sketch_project::snap_points`): a
+/// [`SketchPoint`], or a model `{vertex}` or `{on_edge}`. Snaps given as text are text.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SnapPoint(pub Value);
+
+impl<'de> Deserialize<'de> for SnapPoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ crate::cmd::point_arg_form(&v, true).map(|()| SnapPoint(v)).map_err(|why| D::Error::custom(whole(why)))
+ }
+}
+
+impl JsonSchema for SnapPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "SnapPoint".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ point_arg_schema(generator, true)
+ }
+}
+
+/// A width, as the slot commands read it: a number above 0.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct SlotWidth(pub f64);
+
+impl<'de> Deserialize<'de> for SlotWidth {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)?.as_f64().and_then(params::finite) {
+ Some(w) if w > 1e-9 => Ok(SlotWidth(w)),
+ _ => Err(D::Error::custom("must be positive")),
+ }
+ }
+}
+
+impl JsonSchema for SlotWidth {
+ fn schema_name() -> Cow<'static, str> {
+ "SlotWidth".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The slot's width in mm: more than 0.000000001 and below 1 000 000 000.",
+ "type": "number", "exclusiveMinimum": 1e-9, "exclusiveMaximum": 1e9
+ })
+ }
+}
+
+/// The schema of curve ids as `params::string_list` reads them: a list of ids, or one id when
+/// one is enough, with the bounds on the list.
+fn curve_ids_schema(description: &str, min: usize, max: usize) -> Schema {
+ let list = json!({"type": "array", "items": {"type": "string"}, "minItems": min, "maxItems": max});
+ let forms = if min <= 1 && max >= 1 { json!([{"type": "string"}, list]) } else { json!([list]) };
+ json_schema!({"description": description, "anyOf": forms})
+}
+
+/// `N` curves, as the tangent circles read `curves`: an id or a list of exactly `N` ids. A
+/// missing, `null` or wrongly long one is refused with the same message.
+#[derive(Clone, Debug, PartialEq)]
+pub struct CurveIds<const N: usize>(pub Vec<String>);
+
+impl<'de, const N: usize> Deserialize<'de> for CurveIds<N> {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let ids = name_list(&Value::deserialize(d)?, "curves").map_err(|m| D::Error::custom(whole(m)))?;
+ if ids.len() == N { Ok(CurveIds(ids)) } else { Err(D::Error::custom(whole(format!("`curves` must list {N} curves")))) }
+ }
+}
+
+impl<const N: usize> JsonSchema for CurveIds<N> {
+ fn schema_name() -> Cow<'static, str> {
+ format!("CurveIds{N}").into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ curve_ids_schema(&format!("Exactly {N} curves of the sketch (lines, circles or arcs), by id."), N, N)
+ }
+}
+
+/// Lines, as the centerline and infinite line commands read `curves`: an id or a list of ids, at
+/// least one.
+#[derive(Clone, Debug, PartialEq)]
+pub struct LineIds(pub Vec<String>);
+
+impl<'de> Deserialize<'de> for LineIds {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let ids = name_list(&Value::deserialize(d)?, "curves").map_err(|m| D::Error::custom(whole(m)))?;
+ if ids.is_empty() { Err(D::Error::custom(whole("`curves` must list lines"))) } else { Ok(LineIds(ids)) }
+ }
+}
+
+impl JsonSchema for LineIds {
+ fn schema_name() -> Cow<'static, str> {
+ "LineIds".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ curve_ids_schema("The lines, by id: one id or a list of ids.", 1, params::MAX_STRING_LIST)
+ }
+}
+
+/// `blend_curve`'s `continuity`, as `blend_order` reads it: g1 to g4 in either case, blank for g1.
+#[derive(Clone, Debug, PartialEq)]
+pub struct BlendContinuity(pub String);
+
+impl<'de> Deserialize<'de> for BlendContinuity {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let v = Value::deserialize(d)?;
+ if v.as_str().is_some_and(|s| s.trim().is_empty()) {
+ return Ok(BlendContinuity(String::new()));
+ }
+ params::continuity("", Some(&v), "`continuity`", solidcraft_kernel::Construction::BlendCurve)
+ .map(|g| BlendContinuity(g.as_str().to_string()))
+ .map_err(|e| D::Error::custom(whole(message_of(e))))
+ }
+}
+
+impl JsonSchema for BlendContinuity {
+ fn schema_name() -> Cow<'static, str> {
+ "BlendContinuity".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ let blank = super::types::whitespace_class();
+ json_schema!({
+ "description": "How the blend meets the two curves: g1 (the default, a tangent spline), g2, g3 or g4 (the curvature, its rate and the 4th derivative match too, as one Bézier of degree 5, 7 or 9). Either case; blank is g1.",
+ "type": "string",
+ "pattern": format!("^[{blank}]*([gG][1-4][{blank}]*)?$")
+ })
+ }
+}
+
+/// `periodic`, as `spline` reads it: true or false (`null` too is refused). Only a cubic fit
+/// point spline (`FIT`) can be periodic; the control point splines refuse `true`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Periodic<const FIT: bool>(pub bool);
+
+impl<'de, const FIT: bool> Deserialize<'de> for Periodic<FIT> {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Bool(b) if FIT || !b => Ok(Periodic(b)),
+ Value::Bool(_) => Err(D::Error::custom(whole("periodic mode requires a cubic fit spline"))),
+ _ => Err(D::Error::custom(whole("periodic must be boolean"))),
+ }
+ }
+}
+
+impl<const FIT: bool> JsonSchema for Periodic<FIT> {
+ fn schema_name() -> Cow<'static, str> {
+ if FIT { "PeriodicFit" } else { "PeriodicNever" }.into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ if FIT {
+ json_schema!({"description": "Close the spline smoothly through its points (needs at least 3 distinct points). Default: false.", "type": "boolean"})
+ } else {
+ json_schema!({"description": "Not available for a control point spline: only false is accepted. Default: false.", "type": "boolean", "const": false})
+ }
+ }
+}
+
+/// A spline's points, as `point_list` reads them: 2 to 500 point arguments, snaps included.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SplinePoints(pub Vec<Value>);
+
+impl<'de> Deserialize<'de> for SplinePoints {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let Value::Array(list) = Value::deserialize(d)? else {
+ return Err(D::Error::custom(whole("`points` must be a list")));
+ };
+ if list.len() < 2 || list.len() > solidcraft_sketch::MAX_SPLINE_POINTS {
+ return Err(D::Error::custom(whole("a spline needs 2 to 500 points")));
+ }
+ for v in &list {
+ crate::cmd::point_arg_form(v, true).map_err(|why| D::Error::custom(whole(why)))?;
+ }
+ Ok(SplinePoints(list))
+ }
+}
+
+impl JsonSchema for SplinePoints {
+ fn schema_name() -> Cow<'static, str> {
+ "SplinePoints".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<SnapPoint>();
+ json_schema!({
+ "description": "The spline's points, 2 to 500, each [x, y], a point id or a snap; consecutive points must differ.",
+ "type": "array", "items": point, "minItems": 2, "maxItems": solidcraft_sketch::MAX_SPLINE_POINTS
+ })
+ }
+}
+
+/// Make a line through a midpoint: the line's middle is `mid` and one end is `end`, the other is
+/// the mirror image, held by a midpoint constraint.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = midpoint_required)]
+pub struct MidpointLineParams {
+ // Optional in the type and required in the schema (`midpoint_required`): left out, the handler
+ // refuses it with its own message.
+ /// The line's middle: a point.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SnapPoint")]
+ pub mid: Option<SnapPoint>,
+ /// One end of the line, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub end: Option<PointXY>,
+ /// Make it construction geometry. Default: false.
+ #[serde(default)]
+ pub construction: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn midpoint_required(schema: &mut Schema) {
+ for key in ["mid", "end"] {
+ require(schema, key);
+ }
+}
+
+/// `sketch.arc.tangent`'s `end`: the id of an existing point, or a place [x, y].
+#[derive(Clone, Debug, PartialEq)]
+pub enum ArcEnd {
+ /// The arc ends on this point.
+ Point(String),
+ /// A new point there.
+ At(Vec2),
+}
+
+impl<'de> Deserialize<'de> for ArcEnd {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(id) => Ok(ArcEnd::Point(id)),
+ v => params::vec2(&v).map(ArcEnd::At).ok_or_else(|| D::Error::custom("must be a point [x, y]")),
+ }
+ }
+}
+
+impl JsonSchema for ArcEnd {
+ fn schema_name() -> Cow<'static, str> {
+ "ArcEnd".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let point = generator.subschema_for::<Point2>();
+ json_schema!({
+ "description": "Where the arc ends: [x, y] in mm (a new point), or an existing point's id such as \"l2.start\" (the arc ends on that point).",
+ "anyOf": [point, {"type": "string"}]
+ })
+ }
+}
+
+/// Draw an arc that leaves the end of a line, arc or spline tangent to it, and ends at `end`,
+/// held by a tangent constraint.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = arc_tangent_required)]
+pub struct ArcTangentParams {
+ /// Where the arc starts: the end point of a drawn line, arc or spline, by id (`l1.end`).
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SketchPoint")]
+ pub start: Option<SketchPoint>,
+ /// Where it ends.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ArcEnd")]
+ pub end: Option<ArcEnd>,
+ /// The curve to be tangent to. Default: the first drawn curve that ends at `start`.
+ #[serde(default)]
+ pub curve: Option<String>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn arc_tangent_required(schema: &mut Schema) {
+ for key in ["start", "end"] {
+ require(schema, key);
+ }
+}
+
+/// A diameter, as `sketch.circle.two_tangent` reads it without a `radius`: a finite number.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Diameter(pub f64);
+
+impl<'de> Deserialize<'de> for Diameter {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?.as_f64().and_then(params::finite).map(Diameter).ok_or_else(|| D::Error::custom(whole("needs `radius` or `diameter`")))
+ }
+}
+
+impl JsonSchema for Diameter {
+ fn schema_name() -> Cow<'static, str> {
+ "Diameter".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A diameter in mm.", "type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9})
+ }
+}
+
+/// Draw a circle tangent to two curves, with a radius or a diameter, near a point; the radius is
+/// held by a dimension.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = two_tangent_required)]
+pub struct TwoTangentCircleKeys {
+ /// The radius: a number in mm or a length expression. Wins over `diameter`.
+ #[serde(default)]
+ pub radius: Option<LengthExpr>,
+ /// The diameter in mm, a number; used when there is no `radius`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Diameter")]
+ pub diameter: Option<Diameter>,
+ /// Which of the solutions: the circle whose centre is nearest this point, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub near: Option<PointXY>,
+ /// The two curves, by id: lines, circles or arcs of the sketch.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CurveIds<2>")]
+ pub curves: Option<CurveIds<2>>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn two_tangent_required(schema: &mut Schema) {
+ for key in ["near", "curves"] {
+ require(schema, key);
+ }
+ schema.insert("anyOf".into(), json!([{"required": ["radius"]}, {"required": ["diameter"]}]));
+}
+
+/// `sketch.circle.two_tangent`'s parameters: [`TwoTangentCircleKeys`], with `diameter` left unread
+/// when there is a `radius`, and a `radius` that isn't one left unread otherwise, as the handler
+/// does.
+#[derive(Debug)]
+pub struct TwoTangentCircleParams(pub TwoTangentCircleKeys);
+
+impl<'de> Deserialize<'de> for TwoTangentCircleParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ let radius = params::expr(&value, "radius").is_some();
+ if let Some(keys) = value.as_object_mut() {
+ keys.remove(if radius { "diameter" } else { "radius" });
+ }
+ serde_path_to_error::deserialize(&value).map(TwoTangentCircleParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for TwoTangentCircleParams {
+ fn schema_name() -> Cow<'static, str> {
+ "TwoTangentCircleParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let mut schema = TwoTangentCircleKeys::json_schema(generator);
+ schema.insert("title".into(), "TwoTangentCircleParams".into());
+ schema
+ }
+}
+
+/// Draw a circle tangent to three curves, near a point, held by three tangent constraints.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = three_tangent_required)]
+pub struct ThreeTangentCircleParams {
+ /// Which of the solutions: the circle whose centre is nearest this point, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub near: Option<PointXY>,
+ /// The three curves, by id: lines, circles or arcs of the sketch.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "CurveIds<3>")]
+ pub curves: Option<CurveIds<3>>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn three_tangent_required(schema: &mut Schema) {
+ for key in ["near", "curves"] {
+ require(schema, key);
+ }
+}
+
+/// Draw a slot from its centre and the centre of one end arc; the other end is the mirror
+/// image. Four tangent constraints and an equal one hold it.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = slot_center_required)]
+pub struct SlotCenterPointParams {
+ /// The slot's centre, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub center: Option<PointXY>,
+ /// The centre of one end arc, [x, y] in mm; the other end is its mirror image through `center`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub end: Option<PointXY>,
+ /// The slot's width, in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SlotWidth")]
+ pub width: Option<SlotWidth>,
+ /// Join the new points to the existing points they land on. Default: true.
+ #[serde(default)]
+ pub connect: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn slot_center_required(schema: &mut Schema) {
+ for key in ["center", "end", "width"] {
+ require(schema, key);
+ }
+}
+
+/// Draw a slot along an arc through three points on its centre arc. Returns `centre_arc`: the
+/// construction arc along the slot's middle.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = arc_slot_three_required)]
+pub struct ArcSlotThreePointParams {
+ /// The centre arc's start, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub start: Option<PointXY>,
+ /// A point the centre arc passes through, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub through: Option<PointXY>,
+ /// The centre arc's end, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub end: Option<PointXY>,
+ /// The slot's width, in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SlotWidth")]
+ pub width: Option<SlotWidth>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn arc_slot_three_required(schema: &mut Schema) {
+ for key in ["start", "through", "end", "width"] {
+ require(schema, key);
+ }
+}
+
+/// The sweep of an arc slot, as `sketch.slot.arc_center` reads it: a number of degrees (`null`
+/// is refused).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Sweep(pub f64);
+
+impl<'de> Deserialize<'de> for Sweep {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?.as_f64().and_then(params::finite).map(Sweep).ok_or_else(|| D::Error::custom(whole("`sweep` must be finite degrees")))
+ }
+}
+
+impl JsonSchema for Sweep {
+ fn schema_name() -> Cow<'static, str> {
+ "Sweep".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "The sweep in degrees, counter-clockwise from `start`; the sketch refuses one that is not above 0 and below 360.", "type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9})
+ }
+}
+
+/// Draw a slot along an arc from its centre, the start of its centre arc and its end or sweep.
+/// Returns `centre_arc`: the construction arc along the slot's middle.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = arc_slot_center_required)]
+pub struct ArcSlotCenterKeys {
+ /// The centre of the arcs, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub center: Option<PointXY>,
+ /// The centre arc's start, [x, y] in mm; its distance from `center` is the arc's radius.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub start: Option<PointXY>,
+ /// The slot's width, in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SlotWidth")]
+ pub width: Option<SlotWidth>,
+ /// How far the centre arc turns counter-clockwise, in degrees (0 to 360, not including
+ /// either). Wins over `end`, which is then not read.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Sweep")]
+ pub sweep: Option<Sweep>,
+ /// Without `sweep`: a point in the direction of the centre arc's end from `center` (the arc
+ /// runs counter-clockwise from `start` to it), [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub end: Option<PointXY>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn arc_slot_center_required(schema: &mut Schema) {
+ for key in ["center", "start", "width"] {
+ require(schema, key);
+ }
+ schema.insert("anyOf".into(), json!([{"required": ["sweep"]}, {"required": ["end"]}]));
+}
+
+/// `sketch.slot.arc_center`'s parameters: [`ArcSlotCenterKeys`], with `end` left unread when
+/// `sweep` is there (`null` included), as the handler does.
+#[derive(Debug)]
+pub struct ArcSlotCenterParams(pub ArcSlotCenterKeys);
+
+impl<'de> Deserialize<'de> for ArcSlotCenterParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ if let Some(keys) = value.as_object_mut().filter(|o| o.contains_key("sweep")) {
+ keys.remove("end");
+ }
+ serde_path_to_error::deserialize(&value).map(ArcSlotCenterParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for ArcSlotCenterParams {
+ fn schema_name() -> Cow<'static, str> {
+ "ArcSlotCenterParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let mut schema = ArcSlotCenterKeys::json_schema(generator);
+ schema.insert("title".into(), "ArcSlotCenterParams".into());
+ schema
+ }
+}
+
+/// The minor radius of an ellipse, as `sketch.ellipse` reads it: a number of mm above 0.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct MinorRadius(pub f64);
+
+impl<'de> Deserialize<'de> for MinorRadius {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)?.as_f64().and_then(params::finite) {
+ Some(r) if r > 1e-9 && r < 1e8 => Ok(MinorRadius(r)),
+ _ => Err(D::Error::custom(whole("the minor radius must be positive"))),
+ }
+ }
+}
+
+impl JsonSchema for MinorRadius {
+ fn schema_name() -> Cow<'static, str> {
+ "MinorRadius".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "The minor radius in mm: above 0.000000001 and below 100 000 000.", "type": "number", "exclusiveMinimum": 1e-9, "exclusiveMaximum": 1e8})
+ }
+}
+
+/// The point an ellipse passes through on its minor side, as `sketch.ellipse` reads `minor`
+/// without a `minor_radius`.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct MinorPoint(pub Vec2);
+
+impl<'de> Deserialize<'de> for MinorPoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ params::vec2(&Value::deserialize(d)?).map(MinorPoint).ok_or_else(|| D::Error::custom(whole("needs `minor` [x,y] or `minor_radius`")))
+ }
+}
+
+impl JsonSchema for MinorPoint {
+ fn schema_name() -> Cow<'static, str> {
+ "MinorPoint".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ generator.subschema_for::<Point2>()
+ }
+}
+
+/// `axes`, as `sketch.ellipse` reads it: true or false (`null` is the default).
+fn axes_flag<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
+ nullable(d, |v| match v {
+ Value::Bool(b) => Ok(b),
+ _ => refuse("`axes` must be true or false"),
+ })
+}
+
+/// Draw an ellipse from its centre, the end of its major axis and its minor radius or a point on
+/// its minor side. By default it also gets its major and minor axes as construction lines, held
+/// by midpoint, perpendicular and point-on-curve constraints.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = ellipse_required)]
+pub struct EllipseKeys {
+ /// The ellipse's centre, [x, y] in mm.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub center: Option<PointXY>,
+ /// The end of the major axis, [x, y] in mm; not the centre.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointXY")]
+ pub major: Option<PointXY>,
+ /// The minor radius in mm. Wins over `minor`, which is then not read.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "MinorRadius")]
+ pub minor_radius: Option<MinorRadius>,
+ /// Without `minor_radius`: a point [x, y] in mm the ellipse passes through on its minor side;
+ /// it must lie within the span of the major axis.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "MinorPoint")]
+ pub minor: Option<MinorPoint>,
+ /// Also add the major and minor axes as construction lines. Default: true.
+ #[serde(default, deserialize_with = "axes_flag", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub axes: Option<bool>,
+ /// Make it construction geometry. Default: false.
+ #[serde(default)]
+ pub construction: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn ellipse_required(schema: &mut Schema) {
+ for key in ["center", "major"] {
+ require(schema, key);
+ }
+ schema.insert("anyOf".into(), json!([{"required": ["minor"]}, {"required": ["minor_radius"]}]));
+}
+
+/// `sketch.ellipse`'s parameters: [`EllipseKeys`], with `minor` left unread when there is a
+/// `minor_radius`, and a `minor_radius` that isn't a number left unread, as the handler does.
+#[derive(Debug)]
+pub struct EllipseParams(pub EllipseKeys);
+
+impl<'de> Deserialize<'de> for EllipseParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ let radius = params::num(&value, "minor_radius").is_some();
+ if let Some(keys) = value.as_object_mut() {
+ keys.remove(if radius { "minor" } else { "minor_radius" });
+ }
+ serde_path_to_error::deserialize(&value).map(EllipseParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for EllipseParams {
+ fn schema_name() -> Cow<'static, str> {
+ "EllipseParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let mut schema = EllipseKeys::json_schema(generator);
+ schema.insert("title".into(), "EllipseParams".into());
+ schema
+ }
+}
+
+/// The conic's `rho`, as `sketch.conic` reads it: a number above 0 and below 1 (one of 1e9 or
+/// more in size is ignored, as if left out).
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Rho(pub f64);
+
+impl<'de> Deserialize<'de> for Rho {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Number(n) => match n.as_f64().and_then(params::finite) {
+ Some(r) if r > 1e-6 && r < 1.0 - 1e-6 => Ok(Rho(r)),
+ Some(_) => Err(D::Error::custom(whole("`rho` must be between 0 and 1"))),
+ None => Ok(Rho(0.5)),
+ },
+ _ => Err(D::Error::custom("must be a number between 0 and 1")),
+ }
+ }
+}
+
+impl JsonSchema for Rho {
+ fn schema_name() -> Cow<'static, str> {
+ "Rho".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "How full the curve is: above 0 and below 1. 0.5 is a parabola, less an ellipse, more a hyperbola. A number of 1e9 or more in size is ignored. Default: 0.5.",
+ "type": "number", "exclusiveMinimum": 1e-6, "exclusiveMaximum": 1.0 - 1e-6
+ })
+ }
+}
+
+/// Draw a conic curve from its two ends and the apex where the tangents there meet.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = conic_required)]
+pub struct ConicParams {
+ /// The conic's start: a point.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SnapPoint")]
+ pub start: Option<SnapPoint>,
+ /// The conic's end: a point, not the start.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SnapPoint")]
+ pub end: Option<SnapPoint>,
+ /// The apex, where the tangents at both ends meet: a point, not the start or end.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SnapPoint")]
+ pub apex: Option<SnapPoint>,
+ /// How full the curve is. Default: 0.5 (a parabola).
+ #[serde(default)]
+ pub rho: Option<Rho>,
+ /// Make it construction geometry. Default: false.
+ #[serde(default)]
+ pub construction: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn conic_required(schema: &mut Schema) {
+ for key in ["start", "end", "apex"] {
+ require(schema, key);
+ }
+}
+
+/// Draw a fit point spline: a cubic spline through points, optionally closed (periodic).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = points_required)]
+pub struct FitPointSplineParams {
+ /// The points the spline passes through.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SplinePoints")]
+ pub points: Option<SplinePoints>,
+ /// Close it smoothly through its points. Default: false.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Periodic<true>")]
+ pub periodic: Option<Periodic<true>>,
+ /// Make it construction geometry. Default: false.
+ #[serde(default)]
+ pub construction: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// Draw a control point spline: a cubic one (`sketch.spline.control_point`) or one of degree 5
+/// (`sketch.spline.control_point_5`), shaped by its control points.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = points_required)]
+pub struct ControlPointSplineParams {
+ /// The control points.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SplinePoints")]
+ pub points: Option<SplinePoints>,
+ /// Refused as true: only a cubic fit point spline can be periodic. Default: false.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Periodic<false>")]
+ pub periodic: Option<Periodic<false>>,
+ /// Make it construction geometry. Default: false.
+ #[serde(default)]
+ pub construction: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn points_required(schema: &mut Schema) {
+ require(schema, "points");
+}
+
+/// Join the end points of two curves with a blend curve: a tangent spline (g1), or one Bézier that
+/// also matches the curves' curvature and more (g2 to g4).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = blend_required)]
+pub struct BlendCurveParams {
+ /// The end point of the first curve, by id (`l1.end`).
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SketchPoint")]
+ pub a: Option<SketchPoint>,
+ /// The end point of the second curve, by id (`a2.start`); not the same place as `a`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SketchPoint")]
+ pub b: Option<SketchPoint>,
+ /// g1 (the default), g2, g3 or g4.
+ #[serde(default)]
+ pub continuity: Option<BlendContinuity>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn blend_required(schema: &mut Schema) {
+ for key in ["a", "b"] {
+ require(schema, key);
+ }
+}
+
+/// Make lines centerlines (an axis: not in profiles), or ordinary lines again.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = curves_required)]
+pub struct CenterlineParams {
+ /// The lines, by id.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "LineIds")]
+ pub curves: Option<LineIds>,
+ /// True makes them centerlines, false ordinary lines. Default: each line switches.
+ #[serde(default)]
+ pub value: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// Make lines infinite lines (construction geometry drawn across the whole view through the
+/// line's two points), or ordinary lines again.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = curves_required)]
+pub struct InfiniteLineParams {
+ /// The lines, by id.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "LineIds")]
+ pub curves: Option<LineIds>,
+ /// True makes them infinite, false ordinary lines. Default: each line switches.
+ #[serde(default)]
+ pub value: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn curves_required(schema: &mut Schema) {
+ require(schema, "curves");
+}
+
+/// What the creation commands return: what they made and the sketch's solve.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DrawResult {
+ /// The ids of the curves made.
+ pub curves: Vec<String>,
+ /// The ids of the constraints made.
+ pub constraints: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// What it added: `{points, curves, constraints, dimensions}`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<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 `sketch.slot.arc_three_point` and `sketch.slot.arc_center` return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ArcSlotResult {
+ #[serde(flatten)]
+ pub drawn: DrawResult,
+ /// The id of the construction arc along the slot's middle.
+ pub centre_arc: Option<String>,
+}
+
+/// What `sketch.centerline` and `sketch.infinite` return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct LineTypeResult {
+ /// How many lines were changed.
+ pub changed: usize,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// What it added: `{points, curves, constraints, dimensions}`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<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>,
+}
+
+// ---------------------------------------------------------------------------------------------
+// Sketch text
+
+/// The words of a text, as `text_source` reads `text`: a string that isn't blank, of at most
+/// `MAX_TEXT_CHARS` characters (`null` is as left out).
+fn text_words<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ nullable(d, |v| match v {
+ Value::String(t) if t.trim().is_empty() => refuse("`text` must not be empty"),
+ Value::String(t) if t.chars().count() > solidcraft_sketch::MAX_TEXT_CHARS => refuse("text too long"),
+ Value::String(t) => Ok(t),
+ _ => refuse("`text` must be a string"),
+ })
+}
+
+fn text_words_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string", "pattern": not_blank_pattern(), "maxLength": solidcraft_sketch::MAX_TEXT_CHARS})
+}
+
+fn text_expression<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ nullable(d, |v| match v {
+ Value::String(e) => Ok(e),
+ _ => refuse("`text_expression` must be a string"),
+ })
+}
+
+fn string_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string"})
+}
+
+/// A number of a text, as `text_number` reads it: a finite number, or text that isn't blank (an
+/// expression), at most 4096 bytes.
+fn text_number_form(v: &Value) -> bool {
+ match v {
+ Value::Number(n) => n.as_f64().and_then(params::finite).is_some(),
+ Value::String(e) => !e.trim().is_empty() && e.len() <= 4096,
+ _ => false,
+ }
+}
+
+/// A text's `at`: `[x, y]` with each a number or an expression, or `{x, y}` of numbers.
+fn text_at<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {
+ nullable(d, |v| {
+ let ok = match &v {
+ Value::Array(a) => matches!(a.as_slice(), [x, y] if text_number_form(x) && text_number_form(y)),
+ other => params::vec2(other).is_some(),
+ };
+ if ok { Ok(v) } else { refuse(crate::cmd::AT_MUST) }
+ })
+}
+
+fn text_at_schema(generator: &mut SchemaGenerator) -> Schema {
+ let coordinate = generator.subschema_for::<LengthExpr>();
+ let point = generator.subschema_for::<Point2>();
+ json_schema!({
+ "anyOf": [{"type": "array", "items": coordinate, "minItems": 2, "maxItems": 2}, point]
+ })
+}
+
+fn expression_string() -> Value {
+ json!({"type": "string", "minLength": 1, "maxLength": 4096, "pattern": not_blank_pattern()})
+}
+
+/// A text's `height`: a number of mm above 0 and below 1e5, or an expression.
+fn text_height<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {
+ nullable(d, |v| {
+ if !text_number_form(&v) {
+ return refuse("`height` must be a length in mm, or an expression");
+ }
+ match v.as_f64() {
+ Some(h) if !(h > 1e-6 && h < 1e5) => refuse("`height` must be positive"),
+ _ => Ok(v),
+ }
+ })
+}
+
+fn text_height_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"anyOf": [{"type": "number", "exclusiveMinimum": 1e-6, "exclusiveMaximum": 1e5}, expression_string()]})
+}
+
+/// A text's `angle`: a number of degrees, or an expression.
+fn text_angle<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Value>, D::Error> {
+ nullable(d, |v| if text_number_form(&v) { Ok(v) } else { refuse("`angle` must be an angle in degrees, or an expression") })
+}
+
+fn text_angle_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"anyOf": [{"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9}, expression_string()]})
+}
+
+fn text_font<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ nullable(d, |v| match v {
+ Value::String(f) => Ok(f),
+ _ => refuse("`font` must be a font family name or a font file path"),
+ })
+}
+
+macro_rules! text_flag {
+ ($name:ident, $key:literal) => {
+ fn $name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
+ nullable(d, |v| match v {
+ Value::Bool(b) => Ok(b),
+ _ => refuse(concat!("`", $key, "` must be true or false")),
+ })
+ }
+ };
+}
+
+text_flag!(text_bold, "bold");
+text_flag!(text_italic, "italic");
+text_flag!(text_reverse, "reverse");
+
+fn text_align<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ nullable(d, |v| match v {
+ Value::String(a) if matches!(a.trim().to_ascii_lowercase().as_str(), "left" | "center" | "centre" | "right") => Ok(a),
+ _ => refuse("`align` must be left, center or right"),
+ })
+}
+
+/// A pattern for one of the words, whatever its case, with blanks around it.
+fn word_pattern(words: &[&str]) -> String {
+ let blank = super::types::whitespace_class();
+ let case = |w: &str| w.chars().map(|c| format!("[{}{}]", c.to_ascii_uppercase(), c)).collect::<String>();
+ format!("^[{blank}]*({})[{blank}]*$", words.iter().map(|w| case(w)).collect::<Vec<_>>().join("|"))
+}
+
+fn text_align_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string", "pattern": word_pattern(&["left", "center", "centre", "right"])})
+}
+
+fn text_letter_spacing<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
+ nullable(d, |v| v.as_f64().and_then(params::finite).map_or_else(|| refuse("`letter_spacing` must be a length in mm"), Ok))
+}
+
+fn text_letter_spacing_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9})
+}
+
+fn text_line_spacing<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
+ nullable(d, |v| v.as_f64().and_then(params::finite).filter(|s| *s > 0.0).map_or_else(|| refuse("`line_spacing` must be a positive factor"), Ok))
+}
+
+fn text_line_spacing_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "number", "exclusiveMinimum": 0, "exclusiveMaximum": 1e9})
+}
+
+fn text_path<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ nullable(d, |v| match v {
+ Value::String(c) => Ok(c),
+ _ => refuse("`path` must be a curve id"),
+ })
+}
+
+/// What a text is, as `sketch.text` and `sketch.edit_text` read it (`null` is as left out for
+/// each).
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct TextKeys {
+ /// The words, at most 4096 characters, `\n` breaking lines; not blank. Not with
+ /// `text_expression`. When editing, kept when left out.
+ #[serde(default, deserialize_with = "text_words", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_words_schema")]
+ pub text: Option<String>,
+ /// The words built from text parameters (`parameters.add` with unit text), number parameters
+ /// and quoted texts joined by `+` (`"Label + '-L'"`, `"'W' + Width"`; `number(Width, 2)` is
+ /// a number with 2 decimals). The text keeps it and follows the parameters; the reply's
+ /// `exprs` returns it as `text`. Not with `text`. When editing, typed words replace it.
+ #[serde(default, deserialize_with = "text_expression", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub text_expression: Option<String>,
+ /// The baseline start, [x, y] in mm, or {x, y}; in `[x, y]` each is a number or an expression
+ /// over the design's parameters as a string (`"plate_width / 2"`), which the text keeps and
+ /// follows. Needed to make a text; when editing, kept when left out (and moving a text
+ /// replaces its expressions with numbers). Does not place a text on a `path`.
+ #[serde(default, deserialize_with = "text_at", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_at_schema")]
+ pub at: Option<Value>,
+ /// The capital height in mm (above 0, below 100 000), a number or an expression over the
+ /// design's parameters. Default: 5. When editing, kept when left out.
+ #[serde(default, deserialize_with = "text_height", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_height_schema")]
+ pub height: Option<Value>,
+ /// The direction of the baseline, counter-clockwise from sketch X: a number of degrees or an
+ /// expression. Default: 0. When editing, kept when left out. Does not turn a text on a `path`.
+ #[serde(default, deserialize_with = "text_angle", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_angle_schema")]
+ pub angle: Option<Value>,
+ /// An installed font's family or full name, or a .ttf or .otf file path (`~` and `%VAR%`
+ /// expand); empty: the built-in Liberation Sans. Default: the built-in font. When editing,
+ /// kept when left out.
+ #[serde(default, deserialize_with = "text_font", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub font: Option<String>,
+ /// An installed family's bold face. Default: false. When editing, kept when left out.
+ #[serde(default, deserialize_with = "text_bold", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub bold: Option<bool>,
+ /// An installed family's italic face (without one, the text is slanted). Default: false. When
+ /// editing, kept when left out.
+ #[serde(default, deserialize_with = "text_italic", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub italic: Option<bool>,
+ /// Run the text the other way along its `path`. Default: false. When editing, kept when left
+ /// out.
+ #[serde(default, deserialize_with = "text_reverse", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub reverse: Option<bool>,
+ /// The lines against `at`, or along the path: left, center (or centre) or right, either case.
+ /// Default: left. When editing, kept when left out.
+ #[serde(default, deserialize_with = "text_align", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_align_schema")]
+ pub align: Option<String>,
+ /// Extra space between letters, in mm. Default: 0. When editing, kept when left out.
+ #[serde(default, deserialize_with = "text_letter_spacing", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_letter_spacing_schema")]
+ pub letter_spacing: Option<f64>,
+ /// The line distance as a multiple of the font's (above 0). Default: 1. When editing, kept
+ /// when left out.
+ #[serde(default, deserialize_with = "text_line_spacing", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "text_line_spacing_schema")]
+ pub line_spacing: Option<f64>,
+ /// A curve id of the sketch the baseline follows; empty: none. `at` and `angle` then do not
+ /// place the text, and the curve becomes construction, a guide the letters stand on. When
+ /// editing, kept when left out.
+ #[serde(default, deserialize_with = "text_path", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "string_schema")]
+ pub path: Option<String>,
+}
+
+/// The text keys of `value`, with the handler's messages: `text` and `text_expression` together
+/// are refused first, as `text_source` does before it reads either.
+fn read_text_keys<E: serde::de::Error>(value: &Value) -> Result<TextKeys, E> {
+ let given = |k: &str| value.get(k).is_some_and(|v| !v.is_null());
+ if given("text") && given("text_expression") {
+ return Err(E::custom(whole("give `text` or `text_expression`, not both")));
+ }
+ serde_path_to_error::deserialize(value).map_err(|e| E::custom(located(&e)))
+}
+
+/// Make text in the sketch being edited: outlines that stay linked to their words and style, so a
+/// later `sketch.edit_text` can change them. Give `text` or `text_expression`, and `at`.
+#[derive(Debug)]
+pub struct SketchTextParams(pub TextKeys);
+
+impl<'de> Deserialize<'de> for SketchTextParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let value = Value::deserialize(d)?;
+ // First, as the handler does.
+ if value.get("at").is_none_or(Value::is_null) {
+ return Err(D::Error::custom(whole(crate::cmd::AT_MUST)));
+ }
+ read_text_keys(&value).map(SketchTextParams)
+ }
+}
+
+impl JsonSchema for SketchTextParams {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchTextParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let mut schema = TextKeys::json_schema(generator);
+ schema.insert("title".into(), "SketchTextParams".into());
+ schema.insert(
+ "description".into(),
+ "Make text in the sketch being edited: outlines that stay linked to their words and style, so a later sketch.edit_text can change them. Give `text` or `text_expression`, and `at`."
+ .into(),
+ );
+ add_properties(&mut schema, sketch_property());
+ require(&mut schema, "at");
+ schema.insert("anyOf".into(), json!([{"required": ["text"]}, {"required": ["text_expression"]}]));
+ schema
+ }
+}
+
+/// One text of `sketch.edit_text`: its link or one of its curves (`entity`), and the keys that
+/// change.
+#[derive(Debug)]
+pub struct TextEdit {
+ /// The text's link id.
+ pub link: Option<String>,
+ /// One of its curves, used when there is no `link`.
+ pub entity: Option<String>,
+ /// What changes.
+ pub keys: TextKeys,
+}
+
+impl<'de> Deserialize<'de> for TextEdit {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let value = Value::deserialize(d)?;
+ // `str_` reads a key that isn't text as left out.
+ let name = |k: &str| value.get(k).and_then(Value::as_str).map(str::to_string);
+ let (link, entity) = (name("link"), name("entity"));
+ if link.is_none() && entity.is_none() {
+ return Err(D::Error::custom(whole("give `link` or `entity`")));
+ }
+ Ok(TextEdit { link, entity, keys: read_text_keys(&value)? })
+ }
+}
+
+/// The texts go into the sketch being edited whatever `sketch` says; the session reads it only to
+/// report what the call `created`, so a call that names it still runs without a warning.
+fn sketch_property() -> Value {
+ json!({"sketch": {"description": "Only for the reply's `created`, which compares this sketch (default: the one being edited); the text always goes into the sketch being edited.", "type": ["integer", "string"]}})
+}
+
+fn edit_target_properties() -> Value {
+ json!({
+ "link": {"description": "The text's link id (the `link` the text's reply names).", "type": "string"},
+ "entity": {"description": "One of the text's curves, by id, when there is no `link`.", "type": "string"}
+ })
+}
+
+impl JsonSchema for TextEdit {
+ fn schema_name() -> Cow<'static, str> {
+ "TextEdit".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let mut schema = TextKeys::json_schema(generator);
+ schema.insert("title".into(), "TextEdit".into());
+ schema.insert("description".into(), "One text's change: the text by `link` or `entity`, and the keys to change; the rest is kept.".into());
+ add_properties(&mut schema, edit_target_properties());
+ schema.insert("anyOf".into(), json!([{"required": ["link"]}, {"required": ["entity"]}]));
+ schema
+ }
+}
+
+/// Change texts: one by `link` (or `entity`, one of its curves) with the keys to change, or
+/// several at once by `edits`, the design rebuilt once, all or nothing. What is left out stays; a
+/// number replaces an expression, and so does moving the text. With `edits`, the other keys of the
+/// call (but `live`) are not read.
+#[derive(Debug)]
+pub struct EditTextParams {
+ /// The several texts, when the call gives `edits`.
+ pub edits: Option<Vec<TextEdit>>,
+ /// The one text, when it does not.
+ pub single: Option<TextEdit>,
+ /// One frame of an interactive change.
+ pub live: Option<bool>,
+}
+
+impl<'de> Deserialize<'de> for EditTextParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let value = Value::deserialize(d)?;
+ // `live` takes effect only as `true`; anything else but a flag is a mistake.
+ let live = match value.get("live") {
+ None | Some(Value::Null) => None,
+ Some(Value::Bool(b)) => Some(*b),
+ Some(_) => return Err(D::Error::custom(whole("`live` must be true or false"))),
+ };
+ match value.get("edits") {
+ None | Some(Value::Null) => {
+ let single = TextEdit::deserialize(&value).map_err(|e| D::Error::custom(e.to_string()))?;
+ Ok(EditTextParams { edits: None, single: Some(single), live })
+ }
+ Some(Value::Array(edits)) => {
+ if edits.is_empty() || edits.len() > crate::cmd::MAX_TEXT_EDITS {
+ return Err(D::Error::custom(whole(format!("`edits` must hold 1 to {} edits", crate::cmd::MAX_TEXT_EDITS))));
+ }
+ let edits = edits
+ .iter()
+ .map(|e| serde_path_to_error::deserialize::<_, TextEdit>(e).map_err(|e| D::Error::custom(whole(parse_issue(&e).message))))
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(EditTextParams { edits: Some(edits), single: None, live })
+ }
+ Some(_) => Err(D::Error::custom(whole("`edits` must be a list of edits"))),
+ }
+ }
+}
+
+impl JsonSchema for EditTextParams {
+ fn schema_name() -> Cow<'static, str> {
+ "EditTextParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let item = generator.subschema_for::<TextEdit>();
+ let mut schema = TextKeys::json_schema(generator);
+ schema.insert("title".into(), "EditTextParams".into());
+ schema.insert(
+ "description".into(),
+ "Change texts: one by `link` (or `entity`, one of its curves) with the keys to change, or several at once by `edits`, the design rebuilt once, all or nothing. What is left out stays; a number replaces an expression, and so does moving the text. With `edits`, the other keys of the call (but `live`) are not read."
+ .into(),
+ );
+ add_properties(&mut schema, edit_target_properties());
+ add_properties(&mut schema, sketch_property());
+ add_properties(
+ &mut schema,
+ json!({
+ "edits": {"description": "Several texts changed together: each is `link` or `entity` with the keys to change.", "type": "array", "items": item, "minItems": 1, "maxItems": crate::cmd::MAX_TEXT_EDITS},
+ "live": {"description": "One frame of an interactive change: the sketch is solved and shown, the features after it stay as they were until `sketch.drag_end`. A call with `live: true` is not checked against this schema yet.", "type": "boolean"}
+ }),
+ );
+ schema.insert("anyOf".into(), json!([{"required": ["link"]}, {"required": ["entity"]}, {"required": ["edits"]}]));
+ schema
+ }
+}
+
+/// The expressions behind a text's numbers and words.
+#[derive(Debug, Default, Serialize, JsonSchema)]
+pub struct TextExpressions {
+ /// `at`'s x.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub x: Option<String>,
+ /// `at`'s y.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub y: Option<String>,
+ /// The height.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub height: Option<String>,
+ /// The angle.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub angle: Option<String>,
+ /// The words (`text_expression`).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub text: Option<String>,
+}
+
+/// One text made or changed.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct TextChange {
+ /// The text's link id.
+ pub link: String,
+ /// The ids of its curves.
+ pub curves: Vec<String>,
+ /// The curve the text follows that became construction, a guide the letters stand on; null
+ /// when none did.
+ pub guide: Option<String>,
+ /// The expressions the text keeps; absent when it keeps none.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub exprs: Option<TextExpressions>,
+}
+
+/// What `sketch.text` returns, and `sketch.edit_text` for one text.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct TextResult {
+ #[serde(flatten)]
+ pub change: TextChange,
+ /// What it added: `{points, curves, constraints, dimensions}`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<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 `sketch.edit_text` returns for `edits`.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct TextEditsResult {
+ /// Each edit's result, in order.
+ pub edits: Vec<TextChange>,
+ /// What it added: `{points, curves, constraints, dimensions}`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub created: Option<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 `sketch.edit_text` returns: one text's result, or each edit's.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum EditTextResult {
+ One(TextResult),
+ Many(TextEditsResult),
+}
+
#[cfg(test)]
#[path = "sketch_create_tests.rs"]
mod tests;
diff --git a/crates/engine/src/schema/sketch_create_tests.rs b/crates/engine/src/schema/sketch_create_tests.rs
index bea64f7616..00cc4f6089 100644
--- a/crates/engine/src/schema/sketch_create_tests.rs
+++ b/crates/engine/src/schema/sketch_create_tests.rs
@@ -1,6 +1,11 @@
-use serde_json::json;
+use serde_json::{Value, json};
-use super::{SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams, SplineReverseResult};
+use super::{
+ ArcSlotCenterParams, ArcSlotResult, ArcSlotThreePointParams, ArcTangentParams, BlendCurveParams, CenterlineParams, ConicParams,
+ ControlPointSplineParams, DrawResult, EditTextParams, EditTextResult, EllipseParams, FitPointSplineParams, InfiniteLineParams, LineTypeResult,
+ MidpointLineParams, SketchTextParams, SlotCenterPointParams, SplineRemovePointParams, SplineRemovePointResult, SplineReverseParams,
+ SplineReverseResult, TextResult, ThreeTangentCircleParams, TwoTangentCircleParams,
+};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
@@ -81,3 +86,825 @@ fn construction_line_contracts_and_replies_match() {
}
assert!(s.execute("sketch.construction_line", &json!({"at":[0,0],"mode":"unknown"})).is_err());
}
+
+// ---------------------------------------------------------------------------------------------
+// The creation commands (#12550)
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+/// A session at `level` editing a sketch with two lines meeting at (40, 0), a circle and a text.
+fn drawing(level: ParamCheck) -> Session {
+ let mut s = Session { param_check: level, ..Session::default() };
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
+ run(&mut s, "sketch.line", json!({"points": [[40, 0], [40, 30]]}));
+ run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 4}));
+ run(&mut s, "sketch.text", json!({"text": "Hi", "at": [0, 40]}));
+ s
+}
+
+/// The link of the text `drawing` makes.
+fn text_link() -> String {
+ let mut s = Session::default();
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [40, 0]]}));
+ run(&mut s, "sketch.line", json!({"points": [[40, 0], [40, 30]]}));
+ run(&mut s, "sketch.circle.center", json!({"center": [10, 10], "radius": 4}));
+ run(&mut s, "sketch.text", json!({"text": "Hi", "at": [0, 40]}))["link"].as_str().unwrap_or_default().to_string()
+}
+
+/// Like `assert_strict_keeps_todays_errors`, in a sketch being edited: the calls whose refusal
+/// depends on the design (a point or curve that isn't there), or that the handler reaches only
+/// after it has found its sketch.
+fn assert_strict_keeps_todays_errors_in_a_sketch(cases: &[(&str, Value)]) {
+ for (id, p) in cases {
+ let error = |level: ParamCheck| drawing(level).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}");
+ }
+}
+
+fn matches(schema: schemars::Schema, r: &Value) {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
+}
+
+fn issues(id: &str, p: Value) -> Vec<String> {
+ crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect()
+}
+
+#[test]
+fn creation_schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<MidpointLineParams>(), &["construction", "end", "mid", "sketch"]);
+ assert_keys(input_schema_for::<ArcTangentParams>(), &["curve", "end", "sketch", "start"]);
+ assert_keys(input_schema_for::<TwoTangentCircleParams>(), &["curves", "diameter", "near", "radius", "sketch"]);
+ assert_keys(input_schema_for::<ThreeTangentCircleParams>(), &["curves", "near", "sketch"]);
+ assert_keys(input_schema_for::<SlotCenterPointParams>(), &["center", "connect", "end", "sketch", "width"]);
+ assert_keys(input_schema_for::<ArcSlotThreePointParams>(), &["end", "sketch", "start", "through", "width"]);
+ assert_keys(input_schema_for::<ArcSlotCenterParams>(), &["center", "end", "sketch", "start", "sweep", "width"]);
+ assert_keys(input_schema_for::<EllipseParams>(), &["axes", "center", "construction", "major", "minor", "minor_radius", "sketch"]);
+ assert_keys(input_schema_for::<FitPointSplineParams>(), &["construction", "periodic", "points", "sketch"]);
+ assert_keys(input_schema_for::<ControlPointSplineParams>(), &["construction", "periodic", "points", "sketch"]);
+ assert_keys(input_schema_for::<ConicParams>(), &["apex", "construction", "end", "rho", "sketch", "start"]);
+ assert_keys(input_schema_for::<BlendCurveParams>(), &["a", "b", "continuity", "sketch"]);
+ assert_keys(input_schema_for::<CenterlineParams>(), &["curves", "sketch", "value"]);
+ assert_keys(input_schema_for::<InfiniteLineParams>(), &["curves", "sketch", "value"]);
+ // The texts go into the sketch being edited; `sketch` only picks what `created` compares.
+ assert_keys(
+ input_schema_for::<SketchTextParams>(),
+ &[
+ "align",
+ "angle",
+ "at",
+ "bold",
+ "font",
+ "height",
+ "italic",
+ "letter_spacing",
+ "line_spacing",
+ "path",
+ "reverse",
+ "sketch",
+ "text",
+ "text_expression",
+ ],
+ );
+ assert_keys(
+ input_schema_for::<EditTextParams>(),
+ &[
+ "align",
+ "angle",
+ "at",
+ "bold",
+ "edits",
+ "entity",
+ "font",
+ "height",
+ "italic",
+ "letter_spacing",
+ "line_spacing",
+ "link",
+ "live",
+ "path",
+ "reverse",
+ "sketch",
+ "text",
+ "text_expression",
+ ],
+ );
+ // Every command has a contract and an output schema, and the edit's items too.
+ for id in [
+ "sketch.arc.tangent",
+ "sketch.blend_curve",
+ "sketch.centerline",
+ "sketch.circle.three_tangent",
+ "sketch.circle.two_tangent",
+ "sketch.conic",
+ "sketch.edit_text",
+ "sketch.ellipse",
+ "sketch.infinite",
+ "sketch.line.midpoint",
+ "sketch.slot.arc_center",
+ "sketch.slot.arc_three_point",
+ "sketch.slot.center_point",
+ "sketch.spline.control_point",
+ "sketch.spline.control_point_5",
+ "sketch.spline.fit_point",
+ "sketch.text",
+ ] {
+ let c = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));
+ assert!(c.contract.is_some() && c.output.is_some(), "{id}");
+ }
+ assert_eq!(solidcraft_sketch::MAX_SPLINE_POINTS, 500, "the handler's message and the type's say 500");
+}
+
+/// The calls the handlers refuse before they look at a sketch: strict gives their messages.
+#[test]
+fn strict_keeps_todays_errors_before_the_sketch() {
+ let long = "x".repeat(solidcraft_sketch::MAX_TEXT_CHARS + 1);
+ let at = json!([0, 0]);
+ assert_strict_keeps_todays_errors(&[
+ ("sketch.line.midpoint", json!({})),
+ ("sketch.line.midpoint", json!({"mid": [1, 1]})),
+ ("sketch.line.midpoint", json!({"mid": [1, 1], "end": 5})),
+ ("sketch.line.midpoint", json!({"mid": [1, 1], "end": null})),
+ ("sketch.line.midpoint", json!({"mid": [1, 1], "end": [1]})),
+ ("sketch.arc.tangent", json!({"start": "l1.end"})),
+ ("sketch.arc.tangent", json!({"start": "l1.end", "end": true})),
+ ("sketch.arc.tangent", json!({"start": "l1.end", "end": null})),
+ ("sketch.circle.two_tangent", json!({})),
+ ("sketch.circle.two_tangent", json!({"radius": true})),
+ ("sketch.circle.two_tangent", json!({"radius": " "})),
+ ("sketch.circle.two_tangent", json!({"diameter": "5"})),
+ ("sketch.circle.two_tangent", json!({"radius": 5})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": "x"})),
+ ("sketch.circle.two_tangent", json!({"diameter": 5, "near": null})),
+ ("sketch.circle.three_tangent", json!({})),
+ ("sketch.circle.three_tangent", json!({"near": [1]})),
+ ("sketch.slot.center_point", json!({})),
+ ("sketch.slot.center_point", json!({"center": [0, 0]})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0]})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": 0})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": -2})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": "2"})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": null})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [5], "width": 2})),
+ ("sketch.slot.arc_three_point", json!({})),
+ ("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1]})),
+ ("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1], "end": [2, 0]})),
+ ("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1], "end": [2, 0], "width": 0})),
+ ("sketch.slot.arc_center", json!({})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0]})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "end": true})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": "x"})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": null})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": 1e9})),
+ ("sketch.ellipse", json!({})),
+ ("sketch.ellipse", json!({"center": [0, 0]})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0]})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": true})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": [1]})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 0})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": -3})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 1e8})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": "3"})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 3, "axes": "yes"})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": [1, 1], "axes": 0})),
+ ("sketch.conic", json!({"rho": 0})),
+ ("sketch.conic", json!({"rho": 1})),
+ ("sketch.conic", json!({"rho": -2})),
+ ("sketch.conic", json!({"rho": 1e-7})),
+ ("sketch.spline.fit_point", json!({"periodic": "yes"})),
+ ("sketch.spline.fit_point", json!({"periodic": null})),
+ ("sketch.spline.fit_point", json!({"periodic": 1, "points": [[0, 0], [1, 1]]})),
+ ("sketch.spline.control_point", json!({"periodic": true, "points": [[0, 0], [1, 1]]})),
+ ("sketch.spline.control_point", json!({"periodic": null})),
+ ("sketch.spline.control_point_5", json!({"periodic": true})),
+ ("sketch.blend_curve", json!({"continuity": "g9"})),
+ ("sketch.blend_curve", json!({"continuity": "g0"})),
+ ("sketch.blend_curve", json!({"continuity": 5})),
+ ("sketch.blend_curve", json!({"continuity": true})),
+ ("sketch.centerline", json!({})),
+ ("sketch.centerline", json!({"curves": []})),
+ ("sketch.centerline", json!({"curves": null})),
+ ("sketch.centerline", json!({"curves": 5})),
+ ("sketch.centerline", json!({"curves": [1]})),
+ ("sketch.centerline", json!({"curves": ["l1", true]})),
+ ("sketch.infinite", json!({})),
+ ("sketch.infinite", json!({"curves": []})),
+ ("sketch.infinite", json!({"curves": {"a": 1}})),
+ ("sketch.text", json!({})),
+ ("sketch.text", json!({"at": null})),
+ ("sketch.text", json!({"at": [1], "text": "x"})),
+ ("sketch.text", json!({"at": [1, 2, 3], "text": "x"})),
+ ("sketch.text", json!({"at": "x", "text": "x"})),
+ ("sketch.text", json!({"at": [1, true], "text": "x"})),
+ ("sketch.text", json!({"at": ["", 1], "text": "x"})),
+ ("sketch.text", json!({"at": {"x": "w", "y": 1}, "text": "x"})),
+ ("sketch.text", json!({"at": ["no_such_parameter", 1], "text": "x"})),
+ ("sketch.text", json!({"at": at})),
+ ("sketch.text", json!({"at": at, "text": ""})),
+ ("sketch.text", json!({"at": at, "text": " \n "})),
+ ("sketch.text", json!({"at": at, "text": 5})),
+ ("sketch.text", json!({"at": at, "text": long})),
+ ("sketch.text", json!({"at": at, "text_expression": 5})),
+ ("sketch.text", json!({"at": at, "text": "x", "text_expression": "'y'"})),
+ ("sketch.text", json!({"at": at, "text": 5, "text_expression": 6})),
+ ("sketch.text", json!({"at": at, "text": "x", "height": 0})),
+ ("sketch.text", json!({"at": at, "text": "x", "height": 1e5})),
+ ("sketch.text", json!({"at": at, "text": "x", "height": true})),
+ ("sketch.text", json!({"at": at, "text": "x", "height": " "})),
+ ("sketch.text", json!({"at": at, "text": "x", "height": "no_such_parameter"})),
+ ("sketch.text", json!({"at": at, "text": "x", "angle": []})),
+ ("sketch.text", json!({"at": at, "text": "x", "angle": 1e9})),
+ ("sketch.text", json!({"at": at, "text": "x", "font": 5})),
+ ("sketch.text", json!({"at": at, "text": "x", "font": "No Such Font Family 12345"})),
+ ("sketch.text", json!({"at": at, "text": "x", "bold": "yes"})),
+ ("sketch.text", json!({"at": at, "text": "x", "italic": 1})),
+ ("sketch.text", json!({"at": at, "text": "x", "reverse": []})),
+ ("sketch.text", json!({"at": at, "text": "x", "align": "up"})),
+ ("sketch.text", json!({"at": at, "text": "x", "align": 5})),
+ ("sketch.text", json!({"at": at, "text": "x", "letter_spacing": "wide"})),
+ ("sketch.text", json!({"at": at, "text": "x", "line_spacing": 0})),
+ ("sketch.text", json!({"at": at, "text": "x", "line_spacing": "2"})),
+ ("sketch.text", json!({"at": at, "text": "x", "path": 5})),
+ ]);
+}
+
+/// The calls that need the design to be refused, or that the handlers refuse once they have
+/// found their sketch: strict gives their messages.
+#[test]
+fn strict_keeps_todays_errors_in_a_sketch() {
+ let at = json!([0, 0]);
+ // The text `drawing` made.
+ let t = text_link();
+ assert_strict_keeps_todays_errors_in_a_sketch(&[
+ ("sketch.line.midpoint", json!({"end": [1, 1]})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": null})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": 5})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": [1]})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": [1, true]})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": ["", 1]})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": ["no_such_parameter", 1]})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": {"ref": 5}})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": {"vertex": [1, 2]}})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": "no_such_point"})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": [1, 1]})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": [3, 3], "sketch": true})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": [3, 3], "sketch": -1})),
+ ("sketch.line.midpoint", json!({"end": [1, 1], "mid": [3, 3], "sketch": 4096})),
+ ("sketch.arc.tangent", json!({"end": [1, 1]})),
+ ("sketch.arc.tangent", json!({"end": [1, 1], "start": null})),
+ ("sketch.arc.tangent", json!({"end": [1, 1], "start": 5})),
+ ("sketch.arc.tangent", json!({"end": [1, 1], "start": {"at": 5}})),
+ ("sketch.arc.tangent", json!({"end": [1, 1], "start": "on:l1:5,0"})),
+ ("sketch.arc.tangent", json!({"end": "no_such_point", "start": "l1.end"})),
+ ("sketch.arc.tangent", json!({"end": [50, 20], "start": "l1.end", "curve": "no_such_curve"})),
+ ("sketch.arc.tangent", json!({"end": [50, 0], "start": "l1.end"})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10]})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": null})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1"]})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": 5})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": [1, 2]})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1", true]})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1", "l1", "l2"]})),
+ ("sketch.circle.two_tangent", json!({"radius": 5, "near": [20, 10], "curves": ["l1", "no_such_curve"]})),
+ ("sketch.circle.two_tangent", json!({"radius": "no_such_parameter", "near": [20, 10], "curves": ["l1", "l2"]})),
+ ("sketch.circle.two_tangent", json!({"radius": 0, "near": [20, 10], "curves": ["l1", "l2"]})),
+ ("sketch.circle.three_tangent", json!({"near": [20, 10]})),
+ ("sketch.circle.three_tangent", json!({"near": [20, 10], "curves": ["l1", "l2"]})),
+ ("sketch.circle.three_tangent", json!({"near": [20, 10], "curves": {}})),
+ ("sketch.circle.three_tangent", json!({"near": [20, 10], "curves": ["l1", "l2", "no_such_curve"]})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [0, 0], "width": 2})),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [5, 0], "width": 2, "sketch": [1]})),
+ ("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 0], "end": [2, 0], "width": 1})),
+ ("sketch.slot.arc_three_point", json!({"start": [0, 0], "through": [1, 1], "end": [2, 0], "width": 30})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [0, 0], "width": 1, "sweep": 90})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": 0})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1})),
+ ("sketch.slot.arc_center", json!({"center": [0, 0], "start": [5, 0], "width": 1, "end": [0, 0]})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [0, 0], "minor_radius": 3})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor": [20, 0]})),
+ ("sketch.ellipse", json!({"center": [0, 0], "major": [10, 0], "minor_radius": 3, "sketch": 4096})),
+ ("sketch.conic", json!({"end": [2, 0], "apex": [1, 1]})),
+ ("sketch.conic", json!({"start": null, "end": [2, 0], "apex": [1, 1]})),
+ ("sketch.conic", json!({"start": [0, 0], "end": 5, "apex": [1, 1]})),
+ ("sketch.conic", json!({"start": [0, 0], "end": [2, 0]})),
+ ("sketch.conic", json!({"start": "l1.start", "end": "l1.start", "apex": [1, 1]})),
+ ("sketch.conic", json!({"start": [0, 0], "end": [2, 0], "apex": "no_such_point"})),
+ ("sketch.conic", json!({"start": [0, 0], "end": [2, 0], "apex": "x:l1+l1:1,1"})),
+ ("sketch.spline.fit_point", json!({})),
+ ("sketch.spline.fit_point", json!({"points": 5})),
+ ("sketch.spline.fit_point", json!({"points": null})),
+ ("sketch.spline.fit_point", json!({"points": [[0, 0]]})),
+ ("sketch.spline.fit_point", json!({"points": vec![json!([0, 1]); 501]})),
+ ("sketch.spline.fit_point", json!({"points": [[0, 0], 5]})),
+ ("sketch.spline.fit_point", json!({"points": [[0, 0], [1, 1], {"at": "x"}]})),
+ ("sketch.spline.fit_point", json!({"points": [[0, 0], [0, 0]]})),
+ ("sketch.spline.fit_point", json!({"points": [[0, 0], [1, 1]], "sketch": true})),
+ ("sketch.spline.control_point", json!({"points": [[0, 0], "no_such_point"]})),
+ ("sketch.spline.control_point_5", json!({"points": [[0, 0], [1, 1], ["", 3]]})),
+ ("sketch.blend_curve", json!({"b": "l2.end"})),
+ ("sketch.blend_curve", json!({"a": "l1.end"})),
+ ("sketch.blend_curve", json!({"a": null, "b": "l2.end"})),
+ ("sketch.blend_curve", json!({"a": "l1.end", "b": 5})),
+ ("sketch.blend_curve", json!({"a": "l1.end", "b": "l1.end"})),
+ ("sketch.blend_curve", json!({"a": [1, 1], "b": "l2.end"})),
+ ("sketch.blend_curve", json!({"a": "no_such_point", "b": "l2.end"})),
+ ("sketch.blend_curve", json!({"a": "l1.end", "b": "l2.end", "continuity": "g5"})),
+ ("sketch.centerline", json!({"curves": ["no_such_curve"]})),
+ ("sketch.centerline", json!({"curves": ["c1"]})),
+ ("sketch.infinite", json!({"curves": ["l1", "c1"]})),
+ ("sketch.infinite", json!({"curves": ["no_such_curve"]})),
+ ("sketch.text", json!({"at": at, "text": "x", "path": "no_such_curve"})),
+ ("sketch.text", json!({"at": at, "text": "x", "path": t})),
+ ("sketch.edit_text", json!({})),
+ ("sketch.edit_text", json!({"link": 5})),
+ ("sketch.edit_text", json!({"link": null, "entity": null})),
+ ("sketch.edit_text", json!({"link": "no_such_link"})),
+ ("sketch.edit_text", json!({"entity": "no_such_curve"})),
+ ("sketch.edit_text", json!({"entity": "l1"})),
+ ("sketch.edit_text", json!({"link": t, "text": 5})),
+ ("sketch.edit_text", json!({"link": t, "text": ""})),
+ ("sketch.edit_text", json!({"link": t, "text": "x", "text_expression": "'y'"})),
+ ("sketch.edit_text", json!({"link": t, "text_expression": 5})),
+ ("sketch.edit_text", json!({"link": t, "at": [1]})),
+ ("sketch.edit_text", json!({"link": t, "at": "x"})),
+ ("sketch.edit_text", json!({"link": t, "height": -1})),
+ ("sketch.edit_text", json!({"link": t, "height": []})),
+ ("sketch.edit_text", json!({"link": t, "angle": {}})),
+ ("sketch.edit_text", json!({"link": t, "font": false})),
+ ("sketch.edit_text", json!({"link": t, "bold": "no"})),
+ ("sketch.edit_text", json!({"link": t, "align": "middle"})),
+ ("sketch.edit_text", json!({"link": t, "letter_spacing": true})),
+ ("sketch.edit_text", json!({"link": t, "line_spacing": -1})),
+ ("sketch.edit_text", json!({"link": t, "path": 3})),
+ ("sketch.edit_text", json!({"edits": []})),
+ ("sketch.edit_text", json!({"edits": "t1"})),
+ ("sketch.edit_text", json!({"edits": {"link": t}})),
+ ("sketch.edit_text", json!({"edits": [5]})),
+ ("sketch.edit_text", json!({"edits": [{}]})),
+ ("sketch.edit_text", json!({"edits": [{"link": t}, {"link": "no_such_link"}]})),
+ ("sketch.edit_text", json!({"edits": [{"link": t, "text": 5}]})),
+ ("sketch.edit_text", json!({"edits": [{"link": t, "at": [1, 2, 3]}]})),
+ ("sketch.edit_text", json!({"edits": vec![json!({"link": t}); 1001]})),
+ ("sketch.edit_text", json!({"edits": [{"link": t, "bold": 1}], "live": false})),
+ ]);
+}
+
+/// A key the handler reads leniently (a wrong type read as left out) is a mistake the check
+/// reports: the one place where strict refuses a call that runs today, as documented.
+#[test]
+fn wrong_types_the_handlers_ignore_are_reported() {
+ for (id, p, message) in [
+ ("sketch.conic", json!({"start": [0, 0], "end": [2, 0], "apex": [1, 1], "rho": "x"}), "`rho` must be a number between 0 and 1"),
+ ("sketch.line.midpoint", json!({"mid": [0, 0], "end": [2, 0], "construction": "yes"}), "`construction` must be true or false"),
+ ("sketch.slot.center_point", json!({"center": [0, 0], "end": [2, 0], "width": 1, "connect": 1}), "`connect` must be true or false"),
+ ("sketch.arc.tangent", json!({"start": "l1.end", "end": [2, 0], "curve": 5}), "`curve` must be text"),
+ ("sketch.centerline", json!({"curves": ["l1"], "value": 1}), "`value` must be true or false"),
+ ("sketch.edit_text", json!({"link": "t1", "live": 1}), "`live` must be true or false"),
+ ] {
+ assert_eq!(issues(id, p), [message], "{id}");
+ }
+}
+
+/// Keys a handler reads only in some cases are checked only in those cases: a call that works
+/// never gets a warning for the rest.
+#[test]
+fn keys_read_only_in_some_cases_are_checked_only_then() {
+ let ok = |id: &str, p: Value| assert_eq!(issues(id, p.clone()), Vec::<String>::new(), "{id} {p}");
+ let near = json!([20, 10]);
+ // radius wins over diameter, whatever the diameter is; without a radius, a diameter does.
+ ok("sketch.circle.two_tangent", json!({"radius": 5, "diameter": "wide", "near": near, "curves": ["l1", "l2"]}));
+ ok("sketch.circle.two_tangent", json!({"radius": "r / 2", "diameter": null, "near": near, "curves": ["l1", "l2"]}));
+ ok("sketch.circle.two_tangent", json!({"radius": true, "diameter": 10, "near": near, "curves": ["l1", "l2"]}));
+ ok("sketch.circle.two_tangent", json!({"diameter": 10, "near": near, "curves": ["l1", "l2"]}));
+ assert_eq!(
+ issues("sketch.circle.two_tangent", json!({"diameter": "wide", "near": near, "curves": ["l1", "l2"]})),
+ ["needs `radius` or `diameter`"]
+ );
+ // sweep wins over end, however end is written; without a sweep, end is read.
+ let slot = |extra: Value| {
+ let mut p = json!({"center": [0, 0], "start": [5, 0], "width": 1});
+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
+ p
+ };
+ ok("sketch.slot.arc_center", slot(json!({"sweep": 90, "end": "nowhere"})));
+ ok("sketch.slot.arc_center", slot(json!({"sweep": 90, "end": null})));
+ ok("sketch.slot.arc_center", slot(json!({"end": [0, 5]})));
+ assert_eq!(issues("sketch.slot.arc_center", slot(json!({"end": "nowhere"}))), ["`end` must be a point [x, y]"]);
+ assert_eq!(issues("sketch.slot.arc_center", slot(json!({"sweep": null, "end": [0, 5]}))), ["`sweep` must be finite degrees"]);
+ // minor_radius wins over minor, and a minor_radius that is no number is not read when there is a minor.
+ let ellipse = |extra: Value| {
+ let mut p = json!({"center": [0, 0], "major": [10, 0]});
+ p.as_object_mut().into_iter().for_each(|o| o.extend(extra.as_object().cloned().unwrap_or_default()));
+ p
+ };
+ ok("sketch.ellipse", ellipse(json!({"minor_radius": 3, "minor": "nowhere"})));
+ ok("sketch.ellipse", ellipse(json!({"minor_radius": "wide", "minor": [1, 1]})));
+ ok("sketch.ellipse", ellipse(json!({"minor_radius": null, "minor": [1, 1]})));
+ ok("sketch.ellipse", ellipse(json!({"minor": {"x": 1, "y": 1}})));
+ assert_eq!(issues("sketch.ellipse", ellipse(json!({"minor_radius": "wide", "minor": "x"}))), ["needs `minor` [x,y] or `minor_radius`"]);
+ // Outside `edits` a text edit reads its own keys; with `edits` it reads only `edits` (and `live`).
+ ok("sketch.edit_text", json!({"edits": [{"link": "t1"}], "link": 5, "text": 7, "at": "no", "bold": "yes"}));
+ ok("sketch.edit_text", json!({"edits": null, "link": "t1", "text": "x"}));
+ assert_eq!(issues("sketch.edit_text", json!({"edits": [{"entity": "c1", "bold": "yes"}]})), ["`bold` must be true or false"]);
+ // A link that isn't text is read as left out when there is an entity, and the entity as left out when there is a link.
+ ok("sketch.edit_text", json!({"link": 5, "entity": "l1"}));
+ ok("sketch.edit_text", json!({"link": "t1", "entity": 5}));
+ assert_eq!(issues("sketch.edit_text", json!({"link": 5, "entity": 5})), ["give `link` or `entity`"]);
+ // The texts of a single edit read their own `at` as null: kept.
+ ok("sketch.edit_text", json!({"link": "t1", "at": null, "height": null, "text": null}));
+ // A text on a path: `at` is checked all the same, as the handler does.
+ assert_eq!(issues("sketch.text", json!({"text": "x", "at": null})), [crate::cmd::AT_MUST]);
+ ok("sketch.text", json!({"text": "x", "at": [0, 0], "sketch": 4}));
+ ok("sketch.edit_text", json!({"link": "t1", "sketch": "S"}));
+}
+
+/// Every form of every creation command runs in warn without warnings, replies as its output
+/// schema says, and a misspelt key gets its warning while the reply still matches.
+#[test]
+fn creation_replies_match_the_output_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ run(&mut s, "parameters.add", json!({"name": "tall", "expression": "6 mm"}));
+ run(&mut s, "sketch.create", json!({"plane": "XY"}));
+ for points in [[[0, 0], [40, 0]], [[40, 0], [40, 30]], [[40, 30], [0, 30]]] {
+ run(&mut s, "sketch.line", json!({"points": points}));
+ }
+ let run_ok = |s: &mut Session, id: &str, p: Value| {
+ let r = run(s, id, p.clone());
+ assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");
+ r
+ };
+ let drawn = |s: &mut Session, id: &str, p: Value| {
+ let r = run_ok(s, id, p);
+ matches(output_schema_for::<DrawResult>(), &r);
+ assert_eq!(
+ r.as_object().map(|o| o.keys().cloned().collect::<std::collections::BTreeSet<_>>()),
+ Some(["constraints", "created", "curves", "sketch"].map(String::from).into()),
+ "{r}"
+ );
+ r
+ };
+ let near = json!([30, 10]);
+ for p in [
+ json!({"mid": [100, 5], "end": [110, 5]}),
+ json!({"mid": [100, 15], "end": [110, 15], "construction": true}),
+ json!({"mid": "l1.start", "end": [10, 10], "construction": null, "sketch": null}),
+ json!({"mid": {"ref": "l1.end"}, "end": {"x": 50, "y": 10}}),
+ json!({"mid": {"at": [100, 25]}, "end": [110, 25]}),
+ json!({"mid": ["101 mm", "26"], "end": [111, 26]}),
+ json!({"mid": "mid:l1", "end": [20, 10]}),
+ json!({"mid": "on:l3:10,30", "end": [10, 20]}),
+ ] {
+ drawn(&mut s, "sketch.line.midpoint", p);
+ }
+ drawn(&mut s, "sketch.arc.tangent", json!({"start": "l2.end", "end": [60, 40], "curve": "l2"}));
+ drawn(&mut s, "sketch.circle.two_tangent", json!({"radius": 5, "near": near, "curves": ["l1", "l2"]}));
+ drawn(&mut s, "sketch.circle.two_tangent", json!({"radius": "tall", "near": near, "curves": ["l1", "l2"]}));
+ drawn(&mut s, "sketch.circle.two_tangent", json!({"diameter": 8, "near": near, "curves": ["l1", "l2"]}));
+ drawn(&mut s, "sketch.circle.two_tangent", json!({"radius": 4, "diameter": "ignored", "near": near, "curves": ["l1", "l2"]}));
+ drawn(&mut s, "sketch.circle.three_tangent", json!({"near": [25, 15], "curves": ["l1", "l2", "l3"]}));
+ drawn(&mut s, "sketch.slot.center_point", json!({"center": [100, 100], "end": [110, 100], "width": 4}));
+ drawn(&mut s, "sketch.slot.center_point", json!({"center": [100, 120], "end": [110, 120], "width": 4, "connect": false, "sketch": null}));
+ for p in [
+ json!({"start": [100, 0], "through": [110, 10], "end": [120, 0], "width": 2}),
+ json!({"start": [130, 0], "through": [140, 10], "end": [150, 0], "width": 2, "sketch": null}),
+ ] {
+ let r = run_ok(&mut s, "sketch.slot.arc_three_point", p);
+ matches(output_schema_for::<ArcSlotResult>(), &r);
+ assert!(r["centre_arc"].is_string(), "{r}");
+ }
+ for p in [
+ json!({"center": [200, 0], "start": [210, 0], "end": [200, 10], "width": 2}),
+ json!({"center": [200, 30], "start": [210, 30], "sweep": 90, "width": 2}),
+ json!({"center": [200, 60], "start": [210, 60], "sweep": 90, "end": "nowhere", "width": 2}),
+ ] {
+ let r = run_ok(&mut s, "sketch.slot.arc_center", p);
+ matches(output_schema_for::<ArcSlotResult>(), &r);
+ assert!(r["centre_arc"].is_string(), "{r}");
+ }
+ for p in [
+ json!({"center": [300, 0], "major": [310, 0], "minor_radius": 4}),
+ json!({"center": [300, 20], "major": [310, 20], "minor": [302, 24], "axes": false}),
+ json!({"center": [300, 40], "major": [310, 40], "minor": [302, 44], "axes": null, "construction": true}),
+ json!({"center": [300, 60], "major": [310, 60], "minor_radius": 4, "minor": "nowhere"}),
+ json!({"center": [300, 80], "major": [310, 80], "minor_radius": "wide", "minor": {"x": 302, "y": 84}}),
+ ] {
+ drawn(&mut s, "sketch.ellipse", p);
+ }
+ drawn(&mut s, "sketch.spline.fit_point", json!({"points": [[0, 50], [10, 60], [20, 50]]}));
+ drawn(&mut s, "sketch.spline.fit_point", json!({"points": [[30, 50], [40, 60], [50, 50], [45, 45]], "periodic": true, "construction": true}));
+ drawn(&mut s, "sketch.spline.fit_point", json!({"points": ["l1.start", {"at": [10, 90]}, ["20 mm", 80]], "periodic": false}));
+ drawn(&mut s, "sketch.spline.control_point", json!({"points": [[0, 110], [10, 120], [20, 110], [30, 120]], "periodic": false}));
+ drawn(&mut s, "sketch.spline.control_point_5", json!({"points": [[0, 130], [10, 140], [20, 130], [30, 140], [40, 130], [50, 140]]}));
+ drawn(&mut s, "sketch.conic", json!({"start": [0, 150], "end": [20, 150], "apex": [10, 160]}));
+ drawn(&mut s, "sketch.conic", json!({"start": [30, 150], "end": [50, 150], "apex": [40, 160], "rho": 0.3, "construction": true}));
+ drawn(&mut s, "sketch.blend_curve", json!({"a": "l1.start", "b": "l3.end"}));
+ drawn(&mut s, "sketch.blend_curve", json!({"a": {"ref": "l1.end"}, "b": "l2.end", "continuity": " G2 "}));
+ drawn(&mut s, "sketch.blend_curve", json!({"a": "l1.start", "b": "l2.end", "continuity": "", "sketch": null}));
+ for (id, p) in [
+ ("sketch.centerline", json!({"curves": ["l1"], "value": true})),
+ ("sketch.centerline", json!({"curves": "l1", "value": null})),
+ ("sketch.infinite", json!({"curves": ["l2", "l3"], "value": true, "sketch": null})),
+ ("sketch.infinite", json!({"curves": "l2"})),
+ ] {
+ let r = run_ok(&mut s, id, p);
+ matches(output_schema_for::<LineTypeResult>(), &r);
+ assert_eq!(
+ r.as_object().map(|o| o.keys().cloned().collect::<std::collections::BTreeSet<_>>()),
+ Some(["changed", "created", "sketch"].map(String::from).into()),
+ "{r}"
+ );
+ }
+ // Sketch text: its forms, and its edits.
+ let text = |s: &mut Session, p: Value| {
+ let r = run_ok(s, "sketch.text", p);
+ matches(output_schema_for::<TextResult>(), &r);
+ r
+ };
+ let first = text(&mut s, json!({"text": "Hello\nthere", "at": [0, 200]}));
+ assert!(first["guide"].is_null() && first.get("exprs").is_none(), "{first}");
+ let link = first["link"].as_str().unwrap_or_default().to_string();
+ text(
+ &mut s,
+ json!({"text": "Styled", "at": {"x": 50, "y": 200}, "height": 8, "angle": 10, "font": "", "bold": false, "italic": true, "reverse": false, "align": "Center", "letter_spacing": 0.5, "line_spacing": 1.2, "path": ""}),
+ );
+ text(&mut s, json!({"text": null, "text_expression": "'A' + 'B'", "at": [0, 220], "bold": null, "align": null, "path": null}));
+ let expr = text(&mut s, json!({"text": "Param", "at": ["1 + 1", 230], "height": "tall", "angle": "30 deg"}));
+ // An expression that names no parameter is the number it comes to.
+ assert_eq!(expr["exprs"], json!({"height": "tall"}), "{expr}");
+ let on_path = text(&mut s, json!({"text": "Curve", "at": [0, 0], "path": "l1", "align": " RIGHT ", "reverse": true}));
+ assert_eq!(on_path["guide"], json!("l1"), "{on_path}");
+ let other = text(&mut s, json!({"text": "Other", "at": [0, 260]}));
+ let outline = other["curves"][0].clone();
+ for p in [
+ json!({"link": link, "text": "Changed"}),
+ json!({"link": link, "at": [5, 205], "height": "tall", "angle": null, "font": null, "line_spacing": null}),
+ json!({"entity": outline, "italic": true, "live": false}),
+ json!({"link": link, "entity": 5, "text": "Same", "edits": null}),
+ json!({"edits": [{"link": link, "text": "One"}, {"entity": outline, "height": 9}], "link": 5, "text": 7, "at": "ignored"}),
+ ] {
+ let r = run_ok(&mut s, "sketch.edit_text", p.clone());
+ matches(output_schema_for::<EditTextResult>(), &r);
+ assert!(r["edits"].is_array() == p.get("edits").is_some_and(|e| !e.is_null()), "{r}");
+ }
+ // A misspelt key runs in warn and says so; the reply still matches. Strict refuses it.
+ let misspelt: [(&str, Value); 17] = [
+ ("sketch.line.midpoint", json!({"mid": [100, 45], "end": [110, 45], "constrution": true})),
+ ("sketch.arc.tangent", json!({"start": "l2.end", "end": [62, 42], "curv": "l2"})),
+ ("sketch.circle.two_tangent", json!({"radious": 3, "diameter": 6, "near": near, "curves": ["l1", "l2"]})),
+ ("sketch.circle.three_tangent", json!({"nere": 1, "near": [25, 15], "curves": ["l1", "l2", "l3"]})),
+ ("sketch.slot.center_point", json!({"center": [100, 140], "end": [110, 140], "widht": 1, "width": 4})),
+ ("sketch.slot.arc_three_point", json!({"start": [160, 0], "through": [170, 10], "end": [180, 0], "width": 2, "throgh": 1})),
+ ("sketch.slot.arc_center", json!({"center": [200, 90], "start": [210, 90], "sweep": 90, "width": 2, "swep": 1})),
+ ("sketch.ellipse", json!({"center": [300, 100], "major": [310, 100], "minor_radius": 4, "axs": false})),
+ ("sketch.spline.fit_point", json!({"points": [[60, 50], [70, 60], [80, 50]], "periodc": true})),
+ ("sketch.spline.control_point", json!({"points": [[60, 110], [70, 120], [80, 110]], "point": 1})),
+ ("sketch.spline.control_point_5", json!({"points": [[60, 130], [70, 140], [80, 130], [90, 140], [100, 130], [110, 140]], "constructon": 1})),
+ ("sketch.conic", json!({"start": [60, 150], "end": [80, 150], "apex": [70, 160], "rhoo": 0.4})),
+ ("sketch.blend_curve", json!({"a": "l1.start", "b": "l3.end", "continuty": "g1"})),
+ ("sketch.centerline", json!({"curves": ["l1"], "vlaue": true})),
+ ("sketch.infinite", json!({"curves": ["l2"], "vlaue": true})),
+ ("sketch.text", json!({"text": "Oops", "at": [0, 240], "hieght": 3})),
+ ("sketch.edit_text", json!({"link": link, "txt": "x"})),
+ ];
+ for (id, p) in &misspelt {
+ let r = s.execute(id, p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ assert!(
+ r["param_warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|m| m.contains("unknown key"))),
+ "{id}: {r}"
+ );
+ }
+ s.param_check = ParamCheck::Strict;
+ for (id, p) in &misspelt {
+ let error = s.execute(id, p).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains("unknown key"), "{id}: {error}");
+ }
+}
+
+/// Each command's schemas describe it: a summary, and a description on every key.
+#[test]
+fn creation_schemas_are_described() {
+ for id in [
+ "sketch.arc.tangent",
+ "sketch.blend_curve",
+ "sketch.centerline",
+ "sketch.circle.three_tangent",
+ "sketch.circle.two_tangent",
+ "sketch.conic",
+ "sketch.edit_text",
+ "sketch.ellipse",
+ "sketch.infinite",
+ "sketch.line.midpoint",
+ "sketch.slot.arc_center",
+ "sketch.slot.arc_three_point",
+ "sketch.slot.center_point",
+ "sketch.spline.control_point",
+ "sketch.spline.control_point_5",
+ "sketch.spline.fit_point",
+ "sketch.text",
+ ] {
+ let c = crate::cmd::find_command(id).unwrap_or_else(|| panic!("{id}"));
+ let input = c.contract.map(|c| c.input_schema()).unwrap_or_else(|| panic!("{id}"));
+ let input = input.as_value();
+ assert!(input["description"].as_str().is_some_and(|d| d.len() > 20), "{id}: no summary");
+ for (key, property) in input["properties"].as_object().into_iter().flatten() {
+ assert!(property.get("description").is_some() || property.get("$ref").is_some(), "{id}: `{key}` has no description");
+ }
+ let output = (c.output.unwrap_or_else(|| panic!("{id}")))();
+ assert!(
+ output.as_value().get("properties").is_some() || output.as_value().get("oneOf").is_some() || output.as_value().get("anyOf").is_some(),
+ "{id}"
+ );
+ }
+}
+
+/// The schemas ask for what the handlers can't do without, and take what they read.
+#[test]
+fn the_creation_schemas_take_what_the_handlers_read() {
+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {
+ let schema = schema.as_value();
+ for (p, takes) in cases {
+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");
+ }
+ };
+ takes(
+ input_schema_for::<TwoTangentCircleParams>(),
+ &[
+ (json!({"radius": 5, "near": [1, 2], "curves": ["l1", "l2"]}), true),
+ (json!({"diameter": 5, "near": {"x": 1, "y": 2}, "curves": ["l1", "l2"]}), true),
+ (json!({"diameter": 5, "near": [1, 2], "curves": "l1"}), false),
+ (json!({"radius": "r / 2", "near": [1, 2], "curves": ["l1", "l2"], "sketch": 3}), true),
+ (json!({"near": [1, 2], "curves": ["l1", "l2"]}), false),
+ (json!({"radius": 5, "curves": ["l1", "l2"]}), false),
+ (json!({"radius": 5, "near": [1, 2]}), false),
+ (json!({"radius": 5, "near": [1, 2], "curves": ["l1"]}), false),
+ (json!({"radius": 5, "near": [1, 2], "curves": ["l1", "l2", "l3"]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ArcSlotCenterParams>(),
+ &[
+ (json!({"center": [0, 0], "start": [5, 0], "width": 1, "sweep": 90}), true),
+ (json!({"center": [0, 0], "start": [5, 0], "width": 1, "end": [0, 5]}), true),
+ (json!({"center": [0, 0], "start": [5, 0], "width": 1}), false),
+ (json!({"center": [0, 0], "start": [5, 0], "sweep": 90}), false),
+ (json!({"center": [0, 0], "start": [5, 0], "width": 0, "sweep": 90}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<EllipseParams>(),
+ &[
+ (json!({"center": [0, 0], "major": [5, 0], "minor_radius": 2}), true),
+ (json!({"center": [0, 0], "major": [5, 0], "minor": [1, 1], "axes": false}), true),
+ (json!({"center": [0, 0], "major": [5, 0]}), false),
+ (json!({"center": [0, 0], "minor_radius": 2}), false),
+ (json!({"center": [0, 0], "major": [5, 0], "minor_radius": 0}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ConicParams>(),
+ &[
+ (json!({"start": [0, 0], "end": "l1.end", "apex": {"vertex": [1, 2, 3]}, "rho": 0.2}), true),
+ (json!({"start": ["w / 2", 0], "end": {"ref": "p1"}, "apex": "mid:l1"}), true),
+ (json!({"start": [0, 0], "end": [1, 0]}), false),
+ (json!({"start": [0, 0], "end": [1, 0], "apex": [0, 1], "rho": 1}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<FitPointSplineParams>(),
+ &[
+ (json!({"points": [[0, 0], [1, 1]], "periodic": true}), true),
+ (json!({"points": [[0, 0]]}), false),
+ (json!({"points": vec![json!([0, 0]); 501]}), false),
+ (json!({"periodic": true}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ControlPointSplineParams>(),
+ &[(json!({"points": [[0, 0], [1, 1]], "periodic": false}), true), (json!({"points": [[0, 0]]}), false)],
+ );
+ takes(
+ input_schema_for::<BlendCurveParams>(),
+ &[
+ (json!({"a": "l1.end", "b": "l2.start", "continuity": "G3"}), true),
+ (json!({"a": "l1.end", "b": "l2.start", "continuity": ""}), true),
+ (json!({"a": "l1.end"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<CenterlineParams>(),
+ &[
+ (json!({"curves": "l1"}), true),
+ (json!({"curves": ["l1", "l2"], "value": false}), true),
+ (json!({"curves": []}), false),
+ (json!({}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<SketchTextParams>(),
+ &[
+ (json!({"text": "x", "at": [0, 0]}), true),
+ (json!({"text_expression": "'x'", "at": ["w / 2", "5"]}), true),
+ (json!({"text": "x", "at": {"x": 1, "y": 2}, "height": "h", "angle": "30 deg", "align": "CENTRE", "path": ""}), true),
+ (json!({"text": "x"}), false),
+ (json!({"at": [0, 0]}), false),
+ (json!({"text": "x", "at": [0, 0], "height": 0}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<EditTextParams>(),
+ &[
+ (json!({"link": "j1", "text": "y"}), true),
+ (json!({"entity": "n1", "at": [1, 2]}), true),
+ (json!({"edits": [{"link": "j1"}, {"entity": "n1", "height": 4}], "live": false}), true),
+ (json!({"edits": []}), false),
+ (json!({"edits": [{"text": "y"}]}), false),
+ (json!({"text": "y"}), false),
+ ],
+ );
+}
+
+/// The point forms the types take are the forms the handlers read: `sketch.line.midpoint` snaps
+/// its points, `sketch.blend_curve` does not.
+#[test]
+fn point_forms_match_the_point_readers() {
+ let refused =
+ |e: &crate::EngineError| e.to_string().contains("a point must be [x, y]") || e.to_string().contains("a point's coordinates must be");
+ let forms = [
+ json!([1, 2]),
+ json!({"x": 1, "y": 2}),
+ json!([1e9, 2]),
+ json!([1, "2"]),
+ json!(["1 mm", "2"]),
+ json!(["1", true]),
+ json!([true, "2"]),
+ json!(["", 2]),
+ json!([" ", 2]),
+ json!(["x".repeat(4097), 2]),
+ json!([1e9, "2"]),
+ json!([null, "2"]),
+ json!([1, 2, 3]),
+ json!([1]),
+ json!([]),
+ json!("l1.end"),
+ json!(""),
+ json!("mid:l1"),
+ json!("vertex:1,2,3"),
+ json!({"ref": "l1.end"}),
+ json!({"ref": 5}),
+ json!({"ref": 5, "at": [1, 2]}),
+ json!({"ref": "l1.end", "at": 5}),
+ json!({"at": [1, 2]}),
+ json!({"at": {"x": 1, "y": 2}}),
+ json!({"at": [1, "2"]}),
+ json!({"at": 5}),
+ json!({"vertex": [1, 2, 3]}),
+ json!({"vertex": [1, 2]}),
+ json!({"vertex": [1, 2], "at": [1, 2]}),
+ json!({"on_edge": {"x": 1, "y": 2, "z": 3}}),
+ json!({"on_edge": "x"}),
+ json!({}),
+ json!({"x": 1}),
+ json!(5),
+ json!(true),
+ json!(null),
+ json!([[1, 2]]),
+ ];
+ for v in forms {
+ let mut s = drawing(ParamCheck::Off);
+ let snapped = s.execute("sketch.line.midpoint", &json!({"mid": v, "end": [7, 7]}));
+ assert_eq!(crate::cmd::point_arg_form(&v, true).is_ok(), !snapped.as_ref().err().is_some_and(refused), "mid {v}: {snapped:?}");
+ let mut s = drawing(ParamCheck::Off);
+ let plain = s.execute("sketch.blend_curve", &json!({"a": v, "b": "l2.end"}));
+ assert_eq!(crate::cmd::point_arg_form(&v, false).is_ok(), !plain.as_ref().err().is_some_and(refused), "a {v}: {plain:?}");
+ // The type says the same.
+ assert_eq!(serde_json::from_value::<super::SnapPoint>(v.clone()).is_ok(), crate::cmd::point_arg_form(&v, true).is_ok(), "{v}");
+ assert_eq!(serde_json::from_value::<super::SketchPoint>(v.clone()).is_ok(), crate::cmd::point_arg_form(&v, false).is_ok(), "{v}");
+ }
+}
+
+/// A text edit made `live` goes to the live runner, which the check doesn't wrap yet: it still
+/// replies as the output schema says, and says nothing about its keys.
+#[test]
+fn a_live_text_edit_replies_as_its_schema_says() {
+ let mut s = drawing(ParamCheck::Warn);
+ let link = text_link();
+ let r = run(&mut s, "sketch.edit_text", json!({"link": link, "height": 7, "live": true, "unknown": 1}));
+ matches(output_schema_for::<EditTextResult>(), &r);
+ assert!(r.get("param_warnings").is_none() && r["link"] == json!(link), "{r}");
+}
+
+/// The patterns that spell what a handler reads ignoring case and blanks.
+#[test]
+fn the_case_blind_patterns_say_what_the_handlers_read() {
+ assert_eq!(
+ super::word_pattern(&["left", "right"]),
+ format!("^[{0}]*([Ll][Ee][Ff][Tt]|[Rr][Ii][Gg][Hh][Tt])[{0}]*$", crate::schema::types::whitespace_class())
+ );
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 6d8aac2193..a824b0fcac 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -71,17 +71,11 @@ sheet.export_bend_table
sheet.export_dxf
sheet.flat_pattern
sheet.path_flange
-sketch.arc.tangent
sketch.auto_constrain
sketch.auto_constrain_from_datum
sketch.auto_project
-sketch.blend_curve
sketch.break_link
-sketch.centerline
sketch.chain
-sketch.circle.three_tangent
-sketch.circle.two_tangent
-sketch.conic
sketch.constrainer
sketch.constraint.curvature
sketch.constraint.polygon
@@ -93,21 +87,17 @@ sketch.dimension_text
sketch.drag
sketch.drag_end
sketch.draw.dimensioned
-sketch.edit_text
-sketch.ellipse
sketch.export_dxf
sketch.finish_auto_constrain
sketch.fit_curves_to_section
sketch.glyphs
sketch.include_3d
-sketch.infinite
sketch.insert_dxf
sketch.insert_svg
sketch.inspect
sketch.intersect
sketch.intersection_curve
sketch.isoparametric_curve
-sketch.line.midpoint
sketch.line3d
sketch.move3d
sketch.move_point
@@ -122,19 +112,12 @@ sketch.rectangle.center
sketch.rectangle.rounded
sketch.rectangle.three_point
sketch.rectangle.two_point
-sketch.slot.arc_center
-sketch.slot.arc_three_point
-sketch.slot.center_point
sketch.slot.center_to_center
sketch.slot.overall
sketch.snap
sketch.solve
-sketch.spline.control_point
-sketch.spline.control_point_5
-sketch.spline.fit_point
sketch.spline3d
sketch.spun_profile
-sketch.text
sketch.toggle_driven
solid.align
solid.chamfer
diff --git a/docs/book/src/dev/schemas.md b/docs/book/src/dev/schemas.md
index 70dd3d7f7e..68f1c3822a 100644
--- a/docs/book/src/dev/schemas.md
+++ b/docs/book/src/dev/schemas.md
@@ -61,9 +61,10 @@ handler and everything it passes `p` to:
that take picks;
- `live`, for a command with `.live(…)` (today `sketch.drag` and `sketch.edit_text`): a call
with `live: true` goes to the live runner, which `checked!` doesn't wrap, so live calls aren't
- checked yet. Leave those two on the list until the engine checks the live path too. A new
- command that needs a live runner still gets its contract (declare `live` as an optional
- `bool`); say in its pull request that its live calls aren't checked.
+ checked yet. Leave `sketch.drag` on the list until the engine checks the live path too;
+ `sketch.edit_text` has its contract (with `live` declared as an optional `bool`) and its live
+ calls aren't checked. A new command that needs a live runner gets its contract the same way;
+ say in its pull request that its live calls aren't checked.
A key the handler reads only in some situations (thin-wall keys with `thin: true`) is still a
field; its description says when it applies. Contracts don't check combinations of keys