Skip to content

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

Agents and scripts: Create Sketch, Normal/Construction, Delete, Drag, Move Point, Move Dimension Text, Sketch Options, Chain and Solve describe their exact parameters and reply (#13224) (#13273)

PeppaWutzf256bef34bee
diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rs
index e022cc39dc..0103b491f5 100644
--- a/crates/engine/src/cmd/sketch.rs
+++ b/crates/engine/src/cmd/sketch.rs
@@ -8,11 +8,17 @@ use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, Point
use super::{CommandSpec, in_sketch};
use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec3};
+use crate::schema::frame::SketchSolve;
use crate::schema::sketch::{
CancelResult, CoincidentMade, CoincidentParams, CoincidentResult, CollinearParams, ConcentricParams, Constrained, ConstraintResult, EditParams,
EditResult, EqualMade, EqualParams, EqualResult, ExitParams, FinishResult, FixOutcome, FixParams, FixResult, HorizontalVerticalParams,
MidpointParams, ParallelParams, PerpendicularParams, SymmetryParams, SymmetryResult, TangentMade, TangentParams, TangentResult,
};
+use crate::schema::sketch_session::{
+ Activated, Attachment, ChainParams, ChainResult, ConstructionParams, ConstructionResult, CreateParams, CreateResult, DeleteParams, DeleteResult,
+ DimensionTextParams, DimensionTextResult, DragEndParams, DragEndResult, DragParams, DragResult, Frame, MovePointParams, MovePointResult,
+ OptionsParams, OptionsReply, OptionsResult, SketchOptions, SolveParams, SolveResult,
+};
use crate::schema::sketch_shapes::{
ArcCenterPointParams, ArcThreePointParams, CircleCenterParams, CircleThreePointParams, CircleTwoPointParams, Created, DrawResult, LineParams,
PointParams, PointResult,
@@ -44,6 +50,16 @@ macro_rules! model_operand_doc {
};
}
+const CREATE_CONTRACT: TypedContract<CreateParams> = TypedContract::new();
+const CONSTRUCTION_CONTRACT: TypedContract<ConstructionParams> = TypedContract::new();
+const DELETE_CONTRACT: TypedContract<DeleteParams> = TypedContract::new();
+const MOVE_POINT_CONTRACT: TypedContract<MovePointParams> = TypedContract::new();
+const DRAG_CONTRACT: TypedContract<DragParams> = TypedContract::new();
+const DRAG_END_CONTRACT: TypedContract<DragEndParams> = TypedContract::new();
+const DIMENSION_TEXT_CONTRACT: TypedContract<DimensionTextParams> = TypedContract::new();
+const OPTIONS_CONTRACT: TypedContract<OptionsParams> = TypedContract::new();
+const CHAIN_CONTRACT: TypedContract<ChainParams> = TypedContract::new();
+const SOLVE_CONTRACT: TypedContract<SolveParams> = TypedContract::new();
const EDIT_CONTRACT: TypedContract<EditParams> = TypedContract::new();
const EXIT_CONTRACT: TypedContract<ExitParams> = TypedContract::new();
const HORIZONTAL_VERTICAL_CONTRACT: TypedContract<HorizontalVerticalParams> = TypedContract::new();
@@ -66,9 +82,11 @@ const ARC_THREE_POINT_CONTRACT: TypedContract<ArcThreePointParams> = TypedContra
const ARC_CENTER_POINT_CONTRACT: TypedContract<ArcCenterPointParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("sketch.create", "Create Sketch", create_sketch)
+ CommandSpec::new("sketch.create", "Create Sketch", crate::checked!("sketch.create", create_sketch))
.at("SOLID", "CREATE")
.icon("sketch")
+ .contract(&CREATE_CONTRACT)
+ .output(output_schema_for::<CreateResult>)
.params("plane: XY|XZ|YZ (sketch x, y along world +X, +Y on XY; +X, -Z on XZ; +Y, +Z on YZ) | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} (in world coordinates unless frame says otherwise; a named plane is the active component's own) | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), frame?: world (default) | component (which coordinates an explicit plane is in; the reply's `frame` says which, with a `note` when the active component is moved or turned), project_edges?: bool, activate_part?: bool (default false; on a face of a body of another component than the active one: activate that component at the picked placement first, as component.activate would, and make the sketch there; it stays active afterwards and the reply's `activated` names it), name?"),
CommandSpec::new("sketch.edit", "Edit Sketch", crate::checked!("sketch.edit", edit_sketch))
.noundo().icon("sketch")
@@ -256,40 +274,71 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&SYMMETRY_CONTRACT)
.output(output_schema_for::<SymmetryResult>)
.params(concat!("a, b: two points or two curves (lines mirror their ends, circles/arcs their centres); line: symmetry line id, or x / y for the sketch's own axes (a curve with that id wins; an axis becomes a linked construction line on it, reported in created); or point (or a point id as line, \"origin\" too): symmetric about that point, each pair joined by a construction line it is the midpoint of", model_operand_doc!())),
- CommandSpec::new("sketch.construction", "Normal/Construction", construction)
+ CommandSpec::new("sketch.construction", "Normal/Construction", crate::checked!("sketch.construction", construction))
.at("SKETCH", "CREATE")
.icon("construction")
.key("X")
.enabled(in_sketch)
+ .contract(&CONSTRUCTION_CONTRACT)
+ .output(output_schema_for::<ConstructionResult>)
.params("curves: [ids], value?: bool (default: construction unless all of them already are)"),
- CommandSpec::new("sketch.delete", "Delete Sketch Entities", sketch_delete).icon("delete")
+ CommandSpec::new("sketch.delete", "Delete Sketch Entities", crate::checked!("sketch.delete", sketch_delete)).icon("delete")
.enabled(in_sketch)
+ .contract(&DELETE_CONTRACT)
+ .output(output_schema_for::<DeleteResult>)
.params("entities: [curve, point or constraint ids]"),
- CommandSpec::new("sketch.move_point", "Drag Sketch Point", move_point).icon("sketch_move").enabled(in_sketch).params("point: ref, to: [x,y]"),
+ CommandSpec::new("sketch.move_point", "Drag Sketch Point", crate::checked!("sketch.move_point", move_point))
+ .icon("sketch_move")
+ .enabled(in_sketch)
+ .contract(&MOVE_POINT_CONTRACT)
+ .output(output_schema_for::<MovePointResult>)
+ .params("point: ref, to: [x,y]"),
CommandSpec::new("sketch.move_points", "Move Sketch Points", move_points).icon("sketch_move").enabled(in_sketch).params(
"moves: [{point: ref | near: [x,y], to: [x,y]}] (each point to its own target; `near`: the sketch point closest to it, \
refused when none lies within `tolerance` or two are as close), tolerance?: mm (default 0.1); sketch? → moved: \
[{point, to, at, reached}] (`at`: where it ended up after the one solve; `reached`: whether that is `to`)",
),
- CommandSpec::new("sketch.drag", "Drag Sketch Geometry", drag).icon("sketch_move").enabled(in_sketch).live(drag_live).params(
+ CommandSpec::new("sketch.drag", "Drag Sketch Geometry", crate::checked!("sketch.drag", drag))
+ .icon("sketch_move")
+ .enabled(in_sketch)
+ .live(drag_live)
+ .contract(&DRAG_CONTRACT)
+ .output(output_schema_for::<DragResult>)
+ .params(
"entity: point or curve, from: [x,y] where it was grabbed, to: [x,y], live?: bool: points and the material point grabbed on a line move toward `to` within the design constraints. When exact placement is impossible, bounded feasible steps minimize cursor distance. Splines slide by to - from; a circle or arc grabbed on its edge takes the radius to `to`. `with?`: [point or curve ids] moves the rest of a selection with the entity as one translation (circles keep their radii). Long moves retain the solution branch; arcs cannot sweep through their starts. Returns `reached`: progress projected onto the requested move (0..1), `at`: the grabbed position for the next frame, and `retry`: budget-limited progress can continue in another frame. `live: true` shares a work budget across held-solve decomposition and cursor correction; ordinary recovery and the final model evaluation retain their existing limits, not a wall-clock deadline. Later features stay stale until `sketch.drag_end`; `dof` stays from before the drag",
),
- CommandSpec::new("sketch.drag_end", "End Sketch Drag", drag_end).icon("sketch_move").enabled(in_sketch).doc_only().params(
+ CommandSpec::new("sketch.drag_end", "End Sketch Drag", crate::checked!("sketch.drag_end", drag_end))
+ .icon("sketch_move")
+ .enabled(in_sketch)
+ .doc_only()
+ .contract(&DRAG_END_CONTRACT)
+ .output(output_schema_for::<DragEndResult>)
+ .params(
"constraint?: {command: a sketch.constraint.* id, params}: ends a drag made of `sketch.drag` `live: true` frames: adds the constraint it let go on (not kept if it over-constrains the sketch), then evaluates the whole model once; returns the constraint's result and the sketch's solved state and degrees of freedom",
),
- CommandSpec::new("sketch.dimension_text", "Move Dimension Text", dimension_text).icon("edit")
+ CommandSpec::new("sketch.dimension_text", "Move Dimension Text", crate::checked!("sketch.dimension_text", dimension_text)).icon("edit")
.enabled(in_sketch)
+ .contract(&DIMENSION_TEXT_CONTRACT)
+ .output(output_schema_for::<DimensionTextResult>)
.params("dimension: constraint id or parameter name; at: [x,y] text centre (sketch coordinates) | reset: true (default place)"),
- CommandSpec::new("sketch.options", "Sketch Palette Options", sketch_options).icon("sketch").params(
+ CommandSpec::new("sketch.options", "Sketch Palette Options", crate::checked!("sketch.options", sketch_options))
+ .icon("sketch")
+ .contract(&OPTIONS_CONTRACT)
+ .output(output_schema_for::<OptionsResult>)
+ .params(
"sketch?: id|name (default active); any of show_profile, show_points, show_dimensions, show_constraints, show_projected, show_construction, grid, snap, slice, sketch_3d: bool. Returns them all",
),
- CommandSpec::new("sketch.chain", "Chain", chain_cmd).icon("chain")
+ CommandSpec::new("sketch.chain", "Chain", crate::checked!("sketch.chain", chain_cmd)).icon("chain")
.enabled(in_sketch)
.noundo()
+ .contract(&CHAIN_CONTRACT)
+ .output(output_schema_for::<ChainResult>)
.params("curve: id: the curves joined to it end to end (what a double-click selects)"),
- CommandSpec::new("sketch.solve", "Solve Sketch", solve_cmd).icon("compute")
+ CommandSpec::new("sketch.solve", "Solve Sketch", crate::checked!("sketch.solve", solve_cmd)).icon("compute")
.enabled(in_sketch)
.noundo()
+ .contract(&SOLVE_CONTRACT)
+ .output(output_schema_for::<SolveResult>)
.params("reports the solver status and degrees of freedom"),
];
@@ -305,14 +354,31 @@ pub(super) fn edit<T>(
strict: bool,
f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result<T>,
) -> Result<(T, Value)> {
+ let (out, info) = edit_solve(s, p, cmd, strict, f)?;
+ Ok((out, info.and_then(|info| serde_json::to_value(info).ok()).unwrap_or(Value::Null)))
+}
+
+/// [`edit`] with the solve as its typed value (`None`: the edit did not solve the sketch again).
+pub(super) fn edit_solve<T>(
+ s: &mut Session,
+ p: &Value,
+ cmd: &str,
+ strict: bool,
+ f: impl FnOnce(&mut Sketch, &mut solidcraft_doc::Document) -> Result<T>,
+) -> Result<(T, Option<SketchSolve>)> {
let id = sketch_store::target(s, p, cmd)?;
let (out, rep) = edit_solved(s, id, strict, Analysis::Freedom, |sk, doc| Ok((f(sk, doc)?, Left::Unsolved)))?;
- Ok((out, rep.map(|rep| report_json(&rep)).unwrap_or(Value::Null)))
+ Ok((out, rep.as_ref().map(solve_info)))
}
/// A solve's outcome as commands return it.
+pub(super) fn solve_info(rep: &SolveReport) -> SketchSolve {
+ SketchSolve { solved: rep.keeps_orientation(), dof: rep.dof }
+}
+
+/// A solve's outcome as commands return it, as JSON.
pub(super) fn report_json(rep: &SolveReport) -> Value {
- json!({"solved": rep.keeps_orientation(), "dof": rep.dof})
+ serde_json::to_value(solve_info(rep)).unwrap_or(Value::Null)
}
/// What an [`edit_solved`] step leaves for the edit's own solve.
@@ -893,13 +959,10 @@ pub(super) fn frame_note(frame: Option<&str>, placement: &solidcraft_doc::Mat) -
/// The reply's `frame` for an explicit plane, with a note when a world plane went into a moved
/// or turned component (`placement`: that component's), where it differs from the component's own.
-pub(super) fn frame_reply(out: &mut Value, frame: Option<&str>, placement: &solidcraft_doc::Mat) {
- let Some(o) = out.as_object_mut() else { return };
+fn frame_reply(out: &mut CreateResult, frame: Option<&str>, placement: &solidcraft_doc::Mat) {
let Some(frame) = frame else { return };
- o.insert("frame".into(), json!(frame));
- if let Some(note) = frame_note(Some(frame), placement) {
- o.insert("note".into(), json!(note));
- }
+ out.frame = Frame::named(frame);
+ out.note = frame_note(Some(frame), placement).map(str::to_string);
}
/// The indices of `m`'s triangles by face, for `faces` faces (triangles of a face past that
@@ -935,6 +998,11 @@ pub(super) fn face_contains(m: &solidcraft_geom::Mesh, tris: &[usize], p: Vec3,
}
fn create_sketch(s: &mut Session, p: &Value) -> Result<Value> {
+ reply("sketch.create", new_sketch(s, p)?)
+}
+
+/// What `sketch.create` makes, from its parameters.
+fn new_sketch(s: &mut Session, p: &Value) -> Result<CreateResult> {
let cmd = "sketch.create";
// These name the plane, so they belong inside `plane`. Next to it they were ignored and the
// sketch went to XY (or the plane given) without a word.
@@ -973,7 +1041,7 @@ fn create_sketch(s: &mut Session, p: &Value) -> Result<Value> {
let made = plane_ref(s, p, cmd).and_then(|plane| create_sketch_on(s, p, plane, frame, cmd));
match made {
Ok(mut out) => {
- out["activated"] = json!({"component": component, "path": path});
+ out.activated = Some(Activated { component, path });
Ok(out)
}
Err(error) => {
@@ -984,11 +1052,11 @@ fn create_sketch(s: &mut Session, p: &Value) -> Result<Value> {
}
/// The rest of `sketch.create` once the active component is settled: `flip`, the sketch, the reply's `frame`.
-fn create_sketch_on(s: &mut Session, p: &Value, mut plane: PlaneRef, frame: Option<&str>, cmd: &str) -> Result<Value> {
+fn create_sketch_on(s: &mut Session, p: &Value, mut plane: PlaneRef, frame: Option<&str>, cmd: &str) -> Result<CreateResult> {
if let Some(about_y) = flip_param(s, p, &plane, cmd)? {
plane = PlaneRef::Flipped { base: Box::new(plane), about_y };
}
- let mut out = create_sketch_with_plane(s, p, plane, None)?;
+ let mut out = sketch_on_plane(s, p, plane, None)?;
frame_reply(&mut out, frame, &s.active_component_frame());
Ok(out)
}
@@ -1021,6 +1089,11 @@ pub(super) fn create_face_profile(s: &mut Session, p: &Value, body: &str, index:
}
pub(super) fn create_sketch_with_plane(s: &mut Session, p: &Value, plane: PlaneRef, internal_body: Option<(&str, usize)>) -> Result<Value> {
+ reply("sketch.create", sketch_on_plane(s, p, plane, internal_body)?)
+}
+
+/// A new sketch on `plane`, as `sketch.create` replies.
+fn sketch_on_plane(s: &mut Session, p: &Value, plane: PlaneRef, internal_body: Option<(&str, usize)>) -> Result<CreateResult> {
let before = entry_point(s);
if face::is_face(p) {
face::capture_positions(s, &plane)?;
@@ -1056,17 +1129,17 @@ pub(super) fn create_sketch_with_plane(s: &mut Session, p: &Value, plane: PlaneR
}
let attachment = s.doc.feature(id).and_then(|feature| match &feature.kind {
FeatureKind::Sketch { plane, .. } => Some(if face::anchor(plane).is_some() {
- "exact_face"
+ Attachment::ExactFace
} else if solidcraft_doc::sheet::plane_sheet_face(plane).is_some() {
- "sheet_face"
+ Attachment::SheetFace
} else if internal_body.is_some() {
- "internal_legacy_face"
+ Attachment::InternalLegacyFace
} else {
- "fixed"
+ Attachment::Fixed
}),
_ => None,
});
- Ok(json!({"sketch": id, "name": name, "projected": link,"attachment":attachment}))
+ Ok(CreateResult { sketch: id, name, projected: link, attachment, frame: None, note: None, activated: None, param_warnings: Vec::new() })
}
fn edit_sketch(s: &mut Session, p: &Value) -> Result<Value> {
@@ -3696,7 +3769,7 @@ fn dimension_text(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.dimension_text";
let key = str_(p, "dimension").ok_or_else(|| bad(cmd, "`dimension` must be a dimension id or parameter name"))?.to_string();
let at = if bool_(p, "reset").unwrap_or(false) { None } else { Some(req_vec2(cmd, p, "at")?) };
- let (id, info) = edit(s, p, cmd, false, |sk, _| {
+ let (id, info) = edit_solve(s, p, cmd, false, |sk, _| {
let c = sk
.constraints
.iter()
@@ -3706,7 +3779,7 @@ fn dimension_text(s: &mut Session, p: &Value) -> Result<Value> {
place_text(sk, &id, at);
Ok(id)
})?;
- Ok(json!({"dimension": id, "sketch": info}))
+ reply(cmd, DimensionTextResult { dimension: id, sketch: info, param_warnings: Vec::new() })
}
/// Dimension a point (or a parallel line) to line `l` as a diameter: when `l` is a centerline
@@ -3852,7 +3925,7 @@ fn construction(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "`curves` must list curve ids"));
}
let want = bool_(p, "value");
- let (n, info) = edit(s, p, cmd, false, |sk, _| {
+ let (n, info) = edit_solve(s, p, cmd, false, |sk, _| {
let cs: Vec<usize> =
ids.iter().map(|id| sk.curve_index(id).ok_or_else(|| bad(cmd, format!("unknown curve `{id}`")))).collect::<Result<_>>()?;
// The selection switches together (a slot or polygon as a whole): to construction
@@ -3876,7 +3949,7 @@ fn construction(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok((n, to))
})?;
- Ok(json!({"changed": n.0, "construction": n.1, "sketch": info}))
+ reply(cmd, ConstructionResult { changed: n.0, construction: n.1, sketch: info, param_warnings: Vec::new() })
}
fn sketch_delete(s: &mut Session, p: &Value) -> Result<Value> {
@@ -3885,7 +3958,7 @@ fn sketch_delete(s: &mut Session, p: &Value) -> Result<Value> {
if ids.is_empty() {
return Err(bad(cmd, "`entities` must list sketch entity ids"));
}
- let (n, info) = edit(s, p, cmd, false, |sk, doc| {
+ let (n, info) = edit_solve(s, p, cmd, false, |sk, doc| {
let mut curves = Vec::new();
let mut points = Vec::new();
let mut cons = Vec::new();
@@ -3960,7 +4033,7 @@ fn sketch_delete(s: &mut Session, p: &Value) -> Result<Value> {
})?;
// Dimension parameters may have been dropped; prune again with the stored sketch.
s.doc_mut().prune_model_params();
- Ok(json!({"deleted": n, "sketch": info}))
+ reply(cmd, DeleteResult { deleted: n, sketch: info, param_warnings: Vec::new() })
}
fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
@@ -3973,7 +4046,7 @@ fn move_point(s: &mut Session, p: &Value) -> Result<Value> {
let q = point_ref(sk, p.get("point"), cmd, "point")?;
Ok(((), drag_entity(sk, Ent::Point(q), &[], to, to, false, last).1.solve_again()))
})?;
- Ok(json!({"sketch": rep.as_ref().map(report_json)}))
+ reply(cmd, MovePointResult { sketch: rep.as_ref().map(solve_info), param_warnings: Vec::new() })
}
/// `sketch.move_points`: several points, each dragged to its own target, in one edit (one undo
@@ -4093,7 +4166,10 @@ fn drag_frame(s: &mut Session, p: &Value, live: bool) -> Result<(Value, Option<c
let sk = sketch_store::read(&s.doc, id)?;
let at = d.at(sk, from, to);
let rep = rep.or_else(|| last.map(|ss| SolveReport { status: solidcraft_sketch::SolveStatus::Solved, failing: Vec::new(), ..ss.report.clone() }));
- let out = json!({"sketch": rep.as_ref().map(report_json), "reached": d.reached, "at": [at.x, at.y], "retry": d.retry});
+ let out = reply(
+ cmd,
+ DragResult { sketch: rep.as_ref().map(solve_info), reached: d.reached, at: [at.x, at.y], retry: d.retry, param_warnings: Vec::new() },
+ )?;
Ok((out, rep.filter(|_| live).map(|report| crate::LiveEdit { sketch: id, report })))
}
@@ -4119,29 +4195,30 @@ fn drag_end(s: &mut Session, p: &Value) -> Result<Value> {
}
// A new constraint changed the document: `execute` evaluates the model after this.
if !std::sync::Arc::ptr_eq(&start, &s.doc) {
- return Ok(json!({"constraint": constraint, "sketch": constraint.get("sketch")}));
+ let sketch = constraint.get("sketch").and_then(|solve| serde_json::from_value(solve.clone()).ok());
+ return reply(cmd, DragEndResult { constraint, sketch, param_warnings: Vec::new() });
}
if s.model.is_stale() {
s.refresh();
}
- let report = s.model.result(id).and_then(|r| r.state.sketch(id)).map(|ss| report_json(&ss.report));
- Ok(json!({"constraint": constraint, "sketch": report}))
+ let sketch = s.model.result(id).and_then(|r| r.state.sketch(id)).map(|ss| solve_info(&ss.report));
+ reply(cmd, DragEndResult { constraint, sketch, param_warnings: Vec::new() })
}
/// The Sketch Palette options of a sketch, by their palette names (true = shown / on).
-fn options_json(v: &solidcraft_sketch::SketchView) -> Value {
- json!({
- "show_profile": !v.hide_profile,
- "show_points": !v.hide_points,
- "show_dimensions": !v.hide_dimensions,
- "show_constraints": !v.hide_constraints,
- "show_projected": !v.hide_projected,
- "show_construction": !v.hide_construction,
- "grid": !v.hide_grid,
- "snap": !v.no_snap,
- "slice": v.slice,
- "sketch_3d": v.three_d,
- })
+fn options_of(v: &solidcraft_sketch::SketchView) -> SketchOptions {
+ SketchOptions {
+ show_profile: !v.hide_profile,
+ show_points: !v.hide_points,
+ show_dimensions: !v.hide_dimensions,
+ show_constraints: !v.hide_constraints,
+ show_projected: !v.hide_projected,
+ show_construction: !v.hide_construction,
+ grid: !v.hide_grid,
+ snap: !v.no_snap,
+ slice: v.slice,
+ sketch_3d: v.three_d,
+ }
}
fn sketch_options(s: &mut Session, p: &Value) -> Result<Value> {
@@ -4166,9 +4243,10 @@ fn sketch_options(s: &mut Session, p: &Value) -> Result<Value> {
let set = |k: &str| bool_(p, k);
if keys.iter().all(|k| set(k).is_none()) {
let id = sketch_store::target(s, p, cmd)?;
- return Ok(json!({"options": options_json(&sketch_store::read(&s.doc, id)?.view)}));
+ let options = OptionsReply::Read { options: options_of(&sketch_store::read(&s.doc, id)?.view) };
+ return reply(cmd, OptionsResult { options, param_warnings: Vec::new() });
}
- let (v, info) = edit(s, p, cmd, false, |sk, _| {
+ let (v, info) = edit_solve(s, p, cmd, false, |sk, _| {
let v = &mut sk.view;
let put = |k: &str, flag: &mut bool, shown_means_off: bool| {
if let Some(b) = set(k) {
@@ -4185,9 +4263,9 @@ fn sketch_options(s: &mut Session, p: &Value) -> Result<Value> {
put("snap", &mut v.no_snap, true);
put("slice", &mut v.slice, false);
put("sketch_3d", &mut v.three_d, false);
- Ok(options_json(v))
+ Ok(options_of(v))
})?;
- Ok(json!({"options": v, "sketch": info}))
+ reply(cmd, OptionsResult { options: OptionsReply::Changed { options: v, sketch: info }, param_warnings: Vec::new() })
}
fn chain_cmd(s: &mut Session, p: &Value) -> Result<Value> {
@@ -4195,14 +4273,16 @@ fn chain_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let id = sketch_store::target(s, p, cmd)?;
let sk = sketch_store::read(&s.doc, id)?;
let c = curve_ref(sk, p.get("curve"), cmd, "curve")?;
- Ok(json!({"curves": ids_of(sk, &sk.chain(c))}))
+ reply(cmd, ChainResult { curves: ids_of(sk, &sk.chain(c)), param_warnings: Vec::new() })
}
fn solve_cmd(s: &mut Session, p: &Value) -> Result<Value> {
- let id = sketch_store::target(s, p, "sketch.solve")?;
+ let cmd = "sketch.solve";
+ let id = sketch_store::target(s, p, cmd)?;
let st = s.model.state();
let ss = st.sketch(id).ok_or_else(|| EngineError::Other("the sketch has not been evaluated".into()))?;
- Ok(json!({"status": ss.report.status, "dof": ss.report.dof, "failing": ss.report.failing, "profiles": ss.profiles.len()}))
+ let (status, dof, failing, profiles) = (ss.report.status.into(), ss.report.dof, ss.report.failing.clone(), ss.profiles.len());
+ reply(cmd, SolveResult { status, dof, failing, profiles, param_warnings: Vec::new() })
}
#[cfg(test)]
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 4038893742..8bfce59734 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -114,6 +114,7 @@ pub mod sketch_import;
pub mod sketch_inspect;
pub mod sketch_modify;
pub mod sketch_project;
+pub mod sketch_session;
pub mod sketch_shapes;
pub mod surface_analysis;
pub mod surface_boundary;
diff --git a/crates/engine/src/schema/sketch_session.rs b/crates/engine/src/schema/sketch_session.rs
new file mode 100644
index 0000000000..49a2433750
--- /dev/null
+++ b/crates/engine/src/schema/sketch_session.rs
@@ -0,0 +1,979 @@
+//! Contracts and result types for the sketch session commands in `cmd/sketch.rs`:
+//! `sketch.create`, `sketch.construction`, `sketch.delete`, `sketch.move_point`, `sketch.drag`,
+//! `sketch.drag_end`, `sketch.dimension_text`, `sketch.options`, `sketch.chain` and
+//! `sketch.solve` (#13224).
+//!
+//! 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. Whether a sketch, a curve, a point or a
+//! dimension exists stays the handler's to check, and so does everything that needs the design.
+//! 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.
+//!
+//! Some handlers read a key only in some cases, and the types read it only there too, so a call
+//! that works today gets no warning:
+//!
+//! - `sketch.create` reads `project_edges` only when `plane` is a picked face, and `frame` is
+//! for an explicit plane only. It refuses `face`, `origin`, `x_dir` and `y_dir` next to
+//! `plane` with a message that says where they belong, so they are listed (and can never be
+//! used) to keep that message in strict;
+//! - `sketch.dimension_text` reads `at` only without `reset: true`;
+//! - `sketch.drag_end` reads a constraint's `command` and `params` only when `constraint` is not
+//! `null`.
+//!
+//! A call with `live: true` of `sketch.drag` goes to the live runner, which the check doesn't
+//! wrap, so live frames are not checked yet.
+//!
+//! `sketch.options` refuses a key that is not one of its options with "unknown option"; the
+//! check names it first ("unknown key", with a suggestion) in warn and strict.
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Map, Value, json};
+
+use super::canvas::CanvasPlane;
+use super::check::{located, whole};
+use super::frame::SketchSolve;
+use super::motion::require;
+use super::sketch_ends::SketchTarget;
+use super::types::{LengthExpr, Point2, present};
+use crate::params;
+
+/// The words of `sketch.create`'s refusals, as `plane_frame` and `flip_param` give them.
+const FRAME_FORMS: &str = "`frame` must be \"world\" or \"component\"";
+const FRAME_NOT_EXPLICIT: &str =
+ "`frame` is for an explicit plane {origin, x_dir, y_dir}: a named plane is the component's own, and a face is where it is";
+const FLIP_FORMS: &str = "`flip` must be true, false, \"x\" or \"y\"";
+const FLIP_ON_FACE: &str = "`flip` is for origin, construction and explicit planes; a face already faces outward";
+const ACTIVATE_FORMS: &str = "`activate_part` must be true or false";
+
+/// The keys `sketch.create` refuses next to `plane`, and the form each belongs in.
+const MISPLACED: [(&str, &str); 4] = [
+ ("face", r#"{"plane": {"face": [x, y, z]}}"#),
+ ("origin", r#"{"plane": {"origin": [x, y, z], "x_dir": [..], "y_dir": [..]}}"#),
+ ("x_dir", r#"{"plane": {"origin": [x, y, z], "x_dir": [..], "y_dir": [..]}}"#),
+ ("y_dir", r#"{"plane": {"origin": [x, y, z], "x_dir": [..], "y_dir": [..]}}"#),
+];
+
+/// The message of a handler's refusal.
+fn message(e: crate::EngineError) -> String {
+ match e {
+ crate::EngineError::BadParams { msg, .. } => msg,
+ other => other.to_string(),
+ }
+}
+
+/// The handler's message for a value that is not what a key needs, kept whole.
+fn refuse<E: serde::de::Error>(message: impl std::fmt::Display) -> E {
+ E::custom(whole(message))
+}
+
+// ---------------------------------------------------------------------------------------------
+// Shared readers
+
+/// `key` as text, the handler's `str_`-and-refuse: a string, or `message`.
+macro_rules! text_key {
+ ($($name:ident: $message:literal),+ $(,)?) => {$(
+ fn $name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(s) => Ok(Some(s)),
+ _ => Err(refuse($message)),
+ }
+ }
+ )+};
+}
+
+text_key!(
+ point_id: "`point` must be a point reference",
+ entity_id: "`entity` must be a sketch point or curve",
+ curve_id: "`curve` must be a curve id",
+ dimension_id: "`dimension` must be a dimension id or parameter name",
+);
+
+/// A required point `[x, y]` as `req_vec2` reads it (`null` is refused).
+macro_rules! point_key {
+ ($($name:ident: $key:literal),+ $(,)?) => {$(
+ fn $name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Point2>, D::Error> {
+ params::vec2(&Value::deserialize(d)?)
+ .map(|p| Some(Point2(p)))
+ .ok_or_else(|| refuse(concat!("`", $key, "` must be a point [x, y]")))
+ }
+ )+};
+}
+
+point_key!(to_point: "to", at_point: "at");
+
+/// `from` of `sketch.drag`: a point, where `null` is read as left out (the grab is at `to`).
+fn from_point<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Point2>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Null => Ok(None),
+ v => params::vec2(&v).map(|p| Some(Point2(p))).ok_or_else(|| refuse("`from` must be a point [x, y]")),
+ }
+}
+
+/// Entity ids, as `params::string_list` reads a list of names: a list of text, or one text. An
+/// empty list, `null` included, is the handler's own refusal (`empty`).
+#[derive(Clone, Debug, PartialEq)]
+pub struct EntityIds(pub Vec<String>);
+
+fn entity_ids<'de, D: Deserializer<'de>>(d: D, key: &str, empty: &str) -> Result<Option<EntityIds>, D::Error> {
+ let mut given = Map::new();
+ given.insert(key.to_string(), Value::deserialize(d)?);
+ let list = params::string_list("", &Value::Object(given), key).map_err(|e| refuse::<D::Error>(message(e)))?;
+ if list.is_empty() { Err(refuse(empty)) } else { Ok(Some(EntityIds(list))) }
+}
+
+fn curves<'de, D: Deserializer<'de>>(d: D) -> Result<Option<EntityIds>, D::Error> {
+ entity_ids(d, "curves", "`curves` must list curve ids")
+}
+
+fn entities<'de, D: Deserializer<'de>>(d: D) -> Result<Option<EntityIds>, D::Error> {
+ entity_ids(d, "entities", "`entities` must list sketch entity ids")
+}
+
+impl JsonSchema for EntityIds {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchEntityIds".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Ids, as a list of text (at least one, at most 10000) or a single id.",
+ "anyOf": [
+ {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": params::MAX_STRING_LIST},
+ {"type": "string"}
+ ]
+ })
+ }
+}
+
+/// The ids of what a drag takes along: a list of text, as the handler reads `with`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DragWith(pub Vec<String>);
+
+fn with_ids<'de, D: Deserializer<'de>>(d: D) -> Result<Option<DragWith>, D::Error> {
+ const FORMS: &str = "`with` must be a list of sketch point or curve ids";
+ match Value::deserialize(d)? {
+ Value::Null => Ok(None),
+ Value::Array(ids) => ids
+ .into_iter()
+ .map(|v| if let Value::String(id) = v { Some(id) } else { None })
+ .collect::<Option<Vec<_>>>()
+ .map(|ids| Some(DragWith(ids)))
+ .ok_or_else(|| refuse(FORMS)),
+ _ => Err(refuse(FORMS)),
+ }
+}
+
+impl JsonSchema for DragWith {
+ fn schema_name() -> Cow<'static, str> {
+ "DragWith".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Point and curve ids, as a list. No more than the sketch has points and curves together.",
+ "type": "array",
+ "items": {"type": "string"}
+ })
+ }
+}
+
+/// An optional flag the handler reads with `bool_`, which takes a wrong type as absent: `null` is
+/// absent, and any other value that is not true or false is refused here.
+fn flag<'de, D: Deserializer<'de>>(d: D, key: &str) -> Result<Option<bool>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Null => Ok(None),
+ Value::Bool(b) => Ok(Some(b)),
+ _ => Err(refuse(format!("`{key}` must be true or false"))),
+ }
+}
+
+fn live<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
+ flag(d, "live")
+}
+
+fn reset<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
+ flag(d, "reset")
+}
+
+/// One flag each, as the handler reads them (see [`flag`]).
+macro_rules! option_flags {
+ ($($name:ident),+ $(,)?) => {$(
+ fn $name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
+ flag(d, stringify!($name))
+ }
+ )+};
+}
+
+option_flags!(value, show_profile, show_points, show_dimensions, show_constraints, show_projected, show_construction, grid, snap, slice, sketch_3d);
+
+// ---------------------------------------------------------------------------------------------
+// sketch.create
+
+/// A plane for a new sketch, as `sketch.create` reads `plane`: XY, XZ or YZ (or Top, Front or
+/// Right), a construction plane by name or id, a picked planar face, or an explicit plane. Kept
+/// as given, for the handler.
+#[derive(Clone, Debug, PartialEq)]
+pub struct SketchPlane(pub Value);
+
+impl<'de> Deserialize<'de> for SketchPlane {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ CanvasPlane::deserialize(d).map(|plane| SketchPlane(plane.0))
+ }
+}
+
+impl JsonSchema for SketchPlane {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchPlane".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ CanvasPlane::json_schema(generator)
+ }
+}
+
+/// `flip`: `true`, `false`, or the axis (`"x"` or `"y"`, any case) to turn the plane about.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Flip {
+ Flag(bool),
+ AboutX,
+ AboutY,
+}
+
+impl<'de> Deserialize<'de> for Flip {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Bool(b) => Ok(Flip::Flag(b)),
+ Value::String(a) if a.eq_ignore_ascii_case("x") => Ok(Flip::AboutX),
+ Value::String(a) if a.eq_ignore_ascii_case("y") => Ok(Flip::AboutY),
+ _ => Err(refuse(FLIP_FORMS)),
+ }
+ }
+}
+
+impl JsonSchema for Flip {
+ fn schema_name() -> Cow<'static, str> {
+ "Flip".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "false keeps the plane's own side; true turns it about its y axis (about x when y does not point upward) so the sketch's y axis stays upward; \"x\" or \"y\" (any case) turns it about that axis of the plane.",
+ "anyOf": [{"type": "boolean"}, {"type": "string", "pattern": "^[xXyY]$"}]
+ })
+ }
+}
+
+impl Flip {
+ /// Whether the plane is turned at all.
+ fn turns(self) -> bool {
+ self != Flip::Flag(false)
+ }
+}
+
+/// Which coordinates an explicit plane is in: `world` (the default) or the active component's
+/// own, `component`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
+#[serde(rename_all = "lowercase")]
+pub enum Frame {
+ // World coordinates (the default); the component's own coordinates.
+ World,
+ Component,
+}
+
+impl Frame {
+ /// The frame `plane_frame` names.
+ pub fn named(name: &str) -> Option<Frame> {
+ match name {
+ "world" => Some(Frame::World),
+ "component" => Some(Frame::Component),
+ _ => None,
+ }
+ }
+}
+
+/// A key `sketch.create` refuses next to `plane`: it belongs inside `plane`.
+#[derive(Debug)]
+pub struct InsidePlane;
+
+impl<'de> Deserialize<'de> for InsidePlane {
+ fn deserialize<D: Deserializer<'de>>(_: D) -> Result<Self, D::Error> {
+ Err(refuse("this key belongs inside `plane`"))
+ }
+}
+
+impl JsonSchema for InsidePlane {
+ fn schema_name() -> Cow<'static, str> {
+ "InsidePlane".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Not taken here, in any form: the call is refused, and the message says where it belongs. Put it inside `plane`.",
+ "not": {}
+ })
+ }
+}
+
+/// The keys of a `sketch.create` call.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CreateKeys {
+ /// The plane to sketch on: XY, XZ or YZ (also Top, Front, Right), a construction plane's
+ /// name or id, a picked planar face `{face: [x, y, z], body?, index?, path?, fixed?}`, or an
+ /// explicit plane `{origin?, x_dir, y_dir}` in mm. Default: XY. On XY, the sketch's x and y
+ /// run along world +X and +Y; on XZ, +X and -Z; on YZ, +Y and +Z. A face of a sheet metal
+ /// body attaches to its panel instead, in the flat pattern's coordinates; `fixed: true` keeps
+ /// the plane where the face is now. A named plane is the active component's own.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "SketchPlane")]
+ pub plane: Option<SketchPlane>,
+ /// Move the plane this far along its normal (mm or a length expression), before `flip`.
+ #[serde(default)]
+ pub offset: Option<LengthExpr>,
+ /// Not on a face: sketch the plane from its other side, so the normal and the default
+ /// extrude direction are reversed. Default: false.
+ #[serde(default)]
+ pub flip: Option<Flip>,
+ /// Which coordinates an explicit plane is in. Default: world. Only for an explicit plane
+ /// `{origin, x_dir, y_dir}`; the reply's `frame` says which, with a `note` when the active
+ /// component is moved or turned.
+ #[serde(default)]
+ pub frame: Option<Frame>,
+ /// Only on a picked face: project the face's edges into the sketch. Default: the session's
+ /// Auto Project setting.
+ #[serde(default)]
+ pub project_edges: Option<bool>,
+ /// Only on a face of a body of another component than the active one: activate that
+ /// component at the picked placement first, as `component.activate` would, and make the
+ /// sketch there. It stays active afterwards and the reply's `activated` names it. Default:
+ /// false.
+ #[serde(default)]
+ pub activate_part: Option<bool>,
+ /// The sketch's name. Default: numbered.
+ #[serde(default)]
+ pub name: Option<String>,
+ /// Refused: it belongs inside `plane`.
+ #[serde(default)]
+ #[schemars(with = "InsidePlane")]
+ pub face: Option<InsidePlane>,
+ /// Refused: it belongs inside `plane`.
+ #[serde(default)]
+ #[schemars(with = "InsidePlane")]
+ pub origin: Option<InsidePlane>,
+ /// Refused: it belongs inside `plane`.
+ #[serde(default)]
+ #[schemars(with = "InsidePlane")]
+ pub x_dir: Option<InsidePlane>,
+ /// Refused: it belongs inside `plane`.
+ #[serde(default)]
+ #[schemars(with = "InsidePlane")]
+ pub y_dir: Option<InsidePlane>,
+}
+
+/// `sketch.create`'s parameters: [`CreateKeys`], read in the handler's order, and `project_edges`
+/// only for a face, as the handler does.
+#[derive(Debug)]
+pub struct CreateParams(pub CreateKeys);
+
+impl<'de> Deserialize<'de> for CreateParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ for (key, example) in MISPLACED {
+ if value.get(key).is_some() {
+ return Err(refuse(format!("`{key}` belongs inside `plane`: {example}")));
+ }
+ }
+ if !matches!(value.get("activate_part"), None | Some(Value::Null | Value::Bool(_))) {
+ return Err(refuse(ACTIVATE_FORMS));
+ }
+ let face = value.get("plane").and_then(|plane| plane.get("face")).is_some();
+ let explicit = value.get("plane").is_some_and(Value::is_object) && !face;
+ let frame = match value.get("frame") {
+ None | Some(Value::Null) => false,
+ Some(Value::String(f)) if Frame::named(f).is_some() => true,
+ Some(_) => return Err(refuse(FRAME_FORMS)),
+ };
+ if frame && !explicit {
+ return Err(refuse(FRAME_NOT_EXPLICIT));
+ }
+ if let Some(plane) = value.get("plane") {
+ SketchPlane::deserialize(plane).map_err(|e| D::Error::custom(e.to_string()))?;
+ }
+ match value.get("flip") {
+ None | Some(Value::Null) => {}
+ Some(flip) => {
+ let flip = Flip::deserialize(flip).map_err(|e| D::Error::custom(e.to_string()))?;
+ if flip.turns() && face {
+ return Err(refuse(FLIP_ON_FACE));
+ }
+ }
+ }
+ // `project_edges` is read only for a picked face.
+ if !face && let Some(keys) = value.as_object_mut() {
+ keys.remove("project_edges");
+ }
+ serde_path_to_error::deserialize(&value).map(CreateParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for CreateParams {
+ fn schema_name() -> Cow<'static, str> {
+ "CreateParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ CreateKeys::json_schema(generator)
+ }
+}
+
+/// How a new sketch is attached to its plane: `exact_face`, `sheet_face`, `internal_legacy_face`
+/// or `fixed`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum Attachment {
+ // `exact_face`: a planar face of a body, exactly, so the sketch follows the face;
+ // `sheet_face`: the panel of a sheet metal body's flat pattern;
+ // `internal_legacy_face`: a face picked by a command that starts a sketch on a face
+ // (Extrude, Revolve, Press Pull);
+ // `fixed`: where the plane is (an origin, construction or explicit plane, or a face kept
+ // with `fixed`).
+ ExactFace,
+ SheetFace,
+ InternalLegacyFace,
+ Fixed,
+}
+
+/// The component `activate_part` made active.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct Activated {
+ /// The component, by id.
+ pub component: u64,
+ /// The placement's occurrence path (empty at the root).
+ pub path: Vec<u64>,
+}
+
+/// What `sketch.create` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CreateResult {
+ /// The new sketch's feature id.
+ pub sketch: u64,
+ /// Its name.
+ pub name: String,
+ /// On a face, the link id of the face's projected edges; null when none were projected.
+ pub projected: Option<String>,
+ /// How the sketch is attached to its plane.
+ pub attachment: Option<Attachment>,
+ /// For an explicit plane: which coordinates it was read in.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub frame: Option<Frame>,
+ /// With a world `frame`, when the active component is moved or turned: that the plane was
+ /// stored at its world place in the component.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub note: Option<String>,
+ /// With `activate_part`, when it made another component active.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub activated: Option<Activated>,
+ /// 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.construction, sketch.delete
+
+fn curves_required(schema: &mut Schema) {
+ require(schema, "curves");
+}
+
+fn entities_required(schema: &mut Schema) {
+ require(schema, "entities");
+}
+
+/// Switch curves between normal and construction. The selection switches together (a slot or
+/// polygon as a whole): to construction unless all of it already is. Projected curves may
+/// switch too. A centerline that becomes construction stops being a centerline, and a normal
+/// line is a finite one. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = curves_required)]
+pub struct ConstructionParams {
+ // Optional in the type and required in the schema (`curves_required`).
+ /// The curves, by id.
+ #[serde(default, deserialize_with = "curves", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "EntityIds")]
+ pub curves: Option<EntityIds>,
+ /// True makes them construction, false makes them normal. Default: construction unless all of
+ /// them already are.
+ #[serde(default, deserialize_with = "value", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub value: Option<bool>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// What `sketch.construction` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ConstructionResult {
+ /// How many curves changed.
+ pub changed: usize,
+ /// Whether they are construction now.
+ pub construction: bool,
+ /// The sketch's solve; null when it was not solved again.
+ pub sketch: Option<SketchSolve>,
+ /// 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>,
+}
+
+/// Delete curves, points and constraints (dimensions too) from a sketch, by id; a sketch's
+/// wires and linked geometry too. The sketch origin cannot be deleted. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = entities_required)]
+pub struct DeleteParams {
+ // Optional in the type and required in the schema (`entities_required`).
+ /// What to delete: curve, point, constraint, wire or link ids.
+ #[serde(default, deserialize_with = "entities", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "EntityIds")]
+ pub entities: Option<EntityIds>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// What `sketch.delete` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DeleteResult {
+ /// How many ids were given (all of them were found).
+ pub deleted: usize,
+ /// The sketch's solve; null when it was not solved again.
+ pub sketch: Option<SketchSolve>,
+ /// 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.move_point, sketch.drag, sketch.drag_end
+
+fn move_point_required(schema: &mut Schema) {
+ require(schema, "point");
+ require(schema, "to");
+}
+
+/// Move a sketch point to a position and solve the sketch within its constraints: the point
+/// goes as far toward it as they allow. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = move_point_required)]
+pub struct MovePointParams {
+ // `point` and `to` are optional in the type and required in the schema
+ // (`move_point_required`).
+ /// The point, by id (`p3`, `l1.end`, `origin`).
+ #[serde(default, deserialize_with = "point_id", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub point: Option<String>,
+ /// Where to move it, in sketch coordinates (mm).
+ #[serde(default, deserialize_with = "to_point", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point2")]
+ pub to: Option<Point2>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// What `sketch.move_point` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MovePointResult {
+ /// The sketch's solve; null when it was not solved again.
+ pub sketch: Option<SketchSolve>,
+ /// 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>,
+}
+
+fn drag_required(schema: &mut Schema) {
+ require(schema, "entity");
+ require(schema, "to");
+}
+
+/// Drag a sketch point or curve from where it was grabbed to a position: points and the
+/// material point grabbed on a line move toward it within the design constraints, and when exact
+/// placement is impossible, bounded feasible steps minimize the cursor distance. Splines slide
+/// by `to` minus `from`; a circle or arc grabbed on its edge takes the radius to `to`. Long
+/// moves keep the solution branch, and arcs cannot sweep through their starts. With
+/// `live: true` (one frame of a drag; such calls are not checked against this schema yet), later
+/// features stay stale until `sketch.drag_end`, and `dof` stays from before the drag.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = drag_required)]
+pub struct DragParams {
+ // `entity` and `to` are optional in the type and required in the schema (`drag_required`).
+ /// The point or curve to drag, by id.
+ #[serde(default, deserialize_with = "entity_id", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub entity: Option<String>,
+ /// Where it was grabbed, in sketch coordinates (mm). Default: `to`.
+ #[serde(default, deserialize_with = "from_point", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<Point2>")]
+ pub from: Option<Point2>,
+ /// Where it is dragged to, in sketch coordinates (mm).
+ #[serde(default, deserialize_with = "to_point", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point2")]
+ pub to: Option<Point2>,
+ /// Other points and curves that move with the entity, as one translation (circles keep
+ /// their radii).
+ #[serde(default, deserialize_with = "with_ids", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<DragWith>")]
+ pub with: Option<DragWith>,
+ /// One frame of an interactive drag: the sketch is solved and shown, and the features after
+ /// it stay as they were until `sketch.drag_end`. Default: false.
+ #[serde(default, deserialize_with = "live", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub live: Option<bool>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// What `sketch.drag` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DragResult {
+ /// The sketch's solve; null when it was not solved again.
+ pub sketch: Option<SketchSolve>,
+ /// How far the drag got: progress projected onto the requested move, 0 to 1.
+ pub reached: f64,
+ /// Where the grabbed position is now, for the next frame: [x, y].
+ pub at: [f64; 2],
+ /// Whether work stopped at its budget after making progress: another frame can continue.
+ pub retry: bool,
+ /// 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>,
+}
+
+/// The constraint a drag let go on, as `sketch.drag_end` reads `constraint`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct DragConstraint {
+ /// A `sketch.constraint.*` command.
+ pub command: String,
+ /// Its parameters, as that command takes them. Default: none.
+ pub params: Option<Value>,
+}
+
+impl<'de> Deserialize<'de> for DragConstraint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let value = Value::deserialize(d)?;
+ let name = value.get("command").and_then(Value::as_str).unwrap_or_default();
+ if !crate::cmd::find_command(name).is_some_and(|spec| spec.id.starts_with("sketch.constraint.")) {
+ return Err(refuse("`constraint.command` must be a sketch.constraint.* command"));
+ }
+ Ok(DragConstraint { command: name.to_string(), params: value.get("params").cloned() })
+ }
+}
+
+impl JsonSchema for DragConstraint {
+ fn schema_name() -> Cow<'static, str> {
+ "DragConstraint".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "The constraint the drag let go on: a `sketch.constraint.*` command and its parameters. It is added when it does not over-constrain the sketch.",
+ "type": "object",
+ "properties": {
+ "command": {"description": "A sketch.constraint.* command id.", "type": "string", "pattern": "^sketch\\.constraint\\."},
+ "params": {"description": "The command's parameters."}
+ },
+ "required": ["command"]
+ })
+ }
+}
+
+/// End a drag made of `sketch.drag` frames with `live: true`: add the constraint it let go on
+/// (not kept if it over-constrains the sketch), then evaluate the whole model once. Returns the
+/// constraint's result and the sketch's solved state and degrees of freedom. It reads only the
+/// design, not the evaluated model.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct DragEndParams {
+ /// The constraint to add, `{command, params}`. Default: none.
+ #[serde(default)]
+ pub constraint: Option<DragConstraint>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// What `sketch.drag_end` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DragEndResult {
+ /// What the constraint command returned; `{"error": message}` when it could not be added (it
+ /// is not kept); null when no constraint was given.
+ pub constraint: Value,
+ /// The sketch's solve; null when it was not solved again.
+ pub sketch: Option<SketchSolve>,
+ /// 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.dimension_text
+
+/// `sketch.dimension_text`'s keys.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = dimension_text_required)]
+pub struct DimensionTextKeys {
+ // `dimension` is optional in the type and required in the schema, and so is `at` unless
+ // `reset` is true (`dimension_text_required`).
+ /// The dimension: a constraint id, or the name of the parameter it drives.
+ #[serde(default, deserialize_with = "dimension_id", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub dimension: Option<String>,
+ /// Where the text's centre goes, in sketch coordinates (mm). Not read with `reset: true`.
+ #[serde(default, deserialize_with = "at_point", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point2")]
+ pub at: Option<Point2>,
+ /// True puts the text back in its default place; `at` is then not read. Default: false.
+ #[serde(default, deserialize_with = "reset", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub reset: Option<bool>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn dimension_text_required(schema: &mut Schema) {
+ require(schema, "dimension");
+ schema.insert("anyOf".into(), json!([{"required": ["at"]}, {"required": ["reset"], "properties": {"reset": {"enum": [true]}}}]));
+}
+
+/// Move the text of a dimension to a position in the sketch, or back to its default place. The
+/// text is kept relative to the dimension, so it follows the dimension when the sketch changes.
+/// One undo step.
+#[derive(Debug)]
+pub struct DimensionTextParams(pub DimensionTextKeys);
+
+impl<'de> Deserialize<'de> for DimensionTextParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ // `at` is read only without `reset: true`.
+ if value.get("reset").and_then(Value::as_bool) == Some(true)
+ && let Some(keys) = value.as_object_mut()
+ {
+ keys.remove("at");
+ }
+ serde_path_to_error::deserialize(&value).map(DimensionTextParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for DimensionTextParams {
+ fn schema_name() -> Cow<'static, str> {
+ "DimensionTextParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let mut schema = DimensionTextKeys::json_schema(generator);
+ schema.insert(
+ "description".into(),
+ "Move the text of a dimension to a position in the sketch, or back to its default place. The text is kept relative to the dimension, so it follows the dimension when the sketch changes. One undo step."
+ .into(),
+ );
+ schema
+ }
+}
+
+/// What `sketch.dimension_text` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DimensionTextResult {
+ /// The dimension's constraint id.
+ pub dimension: String,
+ /// The sketch's solve; null when it was not solved again.
+ pub sketch: Option<SketchSolve>,
+ /// 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.options
+
+/// Show or hide what a sketch's palette shows, and read the options. Without any option, only
+/// reads them. Changing an option is one undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct OptionsParams {
+ /// Show the profiles (the filled regions).
+ #[serde(default, deserialize_with = "show_profile", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub show_profile: Option<bool>,
+ /// Show the points.
+ #[serde(default, deserialize_with = "show_points", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub show_points: Option<bool>,
+ /// Show the dimensions.
+ #[serde(default, deserialize_with = "show_dimensions", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub show_dimensions: Option<bool>,
+ /// Show the constraint marks.
+ #[serde(default, deserialize_with = "show_constraints", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub show_constraints: Option<bool>,
+ /// Show projected geometry.
+ #[serde(default, deserialize_with = "show_projected", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub show_projected: Option<bool>,
+ /// Show construction geometry.
+ #[serde(default, deserialize_with = "show_construction", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub show_construction: Option<bool>,
+ /// Show the grid.
+ #[serde(default, deserialize_with = "grid", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub grid: Option<bool>,
+ /// Clicks snap to the grid.
+ #[serde(default, deserialize_with = "snap", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub snap: Option<bool>,
+ /// Cut away the model in front of the sketch plane while editing.
+ #[serde(default, deserialize_with = "slice", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub slice: Option<bool>,
+ /// Make it a 3D sketch: drawing may leave the sketch plane.
+ #[serde(default, deserialize_with = "sketch_3d", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<bool>")]
+ pub sketch_3d: Option<bool>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// A sketch's palette options: true is shown (or on).
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchOptions {
+ /// The profiles are shown.
+ pub show_profile: bool,
+ /// The points are shown.
+ pub show_points: bool,
+ /// The dimensions are shown.
+ pub show_dimensions: bool,
+ /// The constraint marks are shown.
+ pub show_constraints: bool,
+ /// Projected geometry is shown.
+ pub show_projected: bool,
+ /// Construction geometry is shown.
+ pub show_construction: bool,
+ /// The grid is shown.
+ pub grid: bool,
+ /// Clicks snap to the grid.
+ pub snap: bool,
+ /// The model in front of the sketch plane is cut away while editing.
+ pub slice: bool,
+ /// It is a 3D sketch: drawing may leave the sketch plane.
+ pub sketch_3d: bool,
+}
+
+/// What `sketch.options` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OptionsResult {
+ /// The options as they are, or as they are after a change; with a change, also the sketch's
+ /// solve.
+ #[serde(flatten)]
+ pub options: OptionsReply,
+ /// 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>,
+}
+
+/// The options as they are, or as they are after a change.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum OptionsReply {
+ /// No option was given: only read.
+ Read {
+ /// All the options.
+ options: SketchOptions,
+ },
+ /// Options were given: set.
+ Changed {
+ /// All the options, after the change.
+ options: SketchOptions,
+ /// The sketch's solve; null when it was not solved again.
+ sketch: Option<SketchSolve>,
+ },
+}
+
+// ---------------------------------------------------------------------------------------------
+// sketch.chain, sketch.solve
+
+fn curve_required(schema: &mut Schema) {
+ require(schema, "curve");
+}
+
+/// The curves joined end to end to a curve, as a double-click selects them. The design is not
+/// changed.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = curve_required)]
+pub struct ChainParams {
+ // Optional in the type and required in the schema (`curve_required`).
+ /// The curve, by id.
+ #[serde(default, deserialize_with = "curve_id", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub curve: Option<String>,
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// What `sketch.chain` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ChainResult {
+ /// The chain's curves, by id, the given one included.
+ pub curves: Vec<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// Report a sketch's solver status and degrees of freedom, as last evaluated. The design is not
+/// changed.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct SolveParams {
+ /// The sketch. Default: the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// Whether the solver satisfied the constraints: `solved` or `failed`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum SolveOutcome {
+ // `solved`: all constraints are satisfied; `failed`: they conflict (or the solver could not
+ // satisfy them) and the geometry stays as it was before solving.
+ Solved,
+ Failed,
+}
+
+impl From<solidcraft_sketch::SolveStatus> for SolveOutcome {
+ fn from(status: solidcraft_sketch::SolveStatus) -> Self {
+ match status {
+ solidcraft_sketch::SolveStatus::Solved => SolveOutcome::Solved,
+ solidcraft_sketch::SolveStatus::Failed => SolveOutcome::Failed,
+ }
+ }
+}
+
+/// What `sketch.solve` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SolveResult {
+ /// The solver's status.
+ pub status: SolveOutcome,
+ /// The degrees of freedom left (0: fully constrained).
+ pub dof: usize,
+ /// The constraints still violated after a failed solve, by id.
+ pub failing: Vec<String>,
+ /// How many profiles the sketch has.
+ pub profiles: usize,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "sketch_session_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/sketch_session_tests.rs b/crates/engine/src/schema/sketch_session_tests.rs
new file mode 100644
index 0000000000..34eb755c67
--- /dev/null
+++ b/crates/engine/src/schema/sketch_session_tests.rs
@@ -0,0 +1,593 @@
+use serde_json::{Value, json};
+
+use super::{
+ ChainParams, ChainResult, ConstructionParams, ConstructionResult, CreateParams, CreateResult, DeleteParams, DeleteResult, DimensionTextParams,
+ DimensionTextResult, DragEndParams, DragEndResult, DragParams, DragResult, MovePointParams, MovePointResult, OptionsParams, OptionsReply,
+ OptionsResult, SketchOptions, SolveParams, SolveResult,
+};
+use crate::Session;
+use crate::schema::tests::{assert_keys, conforms};
+use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};
+
+/// A session with a sketch being edited that holds a square (10 mm either side of the origin) and
+/// the ids of its four sides.
+fn editing(level: ParamCheck) -> (Session, Vec<String>) {
+ let mut s = Session { param_check: level, ..Session::default() };
+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"));
+ let r = s.execute("sketch.rectangle.center", &json!({"center": [0, 0], "corner": [10, 10]})).unwrap_or_else(|e| panic!("{e}"));
+ let sides = r["created"]["curves"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();
+ (s, sides)
+}
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+fn error(level: ParamCheck, id: &str, p: &Value) -> Option<String> {
+ let (mut s, _) = editing(level);
+ s.execute(id, p).err().map(|e| e.to_string())
+}
+
+/// A call the handler already refuses gets the same message in strict, with a sketch being edited.
+/// (`assert_strict_keeps_todays_errors` runs after the sketch is finished, so a refusal that comes
+/// from the design's side would read "no sketch is being edited" there.)
+fn assert_strict_keeps_todays_errors(cases: &[(&str, Value)]) {
+ for (id, p) in cases {
+ let off = error(ParamCheck::Off, id, p);
+ assert!(off.is_some(), "{id} {p} should fail today");
+ assert_eq!(error(ParamCheck::Strict, id, p), off, "{id} {p}");
+ }
+}
+
+fn messages(id: &str, p: Value) -> Vec<String> {
+ issues(id, &p).into_iter().map(|i| i.message).collect()
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(
+ input_schema_for::<CreateParams>(),
+ &["activate_part", "face", "flip", "frame", "name", "offset", "origin", "plane", "project_edges", "x_dir", "y_dir"],
+ );
+ assert_keys(input_schema_for::<ConstructionParams>(), &["curves", "sketch", "value"]);
+ assert_keys(input_schema_for::<DeleteParams>(), &["entities", "sketch"]);
+ assert_keys(input_schema_for::<MovePointParams>(), &["point", "sketch", "to"]);
+ assert_keys(input_schema_for::<DragParams>(), &["entity", "from", "live", "sketch", "to", "with"]);
+ assert_keys(input_schema_for::<DragEndParams>(), &["constraint", "sketch"]);
+ assert_keys(input_schema_for::<DimensionTextParams>(), &["at", "dimension", "reset", "sketch"]);
+ assert_keys(
+ input_schema_for::<OptionsParams>(),
+ &[
+ "grid",
+ "show_constraints",
+ "show_construction",
+ "show_dimensions",
+ "show_points",
+ "show_profile",
+ "show_projected",
+ "sketch",
+ "sketch_3d",
+ "slice",
+ "snap",
+ ],
+ );
+ assert_keys(input_schema_for::<ChainParams>(), &["curve", "sketch"]);
+ assert_keys(input_schema_for::<SolveParams>(), &["sketch"]);
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ assert_strict_keeps_todays_errors(&[
+ ("sketch.create", json!({"face": [0, 0, 0]})),
+ ("sketch.create", json!({"origin": null})),
+ ("sketch.create", json!({"x_dir": [1, 0, 0]})),
+ ("sketch.create", json!({"y_dir": 3})),
+ ("sketch.create", json!({"activate_part": "yes"})),
+ ("sketch.create", json!({"frame": "local", "plane": {"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})),
+ ("sketch.create", json!({"frame": 1})),
+ ("sketch.create", json!({"frame": "world"})),
+ ("sketch.create", json!({"frame": "component", "plane": "XY"})),
+ ("sketch.create", json!({"plane": true})),
+ ("sketch.create", json!({"plane": null})),
+ ("sketch.create", json!({"plane": [1]})),
+ ("sketch.create", json!({"plane": 1.5})),
+ ("sketch.create", json!({"plane": -1})),
+ ("sketch.create", json!({"plane": "Nope"})),
+ ("sketch.create", json!({"plane": {"x_dir": [1, 0, 0]}})),
+ ("sketch.create", json!({"plane": {"y_dir": [1, 0, 0]}})),
+ ("sketch.create", json!({"plane": {"x_dir": [1, 0, 0], "y_dir": [2, 0, 0]}})),
+ ("sketch.create", json!({"plane": {"origin": "x", "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})),
+ ("sketch.create", json!({"plane": {"face": 5}})),
+ ("sketch.create", json!({"plane": {"face": [0, 0, 0], "fixed": "yes"}})),
+ ("sketch.create", json!({"plane": {"face": [0, 0, 0], "body": ""}})),
+ ("sketch.create", json!({"plane": {"face": [0, 0, 0], "body": "B"}})),
+ ("sketch.create", json!({"plane": {"face": [0, 0, 0], "index": -1}})),
+ ("sketch.create", json!({"plane": {"face": [0, 0, 0], "path": [0]}})),
+ ("sketch.create", json!({"plane": {"face": [0, 0, 0], "path": "x"}})),
+ ("sketch.create", json!({"flip": "z"})),
+ ("sketch.create", json!({"flip": 1})),
+ ("sketch.construction", json!({})),
+ ("sketch.construction", json!({"curves": []})),
+ ("sketch.construction", json!({"curves": null})),
+ ("sketch.construction", json!({"curves": [1]})),
+ ("sketch.construction", json!({"curves": ["l1", 2]})),
+ ("sketch.construction", json!({"curves": 5})),
+ ("sketch.construction", json!({"curves": ["nope"]})),
+ ("sketch.construction", json!({"curves": ["l1"], "sketch": true})),
+ ("sketch.construction", json!({"curves": ["l1"], "sketch": -1})),
+ ("sketch.construction", json!({"curves": ["l1"], "sketch": 99})),
+ ("sketch.delete", json!({})),
+ ("sketch.delete", json!({"entities": []})),
+ ("sketch.delete", json!({"entities": {"a": 1}})),
+ ("sketch.delete", json!({"entities": ["nope"]})),
+ ("sketch.delete", json!({"entities": ["origin"]})),
+ ("sketch.move_point", json!({})),
+ ("sketch.move_point", json!({"to": [1, 2]})),
+ ("sketch.move_point", json!({"to": [1, 2], "point": 5})),
+ ("sketch.move_point", json!({"to": [1, 2], "point": null})),
+ ("sketch.move_point", json!({"to": "x", "point": "origin"})),
+ ("sketch.move_point", json!({"to": null, "point": "origin"})),
+ ("sketch.move_point", json!({"to": [1], "point": "origin"})),
+ ("sketch.move_point", json!({"to": [1, 2], "point": "nope"})),
+ ("sketch.drag", json!({})),
+ ("sketch.drag", json!({"to": [1, 2]})),
+ ("sketch.drag", json!({"to": [1, 2], "entity": 3})),
+ ("sketch.drag", json!({"to": [1, 2], "entity": "nope"})),
+ ("sketch.drag", json!({"to": 3, "entity": "l1"})),
+ ("sketch.drag", json!({"to": [1, 2], "from": "a", "entity": "l1"})),
+ ("sketch.drag", json!({"to": [1, 2], "from": [1], "entity": "l1"})),
+ ("sketch.drag", json!({"to": [1, 2], "entity": "l1", "with": "l2"})),
+ ("sketch.drag", json!({"to": [1, 2], "entity": "l1", "with": [1]})),
+ ("sketch.drag", json!({"to": [1, 2], "entity": "l1", "with": ["nope"]})),
+ ("sketch.drag_end", json!({"constraint": {"command": "solid.box"}})),
+ ("sketch.drag_end", json!({"constraint": {"command": 5}})),
+ ("sketch.drag_end", json!({"constraint": {}})),
+ ("sketch.drag_end", json!({"constraint": 5})),
+ ("sketch.drag_end", json!({"constraint": "sketch.constraint.fix"})),
+ ("sketch.drag_end", json!({"sketch": true})),
+ ("sketch.dimension_text", json!({})),
+ ("sketch.dimension_text", json!({"at": [1, 2]})),
+ ("sketch.dimension_text", json!({"dimension": 5, "at": [1, 2]})),
+ ("sketch.dimension_text", json!({"dimension": null, "reset": true})),
+ ("sketch.dimension_text", json!({"dimension": "d1"})),
+ ("sketch.dimension_text", json!({"dimension": "d1", "at": "x"})),
+ ("sketch.dimension_text", json!({"dimension": "d1", "at": null})),
+ ("sketch.dimension_text", json!({"dimension": "nope", "at": [1, 2]})),
+ ("sketch.options", json!({"sketch": true})),
+ ("sketch.options", json!({"sketch": 99})),
+ ("sketch.options", json!({"show_points": false, "sketch": "nope"})),
+ ("sketch.chain", json!({})),
+ ("sketch.chain", json!({"curve": 5})),
+ ("sketch.chain", json!({"curve": null})),
+ ("sketch.chain", json!({"curve": "nope"})),
+ ("sketch.chain", json!({"curve": "l1", "sketch": [1]})),
+ ("sketch.solve", json!({"sketch": true})),
+ ("sketch.solve", json!({"sketch": 99})),
+ ("sketch.solve", json!({"sketch": "nope"})),
+ ]);
+}
+
+/// A flip that is refused on a face gets the same message in strict.
+#[test]
+fn strict_keeps_the_flip_refusal_on_a_face() {
+ let error = |level: ParamCheck| {
+ let mut s = Session { param_check: level, ..Session::default() };
+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10}));
+ let at = json!({"face": [10, 10, 10]});
+ for flip in [json!(true), json!("x"), json!("Y")] {
+ let e = s.execute("sketch.create", &json!({"plane": at, "flip": flip}));
+ assert!(e.is_err(), "{flip}");
+ }
+ s.execute("sketch.create", &json!({"plane": at, "flip": true})).err().map(|e| e.to_string())
+ };
+ let off = error(ParamCheck::Off);
+ assert!(off.as_deref().is_some_and(|e| e.contains("a face already faces outward")), "{off:?}");
+ assert_eq!(error(ParamCheck::Strict), off);
+}
+
+/// `conforms` doesn't read patterns, so the text of the two that say what a reader checks.
+#[test]
+fn the_patterns_are_pinned() {
+ let schema = input_schema_for::<CreateParams>();
+ assert_eq!(schema.as_value().pointer("/$defs/Flip/anyOf/1/pattern"), Some(&json!("^[xXyY]$")));
+ let schema = input_schema_for::<DragEndParams>();
+ assert_eq!(schema.as_value().pointer("/$defs/DragConstraint/properties/command/pattern"), Some(&json!("^sketch\\.constraint\\.")));
+ for (flip, ok) in [("x", true), ("Y", true), ("z", false), ("xy", false), ("", false)] {
+ assert_eq!(messages("sketch.create", json!({"flip": flip})).is_empty(), ok, "{flip}");
+ }
+}
+
+/// Each key is read in the cases its handler reads it, so a call that works today gets no warning:
+/// `project_edges` is read only for a picked face, `frame` and `reset` as the handlers do, `at`
+/// only without `reset: true`, a constraint only when it is not `null`.
+#[test]
+fn the_types_read_each_key_as_the_handler_does() {
+ // sketch.create: `project_edges` is read only on a face; the handler ignores it elsewhere.
+ assert!(messages("sketch.create", json!({"plane": "XY", "project_edges": "yes"})).is_empty());
+ assert!(messages("sketch.create", json!({"project_edges": [1]})).is_empty());
+ assert_eq!(messages("sketch.create", json!({"plane": {"face": [0, 0, 1]}, "project_edges": "yes"})), ["`project_edges` must be true or false"]);
+ assert!(messages("sketch.create", json!({"plane": {"face": [0, 0, 1]}, "project_edges": false, "activate_part": true})).is_empty());
+ // `frame` is for an explicit plane only, and `null` reads as left out.
+ let explicit = json!({"origin": [0, 0, 1], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]});
+ assert!(messages("sketch.create", json!({"plane": explicit, "frame": "component"})).is_empty());
+ assert!(messages("sketch.create", json!({"plane": explicit, "frame": null, "flip": "X"})).is_empty());
+ assert!(messages("sketch.create", json!({"plane": "XZ", "frame": null, "flip": null, "offset": "w / 2", "name": "S"})).is_empty());
+ assert_eq!(messages("sketch.create", json!({"plane": explicit, "frame": "local"})), ["`frame` must be \"world\" or \"component\""]);
+ assert!(messages("sketch.create", json!({"plane": "XY", "frame": "world"}))[0].starts_with("`frame` is for an explicit plane"));
+ // The keys that belong inside `plane` are refused with their own message, not as unknown keys.
+ assert_eq!(messages("sketch.create", json!({"face": [0, 0, 1]})), [r#"`face` belongs inside `plane`: {"plane": {"face": [x, y, z]}}"#]);
+ assert_eq!(messages("sketch.create", json!({"plane": "XY", "x_dir": null})).len(), 1);
+ // A face is not flipped, but `flip: false` is fine.
+ assert!(messages("sketch.create", json!({"plane": {"face": [0, 0, 1]}, "flip": false})).is_empty());
+ assert_eq!(
+ messages("sketch.create", json!({"plane": {"face": [0, 0, 1]}, "flip": true})),
+ ["`flip` is for origin, construction and explicit planes; a face already faces outward"]
+ );
+
+ // sketch.dimension_text: `at` is read only without `reset: true`.
+ assert!(messages("sketch.dimension_text", json!({"dimension": "d1", "reset": true, "at": "anywhere"})).is_empty());
+ assert!(messages("sketch.dimension_text", json!({"dimension": "d1", "reset": true})).is_empty());
+ assert_eq!(messages("sketch.dimension_text", json!({"dimension": "d1", "reset": false, "at": 1})), ["`at` must be a point [x, y]"]);
+ assert_eq!(messages("sketch.dimension_text", json!({"dimension": "d1", "reset": "yes"})), ["`reset` must be true or false"]);
+ assert!(messages("sketch.dimension_text", json!({"dimension": "d1", "at": {"x": 1, "y": 2}})).is_empty());
+
+ // sketch.drag: `from` may be `null`; `with` too.
+ assert!(messages("sketch.drag", json!({"entity": "l1", "to": [1, 2], "from": null, "with": null, "live": null})).is_empty());
+ assert!(messages("sketch.drag", json!({"entity": "l1", "to": {"x": 1, "y": 2}, "from": [0, 0], "with": ["l2", "p3"], "live": false})).is_empty());
+ assert_eq!(messages("sketch.drag", json!({"entity": "l1", "to": [1, 2], "live": 1})), ["`live` must be true or false"]);
+
+ // sketch.drag_end: a constraint only when it is not `null`; its params are the command's own.
+ assert!(messages("sketch.drag_end", json!({"constraint": null, "sketch": null})).is_empty());
+ assert!(messages("sketch.drag_end", json!({"constraint": {"command": "sketch.constraint.fix", "params": {"point": "origin"}}})).is_empty());
+ assert!(messages("sketch.drag_end", json!({"constraint": {"command": "sketch.constraint.fix"}})).is_empty());
+ assert_eq!(
+ messages("sketch.drag_end", json!({"constraint": {"command": "sketch.line"}})),
+ ["`constraint.command` must be a sketch.constraint.* command"]
+ );
+
+ // Lists of ids: one text or a list of text, as `string_list` reads them.
+ assert!(messages("sketch.construction", json!({"curves": "l1", "value": null})).is_empty());
+ assert!(messages("sketch.delete", json!({"entities": ["l1", "p2", "d1"]})).is_empty());
+ assert_eq!(messages("sketch.construction", json!({"curves": ["l1", 2]})), ["`curves` must list names; the entry 2 is 2"]);
+ assert_eq!(messages("sketch.construction", json!({"curves": ["l1"], "value": "yes"})), ["`value` must be true or false"]);
+ assert_eq!(messages("sketch.delete", json!({"entities": true})), ["`entities` must be a list of names; it is true"]);
+
+ // sketch.options: the options are flags; anything else is named.
+ assert!(messages("sketch.options", json!({"show_points": false, "grid": true, "slice": null, "sketch": 3})).is_empty());
+ assert_eq!(messages("sketch.options", json!({"snap": "on"})), ["`snap` must be true or false"]);
+ assert_eq!(messages("sketch.options", json!({"show_profil": true})), ["unknown key `show_profil`; did you mean `show_profile`?"]);
+}
+
+/// What the types accept, the handlers accept in Off: each call below runs there and has no issue.
+#[test]
+fn what_the_types_accept_the_handlers_run() {
+ let (mut s, sides) = editing(ParamCheck::Off);
+ let bottom = sides[0].clone();
+ for (id, p) in [
+ ("sketch.solve", json!({"sketch": null})),
+ ("sketch.chain", json!({"curve": bottom, "sketch": null})),
+ ("sketch.options", json!({"show_points": null, "grid": null})),
+ ("sketch.construction", json!({"curves": bottom, "value": null})),
+ ("sketch.move_point", json!({"point": "origin", "to": {"x": 0, "y": 0}})),
+ ("sketch.drag", json!({"entity": bottom, "to": [0, -10], "from": null, "with": null, "live": null})),
+ ("sketch.drag_end", json!({"constraint": null})),
+ ("sketch.create", json!({"plane": "XY", "frame": null, "flip": false, "project_edges": "ignored"})),
+ ] {
+ assert!(messages(id, p.clone()).is_empty(), "{id} {p}");
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ }
+}
+
+/// The contracts say what the handlers need: the keys a handler refuses without are required in
+/// the schemas, though the types leave them to the handlers' messages.
+#[test]
+fn the_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::<CreateParams>(),
+ &[
+ (json!({}), true),
+ (json!({"plane": "XZ", "offset": 5, "flip": "x", "name": "S"}), true),
+ (json!({"plane": 3, "flip": true}), true),
+ (
+ json!({"plane": {"face": [1, 2, 3], "body": "B", "index": 2, "path": [1], "fixed": true}, "project_edges": false, "activate_part": true}),
+ true,
+ ),
+ (json!({"plane": {"origin": [0, 0, 1], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "frame": "component"}), true),
+ (json!({"plane": "XY", "frame": "nowhere"}), false),
+ (json!({"plane": 1.5}), false),
+ (json!({"plane": null}), false),
+ (json!({"face": [1, 2, 3]}), false),
+ (json!({"x_dir": null}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ConstructionParams>(),
+ &[
+ (json!({"curves": ["l1", "l2"]}), true),
+ (json!({"curves": "l1", "value": false, "sketch": "S"}), true),
+ (json!({}), false),
+ (json!({"curves": []}), false),
+ (json!({"curves": [1]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<DeleteParams>(),
+ &[
+ (json!({"entities": ["l1", "d1"]}), true),
+ (json!({"entities": "p3", "sketch": 4}), true),
+ (json!({}), false),
+ (json!({"entities": []}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<MovePointParams>(),
+ &[
+ (json!({"point": "l1.end", "to": [1, 2]}), true),
+ (json!({"point": "p1", "to": {"x": 1, "y": 2}}), true),
+ (json!({"to": [1, 2]}), false),
+ (json!({"point": "p1"}), false),
+ (json!({"point": 3, "to": [1, 2]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<DragParams>(),
+ &[
+ (json!({"entity": "l1", "to": [1, 2]}), true),
+ (json!({"entity": "c1", "from": [0, 0], "to": [1, 2], "with": ["p1"], "live": true, "sketch": "S"}), true),
+ (json!({"entity": "c1", "from": null, "to": [1, 2], "with": null}), true),
+ (json!({"entity": "l1"}), false),
+ (json!({"to": [1, 2]}), false),
+ (json!({"entity": "l1", "to": [1, 2], "with": "p1"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<DragEndParams>(),
+ &[
+ (json!({}), true),
+ (json!({"constraint": {"command": "sketch.constraint.fix", "params": {"point": "p1"}}}), true),
+ (json!({"constraint": {"params": {}}}), false),
+ (json!({"constraint": 5}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<DimensionTextParams>(),
+ &[
+ (json!({"dimension": "d1", "at": [1, 2]}), true),
+ (json!({"dimension": "d1", "reset": true}), true),
+ (json!({"dimension": "d1", "reset": true, "at": [1, 2]}), true),
+ (json!({"dimension": "d1", "reset": false}), false),
+ (json!({"dimension": "d1"}), false),
+ (json!({"at": [1, 2]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<OptionsParams>(),
+ &[(json!({}), true), (json!({"show_points": false, "sketch_3d": true, "sketch": "S"}), true), (json!({"grid": "yes"}), false)],
+ );
+ takes(
+ input_schema_for::<ChainParams>(),
+ &[(json!({"curve": "l1"}), true), (json!({"curve": "l1", "sketch": 2}), true), (json!({}), false), (json!({"curve": 1}), false)],
+ );
+ takes(input_schema_for::<SolveParams>(), &[(json!({}), true), (json!({"sketch": "S"}), true), (json!({"sketch": true}), false)]);
+}
+
+fn matches(schema: schemars::Schema, id: &str, reply: &Value) {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
+ assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");
+}
+
+/// Every form of Create Sketch, in Warn: a reply that matches the output schema, no warning.
+#[test]
+fn create_replies_match_the_output_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let made = |s: &mut Session, p: Value| {
+ let r = run(s, "sketch.create", p);
+ matches(output_schema_for::<CreateResult>(), "sketch.create", &r);
+ run(s, "sketch.finish", json!({}));
+ r
+ };
+ let first = made(&mut s, json!({"plane": "XY"}));
+ assert_eq!(first["attachment"], "fixed", "{first}");
+ assert!(first["projected"].is_null() && first.get("frame").is_none(), "{first}");
+ made(&mut s, json!({}));
+ made(&mut s, json!({"plane": "xz", "offset": 5, "name": "Wall", "flip": "x"}));
+ made(&mut s, json!({"plane": "YZ", "offset": "10 / 2", "flip": true, "activate_part": false}));
+ made(&mut s, json!({"plane": "XY", "flip": false, "frame": null, "project_edges": 7}));
+ let explicit = json!({"origin": [0, 0, 5], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]});
+ let world = made(&mut s, json!({"plane": explicit}));
+ assert_eq!(world["frame"], "world", "{world}");
+ let own = made(&mut s, json!({"plane": explicit, "frame": "component", "flip": "Y"}));
+ assert_eq!(own["frame"], "component", "{own}");
+ // A construction plane by name and by id.
+ let plane = run(&mut s, "construct.plane.offset", json!({"base": "XY", "offset": 12, "name": "Mid"}));
+ made(&mut s, json!({"plane": "Mid"}));
+ made(&mut s, json!({"plane": plane["feature"]}));
+ // A picked face, with its edges projected or not, and in another component.
+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "body_name": "Block"}));
+ let top = made(&mut s, json!({"plane": {"face": [10, 10, 10]}}));
+ assert_eq!(top["attachment"], "exact_face", "{top}");
+ assert!(top["projected"].is_string(), "{top}");
+ let bare = made(&mut s, json!({"plane": {"face": [10, 10, 10], "fixed": true}, "project_edges": false, "flip": false}));
+ assert!(bare["projected"].is_null(), "{bare}");
+ // The exact pick: the face's index is the one of the six that holds the point.
+ let exact = (0..6).find_map(|index| {
+ let pick = json!({"plane": {"face": [10, 10, 10], "body": "Block", "index": index}, "activate_part": true, "name": "On face"});
+ s.execute("sketch.create", &pick).ok().map(|r| (pick, r))
+ });
+ let (_, exact) = exact.unwrap_or_else(|| panic!("no face of the box holds the point"));
+ matches(output_schema_for::<CreateResult>(), "sketch.create", &exact);
+ assert_eq!(exact["attachment"], "exact_face", "{exact}");
+}
+
+/// The reply's `note` (a world plane into a moved component) and `activated` (a face of another
+/// component's body), in Warn: both match the output schema and carry no warning.
+#[test]
+fn create_note_and_activated_match_the_output_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let part = run(&mut s, "component.create", json!({"name": "Part", "grounded": false}));
+ run(&mut s, "occurrence.move", json!({"occurrence": part["occurrence"], "translate": [10, 0, 0]}));
+ let r = run(&mut s, "sketch.create", json!({"plane": {"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}}));
+ assert!(r["note"].as_str().is_some_and(|n| n.contains("world coordinates")) && r["frame"] == "world", "{r}");
+ matches(output_schema_for::<CreateResult>(), "sketch.create", &r);
+ run(&mut s, "sketch.finish", json!({}));
+ // Another component with a body, then the root active: a face pick with `activate_part`.
+ run(&mut s, "component.create", json!({"name": "Other", "grounded": true}));
+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 10, "body_name": "Block"}));
+ run(&mut s, "component.activate", json!({"component": 0}));
+ let r = (0..6)
+ .find_map(|index| {
+ let pick = json!({"plane": {"face": [10, 10, 10], "body": "Block", "index": index}, "activate_part": true});
+ s.execute("sketch.create", &pick).ok()
+ })
+ .unwrap_or_else(|| panic!("no face of the box holds the point"));
+ assert!(r["activated"]["component"].is_u64() && r["activated"]["path"].is_array(), "{r}");
+ matches(output_schema_for::<CreateResult>(), "sketch.create", &r);
+}
+
+/// The editing commands, in Warn, on a sketch being edited: each reply matches its output schema
+/// and carries no warning.
+#[test]
+fn editing_replies_match_the_output_schema() {
+ let (mut s, sides) = editing(ParamCheck::Warn);
+ let (bottom, right) = (sides[0].clone(), sides[1].clone());
+ let sketch = s.active_sketch.unwrap_or_default();
+
+ let r = run(&mut s, "sketch.solve", json!({}));
+ assert!(r["status"] == "solved" && r["failing"] == json!([]), "{r}");
+ matches(output_schema_for::<SolveResult>(), "sketch.solve", &r);
+ matches(output_schema_for::<SolveResult>(), "sketch.solve", &run(&mut s, "sketch.solve", json!({"sketch": sketch})));
+
+ let r = run(&mut s, "sketch.chain", json!({"curve": bottom}));
+ assert!(r["curves"].as_array().is_some_and(|c| c.iter().any(|id| id == bottom.as_str())), "{r}");
+ matches(output_schema_for::<ChainResult>(), "sketch.chain", &r);
+ matches(output_schema_for::<ChainResult>(), "sketch.chain", &run(&mut s, "sketch.chain", json!({"curve": right, "sketch": sketch})));
+
+ let r = run(&mut s, "sketch.options", json!({}));
+ assert!(r["options"]["show_points"] == true && r.get("sketch").is_none(), "{r}");
+ matches(output_schema_for::<OptionsResult>(), "sketch.options", &r);
+ let r = run(&mut s, "sketch.options", json!({"show_points": false, "grid": false, "slice": true, "sketch": sketch}));
+ assert!(r["options"]["show_points"] == false && r["options"]["slice"] == true && r["sketch"].is_object(), "{r}");
+ matches(output_schema_for::<OptionsResult>(), "sketch.options", &r);
+ let r = run(&mut s, "sketch.options", json!({"show_points": null, "snap": true}));
+ matches(output_schema_for::<OptionsResult>(), "sketch.options", &r);
+
+ let r = run(&mut s, "sketch.construction", json!({"curves": [bottom]}));
+ assert!(r["construction"] == true && r["changed"] == 1, "{r}");
+ matches(output_schema_for::<ConstructionResult>(), "sketch.construction", &r);
+ let r = run(&mut s, "sketch.construction", json!({"curves": bottom, "value": false, "sketch": sketch}));
+ assert!(r["construction"] == false && r["changed"] == 1, "{r}");
+ matches(output_schema_for::<ConstructionResult>(), "sketch.construction", &r);
+
+ let r = run(&mut s, "sketch.move_point", json!({"point": format!("{bottom}.start"), "to": [-12, -10]}));
+ assert!(r["sketch"].is_object(), "{r}");
+ matches(output_schema_for::<MovePointResult>(), "sketch.move_point", &r);
+ matches(
+ output_schema_for::<MovePointResult>(),
+ "sketch.move_point",
+ &run(&mut s, "sketch.move_point", json!({"point": "origin", "to": {"x": 1, "y": 1}})),
+ );
+
+ let d = run(&mut s, "sketch.dimension", json!({"entities": [right]}));
+ let param = d["param"].as_str().unwrap_or_default().to_string();
+ let r = run(&mut s, "sketch.dimension_text", json!({"dimension": param, "at": [30, 12]}));
+ assert!(r["dimension"].is_string(), "{r}");
+ let dimension = r["dimension"].clone();
+ matches(output_schema_for::<DimensionTextResult>(), "sketch.dimension_text", &r);
+ let r = run(&mut s, "sketch.dimension_text", json!({"dimension": dimension, "reset": true, "at": "ignored"}));
+ matches(output_schema_for::<DimensionTextResult>(), "sketch.dimension_text", &r);
+ let r = run(&mut s, "sketch.dimension_text", json!({"dimension": param, "reset": false, "at": [1, 2], "sketch": sketch}));
+ matches(output_schema_for::<DimensionTextResult>(), "sketch.dimension_text", &r);
+
+ let r = run(&mut s, "sketch.drag", json!({"entity": right, "from": [10, 0], "to": [14, 0]}));
+ assert!(r["reached"].is_number() && r["at"].is_array() && r["retry"] == false, "{r}");
+ matches(output_schema_for::<DragResult>(), "sketch.drag", &r);
+ let r = run(&mut s, "sketch.drag", json!({"entity": bottom, "to": [0, -10], "with": [right], "live": false, "sketch": sketch}));
+ matches(output_schema_for::<DragResult>(), "sketch.drag", &r);
+
+ let r = run(&mut s, "sketch.drag_end", json!({}));
+ assert!(r["constraint"].is_null(), "{r}");
+ matches(output_schema_for::<DragEndResult>(), "sketch.drag_end", &r);
+ let fix = json!({"command": "sketch.constraint.fix", "params": {"entity": format!("{bottom}.start")}});
+ let r = run(&mut s, "sketch.drag_end", json!({"constraint": fix, "sketch": sketch}));
+ assert!(r["constraint"]["result"].is_object() && r["sketch"] == r["constraint"]["sketch"], "{r}");
+ // The nested command is not warned about its own call by the outer one: its reply carries what
+ // its own contract found, here nothing.
+ matches(output_schema_for::<DragEndResult>(), "sketch.drag_end", &r);
+ let r = run(&mut s, "sketch.drag_end", json!({"constraint": null}));
+ matches(output_schema_for::<DragEndResult>(), "sketch.drag_end", &r);
+ // A constraint that cannot be added is not kept; the drag still ends.
+ let bad = json!({"command": "sketch.constraint.coincident", "params": {"a": "origin", "b": "origin"}});
+ let r = run(&mut s, "sketch.drag_end", json!({"constraint": bad}));
+ assert!(r["constraint"]["error"].is_string(), "{r}");
+ matches(output_schema_for::<DragEndResult>(), "sketch.drag_end", &r);
+
+ let r = run(&mut s, "sketch.delete", json!({"entities": [dimension, bottom]}));
+ assert_eq!(r["deleted"], 2, "{r}");
+ matches(output_schema_for::<DeleteResult>(), "sketch.delete", &r);
+ let r = run(&mut s, "sketch.delete", json!({"entities": right, "sketch": sketch}));
+ matches(output_schema_for::<DeleteResult>(), "sketch.delete", &r);
+}
+
+/// A misspelt key still runs in Warn and says so, with a reply that matches the output schema; in
+/// Strict the call is refused with the suggestion.
+#[test]
+fn a_misspelt_key_is_reported() {
+ let (mut s, sides) = editing(ParamCheck::Warn);
+ let bottom = sides[0].clone();
+ let cases = [
+ ("sketch.solve", json!({"skech": 1}), "skech", "sketch"),
+ ("sketch.chain", json!({"curve": bottom, "sketh": 1}), "sketh", "sketch"),
+ ("sketch.construction", json!({"curves": [bottom], "valu": true}), "valu", "value"),
+ ("sketch.move_point", json!({"point": "origin", "to": [1, 1], "too": [2, 2]}), "too", "to"),
+ ("sketch.drag", json!({"entity": bottom, "to": [0, -9], "frm": [0, -10]}), "frm", "from"),
+ ("sketch.drag_end", json!({"constrant": null}), "constrant", "constraint"),
+ ("sketch.delete", json!({"entities": [bottom], "sketch ": 1}), "sketch ", "sketch"),
+ ("sketch.create", json!({"plane": "XY", "ofset": 5}), "ofset", "offset"),
+ ];
+ for (id, p, wrong, right) in cases {
+ let issues = messages(id, p.clone());
+ assert_eq!(issues, [format!("unknown key `{wrong}`; did you mean `{right}`?")], "{id}");
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ assert_eq!(r["param_warnings"], json!(issues), "{id}: {r}");
+ }
+ // sketch.options refuses any key that is not an option itself, so it never replies with
+ // warnings; the shape it would have (flattened untagged enum plus `param_warnings`) still
+ // matches its schema.
+ let opts = serde_json::to_value(OptionsResult {
+ options: OptionsReply::Changed {
+ options: SketchOptions {
+ show_profile: true,
+ show_points: true,
+ show_dimensions: true,
+ show_constraints: true,
+ show_projected: true,
+ show_construction: true,
+ grid: true,
+ snap: true,
+ slice: false,
+ sketch_3d: false,
+ },
+ sketch: None,
+ },
+ param_warnings: vec!["w".into()],
+ })
+ .unwrap_or_default();
+ let schema = output_schema_for::<OptionsResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &opts) && opts["sketch"].is_null() && opts["param_warnings"][0] == "w", "{opts}");
+ // The warned reply still matches its schema.
+ let r = run(&mut s, "sketch.solve", json!({"skech": 1}));
+ let schema = output_schema_for::<SolveResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
+ let (mut strict, _) = editing(ParamCheck::Strict);
+ let e = strict.execute("sketch.solve", &json!({"skech": 1})).err().map(|e| e.to_string());
+ assert_eq!(e.as_deref(), Some("invalid parameters for `sketch.solve`: unknown key `skech`; did you mean `sketch`?"));
+ let e = strict.execute("sketch.options", &json!({"show_profil": true})).err().map(|e| e.to_string());
+ assert!(e.is_some_and(|e| e.contains("unknown key `show_profil`")));
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index a3d8ef67d7..f3abb04177 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -58,17 +58,8 @@ sheet.export_bend_table
sheet.export_dxf
sheet.flat_pattern
sheet.path_flange
-sketch.chain
-sketch.construction
-sketch.create
-sketch.delete
sketch.dimension
-sketch.dimension_text
-sketch.drag
-sketch.drag_end
sketch.draw.dimensioned
-sketch.move_point
-sketch.options
sketch.polygon.circumscribed
sketch.polygon.edge
sketch.polygon.inscribed
@@ -78,7 +69,6 @@ sketch.rectangle.three_point
sketch.rectangle.two_point
sketch.slot.center_to_center
sketch.slot.overall
-sketch.solve
solid.align
solid.chamfer
solid.coil
diff --git a/docs/book/src/dev/schemas.md b/docs/book/src/dev/schemas.md
index 68f1c3822a..30b3f590ec 100644
--- a/docs/book/src/dev/schemas.md
+++ b/docs/book/src/dev/schemas.md
@@ -61,10 +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 `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.
+ checked yet. `sketch.drag` and `sketch.edit_text` have their contracts (with `live` declared as
+ an optional `bool`) and their 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