Skip to content

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

Agents and scripts: the sketch modify commands describe their exact parameters and reply (#12551) (#12605)

PeppaWutz203ce2672bd5
diff --git a/crates/engine/src/cmd/sketch_modify.rs b/crates/engine/src/cmd/sketch_modify.rs
index e5d7a6eb69..21907b695a 100644
--- a/crates/engine/src/cmd/sketch_modify.rs
+++ b/crates/engine/src/cmd/sketch_modify.rs
@@ -13,6 +13,13 @@ use super::sketch::{add_c, coincident_points, dof_now, edit, ids_of, line_or_axi
use super::sketch_store;
use super::{CommandSpec, in_sketch};
use crate::params::{bad, bool_, expr, num, req_expr, req_vec2, str_, string_list, vec2, vec2_list};
+use crate::schema::sketch_modify::{
+ BreakParams, BreakResult, ChamferDistanceAngleParams, ChamferEqualParams, ChamferResult, ChamferTwoParams, CircularPatternParams, ExtendParams,
+ ExtendResult, FilletParams, FilletResult, MAX_BREAK_POINTS, MAX_COPIES, MAX_INSTANCES, MAX_PATH_POINTS, MirrorParams, MirrorResult, MoveParams,
+ MoveResult, OffsetBreakParams, OffsetBreakResult, OffsetParams, OffsetResult, OffsetSide, PatternResult, RectangularPatternParams, ScaleParams,
+ ScaleResult, TrimOutcome, TrimParams, TrimPathParams, TrimPathResult, TrimResult,
+};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
#[path = "sketch_pattern.rs"]
@@ -20,28 +27,54 @@ mod pattern;
#[path = "sketch_support.rs"]
mod support;
+const TRIM_CONTRACT: TypedContract<TrimParams> = TypedContract::new();
+const TRIM_PATH_CONTRACT: TypedContract<TrimPathParams> = TypedContract::new();
+const BREAK_CONTRACT: TypedContract<BreakParams> = TypedContract::new();
+const EXTEND_CONTRACT: TypedContract<ExtendParams> = TypedContract::new();
+const FILLET_CONTRACT: TypedContract<FilletParams> = TypedContract::new();
+const CHAMFER_EQUAL_CONTRACT: TypedContract<ChamferEqualParams> = TypedContract::new();
+const CHAMFER_TWO_CONTRACT: TypedContract<ChamferTwoParams> = TypedContract::new();
+const CHAMFER_DISTANCE_ANGLE_CONTRACT: TypedContract<ChamferDistanceAngleParams> = TypedContract::new();
+const OFFSET_CONTRACT: TypedContract<OffsetParams> = TypedContract::new();
+const OFFSET_BREAK_CONTRACT: TypedContract<OffsetBreakParams> = TypedContract::new();
+const MIRROR_CONTRACT: TypedContract<MirrorParams> = TypedContract::new();
+const MOVE_CONTRACT: TypedContract<MoveParams> = TypedContract::new();
+const SCALE_CONTRACT: TypedContract<ScaleParams> = TypedContract::new();
+const CIRCULAR_PATTERN_CONTRACT: TypedContract<CircularPatternParams> = TypedContract::new();
+const RECTANGULAR_PATTERN_CONTRACT: TypedContract<RectangularPatternParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("sketch.fillet", "Fillet", fillet)
+ CommandSpec::new("sketch.fillet", "Fillet", crate::checked!("sketch.fillet", fillet))
+ .contract(&FILLET_CONTRACT)
+ .output(output_schema_for::<FilletResult>)
.at("SKETCH", "MODIFY")
.icon("sketch_fillet")
.enabled(in_sketch)
.params(concat!("point: corner shared by two curves (\"l1.end\") | points: [corners] (all rounded alike: one radius, the rest equal; a corner is a point reference or {a, b}, the two curves meeting there) | a, b: two lines or arcs meeting at a corner (two lines that share no end are first brought to where they meet: the nearer end of a line that stops short moves there, and a line that runs past is cut there, losing its shorter piece); radius: expr. A corner that dimensions or constraints measure to stays as a virtual sharp corner on both curves' extensions (`virtual_corners`; the moved ones in `moved_to_virtual_corner`). An ellipse's axis line is never a side of a corner (also for the chamfers)", created_doc!())),
- CommandSpec::new("sketch.chamfer.equal_distance", "Equal Distance Chamfer", chamfer_equal)
+ CommandSpec::new("sketch.chamfer.equal_distance", "Equal Distance Chamfer", crate::checked!("sketch.chamfer.equal_distance", chamfer_equal))
+ .contract(&CHAMFER_EQUAL_CONTRACT)
+ .output(output_schema_for::<ChamferResult>)
.at("SKETCH", "MODIFY")
.icon("sketch_chamfer")
.enabled(in_sketch)
.params(concat!("point | points: [corners] (every corner cut alike; a corner is a point reference or {a, b}) | a, b: a corner of two lines (two that share no end are first brought to where they meet, as in sketch.fillet); distance", created_doc!())),
- CommandSpec::new("sketch.chamfer.distance_angle", "Distance and Angle Chamfer", chamfer_dist_angle)
+ CommandSpec::new("sketch.chamfer.distance_angle", "Distance and Angle Chamfer", crate::checked!("sketch.chamfer.distance_angle", chamfer_dist_angle))
+ .contract(&CHAMFER_DISTANCE_ANGLE_CONTRACT)
+ .output(output_schema_for::<ChamferResult>)
.at("SKETCH", "MODIFY")
.icon("sketch_chamfer_angle")
.enabled(in_sketch)
.params(concat!("point | points: [corners] (every corner cut alike; a corner is a point reference or {a, b}, and a point's `a` is the first of its two lines in curve order) | a, b: a corner of two lines (two that share no end are first brought to where they meet, as in sketch.fillet); distance: along a, angle: deg from a", created_doc!())),
- CommandSpec::new("sketch.chamfer.two_distance", "Two Distance Chamfer", chamfer_two)
+ CommandSpec::new("sketch.chamfer.two_distance", "Two Distance Chamfer", crate::checked!("sketch.chamfer.two_distance", chamfer_two))
+ .contract(&CHAMFER_TWO_CONTRACT)
+ .output(output_schema_for::<ChamferResult>)
.at("SKETCH", "MODIFY")
.icon("sketch_chamfer_two_distances")
.enabled(in_sketch)
.params(concat!("point | points: [corners] (every corner cut alike; a corner is a point reference or {a, b}, and a point's `a` is the first of its two lines in curve order) | a, b: a corner of two lines (two that share no end are first brought to where they meet, as in sketch.fillet); distance: along a, distance2: along b", created_doc!())),
- CommandSpec::new("sketch.offset", "Offset", offset)
+ CommandSpec::new("sketch.offset", "Offset", crate::checked!("sketch.offset", offset))
+ .contract(&OFFSET_CONTRACT)
+ .output(output_schema_for::<OffsetResult>)
.at("SKETCH", "MODIFY")
.icon("offset")
.key("O")
@@ -53,33 +86,45 @@ pub static COMMANDS: &[CommandSpec] = &[
"instances?: whole number or unitless expression, 1…100 (default 1): each instance after the first offsets the instance before it by the same distance again, so instance n stands n distances from the curves picked. Every instance of a side is driven by that side's own dimension, and each entry of `sides` names its `instance`; an instance the shape cannot take refuses the whole command",
created_doc!()
)),
- CommandSpec::new("sketch.offset.break", "Break Offset Association", break_offset).icon("sketch_break")
+ CommandSpec::new("sketch.offset.break", "Break Offset Association", crate::checked!("sketch.offset.break", break_offset))
+ .contract(&OFFSET_BREAK_CONTRACT)
+ .output(output_schema_for::<OffsetBreakResult>).icon("sketch_break")
.enabled(in_sketch)
.params("curve: derived offset curve id (retains geometry and makes its points editable)"),
- CommandSpec::new("sketch.trim", "Trim", trim)
+ CommandSpec::new("sketch.trim", "Trim", crate::checked!("sketch.trim", trim))
+ .contract(&TRIM_CONTRACT)
+ .output(output_schema_for::<TrimResult>)
.at("SKETCH", "MODIFY")
.icon("trim")
.key("T")
.enabled(in_sketch)
.params(concat!("curve: id, at: [x,y] (the piece to remove: between the nearest intersections around it). Trimming a line source or its single-line offset releases linked extents (offset_released: curve ids), retaining their driving normal-distance dimensions and parallel relations", created_doc!())),
- CommandSpec::new("sketch.trim.path", "Trim Along Path", trim_path)
+ CommandSpec::new("sketch.trim.path", "Trim Along Path", crate::checked!("sketch.trim.path", trim_path))
+ .contract(&TRIM_PATH_CONTRACT)
+ .output(output_schema_for::<TrimPathResult>)
.icon("trim")
.enabled(in_sketch)
.params(concat!(
"points: [[x,y]…] (2…2000 positions: a path drawn across the sketch). Every piece the path crosses is removed as `sketch.trim` removes the piece at that crossing, in the order the path crosses them; a piece crossed again after it is gone is not trimmed twice; eligible single-line offset outputs are trimmed while preserving their distance; projected geometry, infinite lines, other offset outputs and pieces trim refuses are passed over (why in `skipped`). dry_run?: bool (report without changing the design). One undo step → trimmed: [each trim's result], removed: [[[x,y]…]] (each removed piece as a polyline)",
created_doc!()
)),
- CommandSpec::new("sketch.extend", "Extend", extend)
+ CommandSpec::new("sketch.extend", "Extend", crate::checked!("sketch.extend", extend))
+ .contract(&EXTEND_CONTRACT)
+ .output(output_schema_for::<ExtendResult>)
.at("SKETCH", "MODIFY")
.icon("extend")
.enabled(in_sketch)
.params("curve: id, at: [x,y] near the end to extend (a line runs on to the nearest curve, or the previewed reach when nothing is in the way; an arc grows along its circle and closes into a whole circle when nothing stops it) | curves: [id, id] (two lines or arcs of this sketch, grown until they meet and joined there), at?: [[x,y],[x,y]] (one point per curve: the end to grow; default the end nearest the meeting point). `curve` and `curves` exclude each other; the two-curve form returns moved: the meeting point's id"),
- CommandSpec::new("sketch.break", "Break", break_cmd)
+ CommandSpec::new("sketch.break", "Break", crate::checked!("sketch.break", break_cmd))
+ .contract(&BREAK_CONTRACT)
+ .output(output_schema_for::<BreakResult>)
.at("SKETCH", "MODIFY")
.icon("sketch_break")
.enabled(in_sketch)
.params(concat!("curve: id, at: [x,y] (split at intersections; at a point where the curve ends and another curve meets, the curve gets its own end there and the two are no longer joined) | points: [[x,y]…] (1…1000 positions projected onto the curve; duplicates are merged)", created_doc!())),
- CommandSpec::new("sketch.scale", "Sketch Scale", scale)
+ CommandSpec::new("sketch.scale", "Sketch Scale", crate::checked!("sketch.scale", scale))
+ .contract(&SCALE_CONTRACT)
+ .output(output_schema_for::<ScaleResult>)
.at("SKETCH", "MODIFY")
.icon("sketch_scale")
.enabled(in_sketch)
@@ -90,34 +135,47 @@ pub static COMMANDS: &[CommandSpec] = &[
.key("G")
.enabled(in_sketch)
.params("entities: [curve/point ids], factor?: number (scale), angle?: degrees (turn), center?: [x,y] or point ref (what scales and turns stay put; default [0,0]), translate?: [dx,dy] (applied last); scales, turns and moves in one step"),
- CommandSpec::new("sketch.move", "Move/Copy Sketch Entities", move_copy)
+ CommandSpec::new("sketch.move", "Move/Copy Sketch Entities", crate::checked!("sketch.move", move_copy))
+ .contract(&MOVE_CONTRACT)
+ .output(output_schema_for::<MoveResult>)
.at("SKETCH", "MODIFY")
.icon("sketch_move")
.enabled(in_sketch)
.params(concat!("entities: [ids], translate?: [dx,dy], angle?: deg, center?: [x,y], copy?: bool, rotate_constraints?: bool (default true; false keeps constraints unchanged); a rotation turns the constraints tied to the sketch axes when all their geometry moves (horizontal and vertical relations and dimensions swap at odd quarter turns and stay at half turns, line angles turn with the line) and removes the horizontal and vertical ones that cannot hold at other angles; picking a text outline or linked point transforms its whole text source once, and copies remain editable text; copy also accepts drawn 3D curves, preserving exact arcs and height above the sketch plane", created_doc!())),
- CommandSpec::new("sketch.mirror", "Mirror", mirror)
+ CommandSpec::new("sketch.mirror", "Mirror", crate::checked!("sketch.mirror", mirror))
+ .contract(&MIRROR_CONTRACT)
+ .output(output_schema_for::<MirrorResult>)
.at("SKETCH", "PATTERN")
.icon("sketch_mirror")
.enabled(in_sketch)
.params(concat!("entities: [curve/point ids], line: straight curve id, x / y for a sketch axis, or {axis: X|Y|Z} for an origin axis (the mirror line is the axis's projection into the sketch plane; an axis perpendicular to the plane is refused) (symmetry constraints are added)", created_doc!())),
- CommandSpec::new("sketch.pattern.circular", "Circular Pattern", pattern_circular)
+ CommandSpec::new("sketch.pattern.circular", "Circular Pattern", crate::checked!("sketch.pattern.circular", pattern_circular))
+ .contract(&CIRCULAR_PATTERN_CONTRACT)
+ .output(output_schema_for::<PatternResult>)
.at("SKETCH", "PATTERN")
.icon("sketch_circ_pattern")
.enabled(in_sketch)
.params(concat!("entities: [ids], center: [x,y] or point ref, count: 2…500 (number or unitless expression, retained through edits), angle?: total deg, number or expression (default 360); alignment?: left|center|right (default right); reversed?: bool (default false). Quantity includes the original. Center balances copies around it; reversed flips the direction and extra side for even totals. Partial arcs span angle with angle/(count-1) spacing; full turns use angle/count. Adds associative pattern constraints; a coordinate center creates a constrainable point. Returns pattern and center ids. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())),
- CommandSpec::new("sketch.pattern.rectangular", "Rectangular Pattern", pattern_rect)
+ CommandSpec::new("sketch.pattern.rectangular", "Rectangular Pattern", crate::checked!("sketch.pattern.rectangular", pattern_rect))
+ .contract(&RECTANGULAR_PATTERN_CONTRACT)
+ .output(output_schema_for::<PatternResult>)
.at("SKETCH", "PATTERN")
.icon("sketch_rect_pattern")
.enabled(in_sketch)
.params(concat!("entities: [ids], count, spacing; count2?, spacing2?; counts: positive integer numbers or expressions, at most 500 instances total; spacings: length numbers or expressions; direction?, direction2?: sketch line ids (live references); dir?, dir2?: [x,y] vectors (defaults: sketch x, perpendicular to direction 1); alignment?, alignment2?: left|center|right (default right). Signed spacings reverse each direction. reversed?, reversed2?: bool (default false); reverses placement and the extra side of even centered totals. Quantities include the original. Adds associative pattern constraints. Returns pattern id. pattern?: existing pattern id to edit (omitted values retained; surviving instance ids retained)", created_doc!())),
];
+/// A reply built from its typed value, which is what the command's output schema describes.
+fn reply(cmd: &str, value: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(value).map_err(|e| bad(cmd, e.to_string()))
+}
+
+/// The strings of a JSON list, or `None` when it isn't one.
+fn strings(v: &Value) -> Option<Vec<String>> {
+ v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())
+}
+
const TOL: f64 = 1e-7;
-const MAX_COPIES: usize = 500;
-/// The most offsets `sketch.offset` stacks one behind the other in a single run. Each instance
-/// is its own association, so this stays below the sketch's own caps on analytic offset groups
-/// and free-form associations (both 128).
-const MAX_INSTANCES: usize = 100;
fn curve_arg(sk: &Sketch, p: &Value, cmd: &str) -> Result<usize> {
let id = str_(p, "curve").ok_or_else(|| bad(cmd, "`curve` must be a curve id"))?;
@@ -523,14 +581,11 @@ fn trim(s: &mut Session, p: &Value) -> Result<Value> {
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
let ci = curve_arg(sk, p, cmd)?;
let released = release_line_offsets(sk, doc, ci, cmd)?;
- let (mut out, _) = remove_piece(sk, ci, at, cmd)?;
- if !released.is_empty() {
- out["offset_released"] = json!(released);
- }
+ let (out, _) = remove_piece(sk, ci, at, cmd)?;
doc.prune_model_params();
- Ok(out)
+ Ok(out.released(released))
})?;
- Ok(json!({"result": out, "sketch": info}))
+ reply(cmd, TrimResult { result: out, sketch: info, param_warnings: Vec::new() })
}
/// Source lines and their single-line offsets can have independent endpoints. Materialize
@@ -685,7 +740,7 @@ fn hold_cut(sk: &mut Sketch, before: Option<&Sketch>, midpoints: &[usize], pi: u
/// Remove the piece of curve `ci` around `at`: between the nearest intersections on either
/// side, or the whole curve when nothing crosses it. Returns what `sketch.trim` reports and the
/// removed piece as a polyline.
-fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Value, Vec<Vec2>)> {
+fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(TrimOutcome, Vec<Vec2>)> {
loosen_along(sk, ci);
let id = sk.curves.get(ci).map(|c| c.id.clone()).unwrap_or_default();
if sk.curves.get(ci).is_some_and(|c| c.infinite) {
@@ -698,7 +753,8 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu
Some(pts) => pts.iter().filter_map(|q| Some(Vec2::new(q.get(0)?.as_f64()?, q.get(1)?.as_f64()?))).collect(),
None => whole,
};
- return Ok((json!({"trimmed": id, "pieces": r["curves"]}), removed));
+ let pieces = r.get("curves").and_then(strings);
+ return Ok((TrimOutcome::Freeform { trimmed: id, pieces, offset_released: Vec::new() }, removed));
}
let sh = sk.shape(ci).ok_or_else(|| bad(cmd, "curve"))?;
let tq = sh.param(sh.project(at));
@@ -707,7 +763,7 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu
// Nothing crosses it: the whole curve goes.
let removed = sk.polyline(ci);
sk.remove_curves(&[ci]);
- return Ok((json!({"deleted": id}), removed));
+ return Ok((TrimOutcome::Deleted { deleted: id, offset_released: Vec::new() }, removed));
}
refuse_offset_ends(sk, ci, "trim", cmd)?;
// For parallel lines, any point on the output measures the same normal distance.
@@ -788,14 +844,12 @@ fn remove_piece(sk: &mut Sketch, ci: usize, at: Vec2, cmd: &str) -> Result<(Valu
}
let removed = sk.polyline(gone);
sk.remove_curves(&[gone]);
- Ok((json!({"trimmed": id}), removed))
+ Ok((TrimOutcome::Trimmed { trimmed: id, offset_released: Vec::new() }, removed))
}
/// Most crossings one `sketch.trim.path` trims (each one splits a curve, so this also caps the
/// work a hostile path can ask for).
const MAX_PATH_TRIMS: usize = 500;
-/// Most positions in a trim path.
-const MAX_PATH_POINTS: usize = 2_000;
/// The first place along `path` after `after` (segment, parameter along it) where the path
/// crosses a curve that a trim may change: (segment, parameter, curve, the crossing point). Crossings are found on the
@@ -860,6 +914,10 @@ fn seg_cross(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Option<(f64, Vec2)> {
/// Preview or trim the pieces crossed by a path, skipping protected or unsupported geometry.
fn trim_path(s: &mut Session, p: &Value) -> Result<Value> {
+ reply("sketch.trim.path", trim_path_reply(s, p)?)
+}
+
+fn trim_path_reply(s: &mut Session, p: &Value) -> Result<TrimPathResult> {
let cmd = "sketch.trim.path";
let path = vec2_list(cmd, p, "points", MAX_PATH_POINTS)?;
if path.len() < 2 {
@@ -871,13 +929,13 @@ fn trim_path(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(o) = q.as_object_mut() {
o.remove("dry_run");
}
- let mut out = trim_path(&mut t, &q)?;
- out["dry_run"] = json!(true);
+ let mut out = trim_path_reply(&mut t, &q)?;
+ out.dry_run = Some(true);
return Ok(out);
}
let ((trimmed, removed, skipped), info) = edit(s, p, cmd, false, |sk, doc| {
- let mut trimmed: Vec<Value> = Vec::new();
- let mut removed: Vec<Value> = Vec::new();
+ let mut trimmed: Vec<TrimOutcome> = Vec::new();
+ let mut removed: Vec<Vec<[f64; 2]>> = Vec::new();
let mut skipped: Vec<String> = Vec::new();
let mut after = (0, f64::NEG_INFINITY);
for _ in 0..MAX_PATH_TRIMS {
@@ -886,16 +944,13 @@ fn trim_path(s: &mut Session, p: &Value) -> Result<Value> {
// A piece trim refuses (a closed spline crossed once) stays as it was.
let before = sk.clone();
let cut = release_line_offsets(sk, doc, ci, cmd).and_then(|released| {
- let (mut out, gone) = remove_piece(sk, ci, q, cmd)?;
- if !released.is_empty() {
- out["offset_released"] = json!(released);
- }
- Ok((out, gone))
+ let (out, gone) = remove_piece(sk, ci, q, cmd)?;
+ Ok((out.released(released), gone))
});
match cut {
Ok((out, gone)) => {
trimmed.push(out);
- removed.push(json!(gone.iter().map(|v| [v.x, v.y]).collect::<Vec<_>>()));
+ removed.push(gone.iter().map(|v| [v.x, v.y]).collect());
}
Err(e) => {
*sk = before;
@@ -912,7 +967,7 @@ fn trim_path(s: &mut Session, p: &Value) -> Result<Value> {
doc.prune_model_params();
Ok((trimmed, removed, skipped))
})?;
- Ok(json!({"trimmed": trimmed, "removed": removed, "skipped": skipped, "sketch": info}))
+ Ok(TrimPathResult { trimmed, removed, skipped, sketch: info, dry_run: None, param_warnings: Vec::new() })
}
/// Cuts closer than this to a curve's end or to each other are one place (mm).
@@ -920,7 +975,7 @@ const BREAK_GAP: f64 = 1e-6;
fn break_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sketch.break";
- let points = if p.get("points").is_some() { Some(vec2_list(cmd, p, "points", 1000)?) } else { None };
+ let points = if p.get("points").is_some() { Some(vec2_list(cmd, p, "points", MAX_BREAK_POINTS)?) } else { None };
let (out, info) = edit(s, p, cmd, false, |sk, doc| {
let ci = curve_arg(sk, p, cmd)?;
if points.is_none()
@@ -998,7 +1053,7 @@ fn break_cmd(s: &mut Session, p: &Value) -> Result<Value> {
tie(sk, &pieces)?;
Ok(ids_of(sk, &pieces))
})?;
- Ok(json!({"curves": out, "sketch": info}))
+ reply(cmd, BreakResult { curves: out, sketch: info, param_warnings: Vec::new() })
}
/// The end of curve `ci` at `at` that another curve also ends at or passes through: Break there
@@ -1478,7 +1533,7 @@ fn extend(s: &mut Session, p: &Value) -> Result<Value> {
};
grow_line(sk, ci, aim)
})?;
- Ok(json!({"moved": out, "sketch": info}))
+ reply(cmd, ExtendResult { moved: out, sketch: info, param_warnings: Vec::new() })
}
/// Grow line `ci` past the end `aim` names, to `aim.hit`: a new line when that end is joined to
@@ -2166,8 +2221,8 @@ fn fillet(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok((arcs, cons, pname, kept_json(kept)))
})?;
- let (vc, moved) = out.3;
- Ok(json!({"curves": out.0, "constraints": out.1, "param": out.2, "virtual_corners": vc, "moved_to_virtual_corner": moved, "sketch": info}))
+ let (curves, constraints, param, (virtual_corners, moved_to_virtual_corner)) = out;
+ reply(cmd, FilletResult { curves, constraints, param, virtual_corners, moved_to_virtual_corner, sketch: info, param_warnings: Vec::new() })
}
/// The virtual corners kept and the constraints moved to them, for a response.
@@ -2381,8 +2436,8 @@ fn chamfer(s: &mut Session, p: &Value, cmd: &str, dists: impl Fn(f64) -> Result<
}
Ok((ids_of(sk, &lines), kept_json(kept)))
})?;
- let (curves, (vc, moved)) = out;
- Ok(json!({"curves": curves, "virtual_corners": vc, "moved_to_virtual_corner": moved, "sketch": info}))
+ let (curves, (virtual_corners, moved_to_virtual_corner)) = out;
+ reply(cmd, ChamferResult { curves, virtual_corners, moved_to_virtual_corner, sketch: info, param_warnings: Vec::new() })
}
/// Cut one corner (`point` or `a`, `b`) of two lines with a straight line, `dists` giving how
@@ -3167,30 +3222,25 @@ fn offset(s: &mut Session, p: &Value) -> Result<Value> {
doc.params.retain(|p| !made.contains(&p.name) || param.as_ref() == Some(&p.name) || param2.as_ref() == Some(&p.name));
Ok((sides, param, param2))
})?;
- let curves: Vec<&String> = sides.iter().flat_map(|(_, side)| side.curves.iter()).collect();
- let constraints: Vec<&String> = sides.iter().flat_map(|(_, side)| side.constraints.iter()).collect();
- let each: Vec<Value> = sides
+ let curves: Vec<String> = sides.iter().flat_map(|(_, side)| side.curves.iter().cloned()).collect();
+ let constraints: Vec<String> = sides.iter().flat_map(|(_, side)| side.constraints.iter().cloned()).collect();
+ let each: Vec<OffsetSide> = sides
.iter()
- .map(|(instance, side)| {
- let mut entry = json!({"distance": side.distance, "curves": side.curves, "param": side.param, "instance": instance});
- if let Some(association) = &side.association {
- entry["association"] = json!(association);
- }
- entry
+ .map(|(instance, side)| OffsetSide {
+ distance: side.distance,
+ curves: side.curves.clone(),
+ param: side.param.clone(),
+ instance: *instance,
+ association: side.association.clone(),
})
.collect();
- let mut response = json!({"curves":curves,"constraints":constraints,"sketch":info,"sides":each,"param":param,"instances":instances});
- if let Some(param2) = param2 {
- response["param2"] = json!(param2);
- }
// One side keeps the single `association` it always returned. Two sides, or an instance
// behind another, have one each in `sides`, so there is no single association left to name.
- if let [(_, only)] = sides.as_slice()
- && let Some(association) = &only.association
- {
- response["association"] = json!(association);
- }
- Ok(response)
+ let association = match sides.as_slice() {
+ [(_, only)] => only.association.clone(),
+ _ => None,
+ };
+ reply(cmd, OffsetResult { curves, constraints, sketch: info, sides: each, param, instances, param2, association, param_warnings: Vec::new() })
}
fn break_offset(s: &mut Session, p: &Value) -> Result<Value> {
@@ -3281,11 +3331,7 @@ fn break_offset(s: &mut Session, p: &Value) -> Result<Value> {
Ok((output.to_string(), None))
})?;
s.doc_mut().prune_model_params();
- let mut response = json!({"curve":out.0,"sketch":info});
- if let Some(curves) = out.1 {
- response["curves"] = json!(curves);
- }
- Ok(response)
+ reply(cmd, OffsetBreakResult { curve: out.0, sketch: info, curves: out.1, param_warnings: Vec::new() })
}
/// A broken logical boundary becomes ordinary geometry. Keep downstream features
@@ -3530,7 +3576,7 @@ fn mirror(s: &mut Session, p: &Value) -> Result<Value> {
}
Ok((ids_of(sk, &made), cons))
})?;
- Ok(json!({"curves": out.0, "constraints": out.1, "sketch": info}))
+ reply(cmd, MirrorResult { curves: out.0, constraints: out.1, sketch: info, param_warnings: Vec::new() })
}
fn point_or_ref(sk: &Sketch, p: &Value, k: &str, cmd: &str) -> Result<Vec2> {
@@ -3740,7 +3786,7 @@ fn move_copy(s: &mut Session, p: &Value) -> Result<Value> {
Ok(ids_of(sk, &cs))
})?;
s.doc_mut().prune_model_params();
- Ok(json!({"curves": out, "sketch": info}))
+ reply(cmd, MoveResult { curves: out, sketch: info, param_warnings: Vec::new() })
}
/// Scale, turn and move the entities in one step: scaled about `center`, then turned about it,
@@ -3838,7 +3884,7 @@ fn scale(s: &mut Session, p: &Value) -> Result<Value> {
transform_in_place(sk, &cs, &ps, &f, k, cmd)?;
Ok(ids_of(sk, &cs))
})?;
- Ok(json!({"curves": out, "sketch": info}))
+ reply(cmd, ScaleResult { curves: out, sketch: info, param_warnings: Vec::new() })
}
#[cfg(test)]
diff --git a/crates/engine/src/cmd/sketch_pattern.rs b/crates/engine/src/cmd/sketch_pattern.rs
index d90c23a101..11bea6d23d 100644
--- a/crates/engine/src/cmd/sketch_pattern.rs
+++ b/crates/engine/src/cmd/sketch_pattern.rs
@@ -4,6 +4,7 @@ use solidcraft_sketch::{SketchPattern, SketchPatternKind};
use super::*;
use crate::cmd::{alignment_param, reversed_param};
+use crate::schema::sketch_modify::PatternResult;
pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result<Value> {
let cmd = if circular { "sketch.pattern.circular" } else { "sketch.pattern.rectangular" };
@@ -194,13 +195,10 @@ pub(super) fn run(s: &mut Session, p: &Value, circular: bool) -> Result<Value> {
let pattern = sk.patterns.get(index).ok_or_else(|| bad(cmd, "missing sketch pattern"))?;
let curves: Vec<_> = pattern.instances.iter().flat_map(|i| i.curves.iter().cloned()).collect();
let constraints: Vec<_> = pattern.instances.iter().flat_map(|i| i.constraints.iter().cloned()).collect();
- Ok(json!({"pattern":id,"center":center_id,"curves":curves,"constraints":constraints}))
+ Ok((id, center_id, curves, constraints))
})?;
- let mut out = out;
- if let Some(out) = out.as_object_mut() {
- out.insert("sketch".into(), info);
- }
- Ok(out)
+ let (pattern, center, curves, constraints) = out;
+ reply(cmd, PatternResult { pattern, center, curves, constraints, sketch: info, param_warnings: Vec::new() })
}
fn count(p: &Value, k: &str, cmd: &str) -> Result<usize> {
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 86dbd2985c..e7de65f40d 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -107,6 +107,7 @@ pub mod sketch_create;
pub mod sketch_ends;
pub mod sketch_equation;
pub mod sketch_inspect;
+pub mod sketch_modify;
pub mod surface_analysis;
pub mod surface_boundary;
pub mod surface_match;
diff --git a/crates/engine/src/schema/sketch_modify.rs b/crates/engine/src/schema/sketch_modify.rs
new file mode 100644
index 0000000000..b2b2911508
--- /dev/null
+++ b/crates/engine/src/schema/sketch_modify.rs
@@ -0,0 +1,1520 @@
+//! Contracts and result types for the commands in `cmd/sketch_modify.rs`: `sketch.trim`,
+//! `sketch.trim.path`, `sketch.break`, `sketch.extend`, `sketch.fillet`, the three
+//! `sketch.chamfer.*`, `sketch.offset`, `sketch.offset.break`, `sketch.mirror`, `sketch.move`,
+//! `sketch.scale` and the two `sketch.pattern.*` (#12551).
+//!
+//! The handlers read their parameters from the raw JSON, so each type here reads its keys by
+//! calling the helpers the handlers call (`params::req_vec2`, `params::vec2_list`,
+//! `params::string_list`, `alignment_param`…) on the same JSON, and a value they refuse fails
+//! with the handler's own message. Whether a curve, a point or a sketch exists stays the
+//! handler's to check, and so does whatever needs the design (an expression that has to
+//! evaluate, a pattern being edited).
+//!
+//! 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.
+//!
+//! Several commands read different keys in different cases, and each type reads only the keys
+//! its handler reads in the case the call is in, so a call that works today gets no warning:
+//!
+//! - `sketch.break` takes `points` when the key is there (even `null`, which the handler
+//! refuses) and otherwise `at`;
+//! - `sketch.extend` is the two-curve form when `curves` is there, reading `curves` and `at` as
+//! a pair and refusing `curve`, and otherwise reads `curve` and `at` as one point;
+//! - `sketch.fillet` and the chamfers take every corner of `points` when it is a list, each as a
+//! point reference or `{a, b}`, and otherwise read `point`, or `a` and `b` when `point` is not
+//! text. A `point` that is not text, a `points` that is not a list, a `pattern` that is not
+//! text and an offset's `direction` that is not text switch the handler into its other form
+//! instead of being refused, so the types leave them alone too;
+//! - `sketch.offset` reads `symmetric` unless `direction` is `symmetric`;
+//! - the pattern commands may leave out what the pattern they edit (`pattern`) already has.
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Value, json};
+use solidcore_record::Vec2;
+use solidcraft_doc::Expr;
+use solidcraft_geom::prelude::*;
+use solidcraft_sketch::PatternAlignment;
+
+use super::check::whole;
+use super::motion::require;
+use super::sketch_ends::SketchTarget;
+use super::types::{LengthExpr, Point2, StringList};
+use crate::params::{self, expr, num, str_};
+
+/// The most copies a pattern makes, as `sketch.pattern.*` and the handlers' limits have it.
+pub(crate) const MAX_COPIES: usize = 500;
+/// The most offsets `sketch.offset` stacks one behind the other in a single run. Each instance
+/// is its own association, so this stays below the sketch's own caps on analytic offset groups
+/// and free-form associations (both 128).
+pub(crate) const MAX_INSTANCES: usize = 100;
+/// The most positions in a trim path.
+pub(crate) const MAX_PATH_POINTS: usize = 2_000;
+/// The most positions `sketch.break` takes.
+pub(crate) const MAX_BREAK_POINTS: usize = 1_000;
+/// The most corners one fillet or chamfer takes.
+const MAX_CORNERS: usize = 500;
+/// The most curves one offset takes.
+const MAX_OFFSET_CURVES: usize = 500;
+
+type Read<T> = Result<T, String>;
+
+/// The message of a handler's refusal.
+fn message(e: crate::EngineError) -> String {
+ match e {
+ crate::EngineError::BadParams { msg, .. } => msg,
+ other => other.to_string(),
+ }
+}
+
+/// Parameters read in one go from the raw JSON, as the handler reads them: a refusal is the
+/// handler's message, kept whole.
+macro_rules! read_params {
+ ($($ty:ty),+ $(,)?) => {$(
+ impl<'de> Deserialize<'de> for $ty {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Self::read(&Value::deserialize(d)?).map_err(|m| D::Error::custom(whole(m)))
+ }
+ }
+ )+};
+}
+
+/// `key` as text, or `msg`; `None` when it is left out.
+fn text(p: &Value, key: &str, msg: &str) -> Read<Option<String>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(Value::String(s)) => Ok(Some(s.clone())),
+ Some(_) => Err(msg.to_string()),
+ }
+}
+
+/// `key` as a point `[x, y]`, or `msg`; `None` when it is left out.
+fn point(p: &Value, key: &str, msg: &str) -> Read<Option<Vec2>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(v) => params::vec2(v).map(Some).ok_or_else(|| msg.to_string()),
+ }
+}
+
+/// A 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(p: &Value, key: &str) -> Read<Option<bool>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::Bool(b)) => Ok(Some(*b)),
+ Some(_) => Err(format!("`{key}` must be true or false")),
+ }
+}
+
+/// A number the handler reads with `num`, or `msg`; `None` when it is left out.
+fn number(p: &Value, key: &str, msg: &str) -> Read<Option<f64>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(_) => num(p, key).map(Some).ok_or_else(|| msg.to_string()),
+ }
+}
+
+/// A list of names as `params::string_list` reads it (`null` is an empty list, which the
+/// handler refuses with its own message); `None` when the key is left out.
+fn names(p: &Value, key: &str) -> Read<Option<Vec<String>>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(_) => params::string_list("", p, key).map(Some).map_err(message),
+ }
+}
+
+/// The sketch the call is for, as `sketch_store::target` reads it: an id or a name, and `null`
+/// is the one being edited.
+fn sketch_of(p: &Value) -> Read<Option<SketchTarget>> {
+ match p.get("sketch") {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::Number(n)) if n.is_u64() => Ok(Some(SketchTarget(n.to_string()))),
+ Some(Value::String(s)) => Ok(Some(SketchTarget(s.clone()))),
+ Some(_) => Err("`sketch` must be an id or a name".to_string()),
+ }
+}
+
+/// A point `[x, y]` or the id of one, as `point_or_ref` reads `key`; `None` when it is left out.
+fn point_or_id(p: &Value, key: &str) -> Read<Option<PointOrId>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(Value::String(id)) => Ok(Some(PointOrId::Id(id.clone()))),
+ Some(v) => params::vec2(v).map(PointOrId::At).map(Some).ok_or_else(|| format!("`{key}` must be [x, y] or a point id")),
+ }
+}
+
+/// A point of the sketch: `[x, y]` (or `{x, y}`) in mm, or the id of an existing point.
+#[derive(Clone, Debug, PartialEq)]
+pub enum PointOrId {
+ /// By its coordinates.
+ At(Vec2),
+ /// By its id (`p3`, `l1.end`). Whether the sketch has it is the handler's to check.
+ Id(String),
+}
+
+impl JsonSchema for PointOrId {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchPointOrId".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let at = generator.subschema_for::<Point2>();
+ json_schema!({
+ "description": "A point of the sketch: [x, y] or {\"x\", \"y\"} in mm, or the id of an existing point.",
+ "anyOf": [at, {"type": "string"}]
+ })
+ }
+}
+
+/// An optional key's schema when `null` is not read as absent and a plain value is.
+fn number_or_expression(description: &str) -> Schema {
+ json_schema!({
+ "description": description,
+ "anyOf": [
+ {"type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9},
+ {"type": "string"}
+ ]
+ })
+}
+
+fn coordinate_number(description: &str) -> Schema {
+ json_schema!({"description": description, "type": "number", "exclusiveMinimum": -1e9, "exclusiveMaximum": 1e9})
+}
+
+fn require_all(schema: &mut Schema, keys: &[&str]) {
+ for key in keys {
+ require(schema, key);
+ }
+}
+
+/// A schema's `anyOf` of the key sets a call may be built from (the first form that fits).
+fn one_of_these(schema: &mut Schema, forms: &[&[&str]]) {
+ let forms: Vec<Value> = forms.iter().map(|keys| json!({"required": keys})).collect();
+ schema.insert("anyOf".into(), Value::Array(forms));
+}
+
+// ---------------------------------------------------------------------------------------------
+// Corners
+
+/// One corner of a fillet or chamfer: a point where two curves meet, or the two curves.
+#[derive(Clone, Debug, PartialEq)]
+pub enum Corner {
+ /// The corner point's reference (`l1.end`).
+ Point(String),
+ /// The two curves that meet at the corner, by id.
+ Lines { a: String, b: String },
+}
+
+impl Corner {
+ /// The corner `p` names, as `corner` reads it: `point` when it is text, else `a` and `b`.
+ fn read(p: &Value) -> Read<Corner> {
+ if let Some(point) = str_(p, "point") {
+ return Ok(Corner::Point(point.to_string()));
+ }
+ let line = |key: &str| str_(p, key).map(str::to_string).ok_or_else(|| format!("`{key}` must be a line"));
+ Ok(Corner::Lines { a: line("a")?, b: line("b")? })
+ }
+
+ /// An entry of `points`, as `corner_arg` turns it into the parameters of one corner: an
+ /// object with `a`, `b` or `point` as it is, anything else as a `point`.
+ fn read_entry(entry: &Value) -> Read<Corner> {
+ match entry {
+ Value::Object(o) if o.contains_key("a") || o.contains_key("b") || o.contains_key("point") => Corner::read(entry),
+ _ => Corner::read(&json!({ "point": entry })),
+ }
+ }
+}
+
+impl JsonSchema for Corner {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchCorner".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A corner: its point's reference (\"l1.end\"), or {\"point\"}, or {\"a\", \"b\"}, the two curves that meet there.",
+ "anyOf": [
+ {"type": "string"},
+ {"type": "object", "properties": {"point": {"type": "string"}}, "required": ["point"]},
+ {"type": "object", "properties": {"a": {"type": "string"}, "b": {"type": "string"}}, "required": ["a", "b"]}
+ ]
+ })
+ }
+}
+
+/// The corners a fillet or chamfer works on: `points`, a list of corners, or the one corner
+/// `point` or `a` and `b` name. Fillet and the chamfers flatten this into their parameters.
+#[derive(Debug, JsonSchema)]
+pub struct CornerSelection {
+ /// A corner's point reference (`l1.end`): the point two curves share. Used when `points` is
+ /// not a list; it takes the place of `a` and `b` when it is text.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub point: Option<String>,
+ /// One of the two curves that meet at the corner (used when `point` is not text). Two lines
+ /// that share no end are first brought to where they meet.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub a: Option<String>,
+ /// The other curve of the corner (see `a`).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub b: Option<String>,
+ /// Several corners in one go, 1 to 500, all cut alike: each a point reference or `{a, b}`
+ /// (an object with `point`, `a` or `b`). When it is a list, `point`, `a` and `b` are not
+ /// used.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub points: Option<Vec<Corner>>,
+}
+
+impl CornerSelection {
+ fn read(p: &Value) -> Read<CornerSelection> {
+ let mut selection = CornerSelection { point: None, a: None, b: None, points: None };
+ match p.get("points").and_then(Value::as_array) {
+ Some(list) if !list.is_empty() && list.len() <= MAX_CORNERS => {
+ selection.points = Some(list.iter().map(Corner::read_entry).collect::<Read<Vec<_>>>()?);
+ }
+ Some(_) => return Err(format!("`points` must list 1…{MAX_CORNERS} corners")),
+ None => match Corner::read(p)? {
+ Corner::Point(point) => selection.point = Some(point),
+ Corner::Lines { a, b } => (selection.a, selection.b) = (Some(a), Some(b)),
+ },
+ }
+ Ok(selection)
+ }
+}
+
+/// The forms a corner is given in, for the schemas that flatten [`CornerSelection`].
+fn corner_forms(schema: &mut Schema) {
+ one_of_these(schema, &[&["point"], &["a", "b"], &["points"]]);
+}
+
+// ---------------------------------------------------------------------------------------------
+// Trim, break, extend
+
+/// Remove the piece of a curve between the nearest crossings around a point (a curve nothing
+/// crosses goes whole). The cut ends are joined to the curve that cut them. Trimming a line that
+/// has single-line offsets, or one that is such an offset, releases their linked extents into
+/// the dimensions that held them. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = trim_required)]
+pub struct TrimParams {
+ /// The curve to trim, by id.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub curve: Option<String>,
+ /// A point on the piece to remove, in mm.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point2")]
+ pub at: Option<Vec2>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn trim_required(schema: &mut Schema) {
+ require_all(schema, &["curve", "at"]);
+}
+
+impl TrimParams {
+ fn read(p: &Value) -> Read<Self> {
+ let at = point(p, "at", "`at` must be a point [x, y]")?;
+ let sketch = sketch_of(p)?;
+ let curve = text(p, "curve", "`curve` must be a curve id")?;
+ Ok(TrimParams { curve, at, sketch })
+ }
+}
+
+/// Trim every piece a path drawn across the sketch crosses, as `sketch.trim` removes the piece
+/// at each crossing, in the order the path crosses them. A piece crossed again after it is gone
+/// is not trimmed twice. Projected geometry, infinite lines, offset outputs other than a single
+/// line's, and pieces `sketch.trim` refuses are passed over (the reply's `skipped` says why).
+/// One undo step; with `dry_run`, nothing changes.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = trim_path_required)]
+pub struct TrimPathParams {
+ /// The path: 2 to 2000 positions in mm.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Vec<Point2>", length(min = 2, max = 2000))]
+ pub points: Option<Vec<Vec2>>,
+ /// Report what would be trimmed without changing the design. Default: false.
+ #[serde(default)]
+ pub dry_run: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn trim_path_required(schema: &mut Schema) {
+ require(schema, "points");
+}
+
+impl TrimPathParams {
+ fn read(p: &Value) -> Read<Self> {
+ let points = match p.get("points") {
+ None => None,
+ Some(_) => {
+ let points = params::vec2_list("", p, "points", MAX_PATH_POINTS).map_err(message)?;
+ if points.len() < 2 {
+ return Err("`points` needs at least two positions".to_string());
+ }
+ Some(points)
+ }
+ };
+ let dry_run = flag(p, "dry_run")?;
+ let sketch = sketch_of(p)?;
+ Ok(TrimPathParams { points, dry_run, sketch })
+ }
+}
+
+/// Split a curve in two or more, at the places other curves cross it (`at`) or at given
+/// positions (`points`). At a point where the curve ends and another curve meets, the curve
+/// gets its own end there and the two are no longer joined. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = break_required)]
+pub struct BreakParams {
+ /// The curve to break, by id.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub curve: Option<String>,
+ /// A point near the place to break, in mm: the curve is split at the crossings either side
+ /// of it. Used when `points` is not given.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point2")]
+ pub at: Option<Vec2>,
+ /// Positions to break at, 1 to 1000, in mm, projected onto the curve; duplicates are
+ /// merged. When this key is there, `at` is not used.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Vec<Point2>", length(max = 1000))]
+ pub points: Option<Vec<Vec2>>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn break_required(schema: &mut Schema) {
+ require(schema, "curve");
+ one_of_these(schema, &[&["at"], &["points"]]);
+}
+
+impl BreakParams {
+ fn read(p: &Value) -> Read<Self> {
+ let points = match p.get("points") {
+ Some(_) => Some(params::vec2_list("", p, "points", MAX_BREAK_POINTS).map_err(message)?),
+ None => None,
+ };
+ let sketch = sketch_of(p)?;
+ let curve = text(p, "curve", "`curve` must be a curve id")?;
+ let at = if points.is_some() { None } else { point(p, "at", "`at` must be a point [x, y]")? };
+ Ok(BreakParams { curve, at, points, sketch })
+ }
+}
+
+/// Where `sketch.extend` takes its ends from: one point, or one per curve.
+#[derive(Clone, Debug, PartialEq)]
+pub enum ExtendAt {
+ /// One curve: a point near the end to extend.
+ End(Vec2),
+ /// Two curves: one point per curve, naming the end of it to grow.
+ Ends([Vec2; 2]),
+}
+
+impl JsonSchema for ExtendAt {
+ fn schema_name() -> Cow<'static, str> {
+ "ExtendAt".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ let at = generator.subschema_for::<Point2>();
+ json_schema!({
+ "description": "With `curve`: a point near the end to extend, [x, y] in mm. With `curves`: one point per curve, [[x, y], [x, y]].",
+ "anyOf": [at, {"type": "array", "items": at, "minItems": 2, "maxItems": 2}]
+ })
+ }
+}
+
+/// Extend a line or arc to the nearest curve in its way (`curve` and `at`), or grow two lines or
+/// arcs until they meet and join them there (`curves`). A line with nothing in its way runs on
+/// to the reach the preview shows; an arc grows along its circle and closes into a whole circle
+/// when nothing stops it. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = extend_required)]
+pub struct ExtendParams {
+ /// The curve to extend, by id. Not with `curves`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "String")]
+ pub curve: Option<String>,
+ /// Two lines or arcs of the sketch to grow until they meet, 2 ids, joined where they meet.
+ /// Not with `curve`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Vec<String>", length(min = 2, max = 2))]
+ pub curves: Option<Vec<String>>,
+ /// With `curve`: a point near the end to extend. With `curves`: one point per curve, the
+ /// end to grow (default: the end of each nearest the meeting point).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ExtendAt")]
+ pub at: Option<ExtendAt>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn extend_required(schema: &mut Schema) {
+ one_of_these(schema, &[&["curve", "at"], &["curves"]]);
+ schema.insert("not".into(), json!({"required": ["curve", "curves"]}));
+}
+
+impl ExtendParams {
+ fn read(p: &Value) -> Read<Self> {
+ if let Some(list) = p.get("curves") {
+ if p.get("curve").is_some() {
+ return Err("give `curve` with `at` (one curve) or `curves` (two curves), not both".to_string());
+ }
+ let ids =
+ list.as_array().filter(|a| a.len() == 2).and_then(|a| a.iter().map(|v| v.as_str().map(str::to_string)).collect::<Option<Vec<_>>>());
+ let Some(ids) = ids else {
+ return Err("`curves` must be a list of exactly two curve ids".to_string());
+ };
+ let at = match p.get("at") {
+ None => None,
+ Some(v) => {
+ let ends = v.as_array().filter(|a| a.len() == 2).and_then(|a| a.iter().map(params::vec2).collect::<Option<Vec<Vec2>>>());
+ match ends.map(<[Vec2; 2]>::try_from) {
+ Some(Ok(two)) => Some(ExtendAt::Ends(two)),
+ _ => return Err("with `curves`, `at` is one point per curve: [[x,y],[x,y]]".to_string()),
+ }
+ }
+ };
+ let sketch = sketch_of(p)?;
+ return Ok(ExtendParams { curve: None, curves: Some(ids), at, sketch });
+ }
+ let at = point(p, "at", "`at` must be a point [x, y]")?.map(ExtendAt::End);
+ let sketch = sketch_of(p)?;
+ let curve = text(p, "curve", "`curve` must be a curve id")?;
+ Ok(ExtendParams { curve, curves: None, at, sketch })
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Fillet and chamfers
+
+/// Round one or several corners of a sketch with an arc of one radius, tangent to both curves.
+/// The corner is two lines, or a line and an arc, or two arcs, that meet at a point. Two lines
+/// that share no end are first brought to where they meet (the nearer end of a line that stops
+/// short moves there, and a line that runs past is cut there, losing its shorter piece). With
+/// several corners the first arc carries the radius dimension and the rest are equal to it. A
+/// corner that dimensions or constraints measure to stays as a virtual sharp corner on both
+/// curves' extensions. An ellipse's axis line is never a side of a corner. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = fillet_required)]
+pub struct FilletParams {
+ /// The radius: a number in mm or a length expression, above 0.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "LengthExpr")]
+ pub radius: Option<Expr>,
+ #[serde(flatten)]
+ pub corners: CornerSelection,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn fillet_required(schema: &mut Schema) {
+ require(schema, "radius");
+ corner_forms(schema);
+}
+
+impl FilletParams {
+ fn read(p: &Value) -> Read<Self> {
+ let radius = match p.get("radius") {
+ None => None,
+ Some(_) => Some(expr(p, "radius").ok_or_else(|| format!("`radius` {}", params::expr_problem(p.get("radius"))))?),
+ };
+ let corners = CornerSelection::read(p)?;
+ let sketch = sketch_of(p)?;
+ Ok(FilletParams { radius, corners, sketch })
+ }
+}
+
+/// Cut one or several corners of two lines with a straight line, the same distance back along
+/// both lines. Two lines that share no end are first brought to where they meet, as in
+/// `sketch.fillet`. Every corner is cut alike, in one undo step, and a corner that cannot be
+/// cut refuses them all. A corner that dimensions or constraints measure to stays as a virtual
+/// sharp corner.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = chamfer_equal_required)]
+pub struct ChamferEqualParams {
+ /// How far back from the corner along each line, in mm (a number; an expression is not
+ /// read).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "distance_schema")]
+ pub distance: Option<f64>,
+ #[serde(flatten)]
+ pub corners: CornerSelection,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn distance_schema(_: &mut SchemaGenerator) -> Schema {
+ coordinate_number("A distance in mm, a number.")
+}
+
+fn chamfer_equal_required(schema: &mut Schema) {
+ require(schema, "distance");
+ corner_forms(schema);
+}
+
+impl ChamferEqualParams {
+ fn read(p: &Value) -> Read<Self> {
+ let distance = number(p, "distance", "`distance` must be a number")?;
+ let corners = CornerSelection::read(p)?;
+ let sketch = sketch_of(p)?;
+ Ok(ChamferEqualParams { distance, corners, sketch })
+ }
+}
+
+/// Cut one or several corners of two lines with a straight line that is `distance` back along
+/// `a` and `distance2` back along `b`. A point's `a` is the first of its two lines in curve
+/// order. Two lines that share no end are first brought to where they meet, as in
+/// `sketch.fillet`. Every corner is cut alike, in one undo step, and a corner that cannot be
+/// cut refuses them all.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = chamfer_two_required)]
+pub struct ChamferTwoParams {
+ /// How far back from the corner along `a` (the first line), in mm (a number).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "distance_schema")]
+ pub distance: Option<f64>,
+ /// How far back from the corner along `b` (the second line), in mm (a number).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "distance_schema")]
+ pub distance2: Option<f64>,
+ #[serde(flatten)]
+ pub corners: CornerSelection,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn chamfer_two_required(schema: &mut Schema) {
+ require_all(schema, &["distance", "distance2"]);
+ corner_forms(schema);
+}
+
+impl ChamferTwoParams {
+ fn read(p: &Value) -> Read<Self> {
+ let distance = number(p, "distance", "`distance` must be a number")?;
+ let distance2 = number(p, "distance2", "`distance2` must be a number")?;
+ let corners = CornerSelection::read(p)?;
+ let sketch = sketch_of(p)?;
+ Ok(ChamferTwoParams { distance, distance2, corners, sketch })
+ }
+}
+
+/// Cut one or several corners of two lines with a straight line that is `distance` back along
+/// `a` and meets `b` at `angle` from `a`. A point's `a` is the first of its two lines in curve
+/// order. Two lines that share no end are first brought to where they meet, as in
+/// `sketch.fillet`. Every corner is cut alike, in one undo step, and a corner that cannot be
+/// cut refuses them all.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = chamfer_angle_required)]
+pub struct ChamferDistanceAngleParams {
+ /// How far back from the corner along `a`, in mm (a number).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "distance_schema")]
+ pub distance: Option<f64>,
+ /// The angle of the cut from `a`, in degrees (a number). It must leave room to meet the
+ /// other line.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "angle_schema")]
+ pub angle: Option<f64>,
+ #[serde(flatten)]
+ pub corners: CornerSelection,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn angle_schema(_: &mut SchemaGenerator) -> Schema {
+ coordinate_number("An angle in degrees, a number.")
+}
+
+fn chamfer_angle_required(schema: &mut Schema) {
+ require_all(schema, &["distance", "angle"]);
+ corner_forms(schema);
+}
+
+impl ChamferDistanceAngleParams {
+ fn read(p: &Value) -> Read<Self> {
+ let distance = number(p, "distance", "`distance` must be a number")?;
+ let angle = number(p, "angle", "`angle` must be a number (degrees)")?;
+ let corners = CornerSelection::read(p)?;
+ let sketch = sketch_of(p)?;
+ Ok(ChamferDistanceAngleParams { distance, angle, corners, sketch })
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Offset
+
+/// Offset a chain of sketch curves by a distance, as new curves driven by one dimension (a
+/// parameter, `param`). The chain is the connected curves through the ones picked (`chain`).
+/// A corner is trimmed back to the crossing when the offset runs past it, and extended until the
+/// offset curves intersect when the corner falls short. Each side is its own offset association,
+/// listed in the reply's `sides`. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = offset_required)]
+pub struct OffsetParams {
+ /// The curves to offset, 1 to 500 ids (one id is taken as a list of one).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "StringList")]
+ pub curves: Option<Vec<String>>,
+ /// The distance: a number in mm or a length expression (it creates an editable dimension).
+ /// Positive is left of the chain, or toward `side`; negative is the other way.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "LengthExpr")]
+ pub distance: Option<Expr>,
+ /// A point on the side to offset toward, in mm. Not with `symmetric`.
+ #[serde(default)]
+ pub side: Option<Point2>,
+ /// Offset the whole connected chain, ends that only coincide included. Default: true.
+ #[serde(default)]
+ pub chain: Option<bool>,
+ /// Reverse the primary side. Default: false.
+ #[serde(default)]
+ pub flip: Option<bool>,
+ /// `one_side` (the default) or `symmetric` (the same distance each way; no `side`). Read
+ /// without regard to case. Text that is not one of these, and `negative`, `reverse` and
+ /// `flip`, which mean nothing here, are refused; a value that is not text is ignored.
+ #[serde(default)]
+ #[schemars(schema_with = "direction_schema")]
+ pub direction: Option<Value>,
+ /// The same distance each way, as `direction: symmetric` does; read unless `direction` is
+ /// `symmetric`. Default: false.
+ #[serde(default)]
+ pub symmetric: Option<bool>,
+ /// An independent distance the other way, as for `solid.extrude`: a number in mm or a
+ /// positive length expression. Not with `symmetric`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "LengthExpr")]
+ pub distance2: Option<Expr>,
+ /// How many offsets stand one behind the other, 1 to 100 (a whole number or a unitless
+ /// expression). Each instance after the first offsets the one before it by the same
+ /// distance again. Default: 1.
+ #[serde(default)]
+ #[schemars(schema_with = "instances_schema")]
+ pub instances: Option<Value>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn direction_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "one_side or symmetric, in any case.", "type": ["string", "null"]})
+}
+
+fn instances_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A whole number from 1 to 100, or a unitless expression for one.",
+ "anyOf": [
+ {"type": "number", "minimum": 1, "maximum": MAX_INSTANCES},
+ {"type": "string"},
+ {"type": "null"}
+ ]
+ })
+}
+
+fn offset_required(schema: &mut Schema) {
+ require_all(schema, &["curves", "distance"]);
+}
+
+/// `key` as a length, as `offset_length` reads it: a number or a length expression.
+fn length(p: &Value, key: &str) -> Read<Option<Expr>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(_) => expr(p, key).map(Some).ok_or_else(|| format!("`{key}` must be a length expression")),
+ }
+}
+
+impl OffsetParams {
+ fn read(p: &Value) -> Read<Self> {
+ let curves = names(p, "curves")?;
+ if curves.as_ref().is_some_and(|c| c.is_empty() || c.len() > MAX_OFFSET_CURVES) {
+ return Err(format!("`curves` must list 1…{MAX_OFFSET_CURVES} curves"));
+ }
+ let distance = length(p, "distance")?;
+ let flip = flag(p, "flip")?;
+ // The handler reads a `side` that is not a point as left out, so this does too.
+ let side = p.get("side").and_then(params::vec2).map(Point2);
+ let chain = flag(p, "chain")?;
+ let direction = p.get("direction").filter(|v| !v.is_null()).cloned();
+ let symmetric = match str_(p, "direction").map(str::to_ascii_lowercase).as_deref() {
+ None | Some("positive") | Some("one_side") => flag(p, "symmetric")?,
+ Some("symmetric") => None,
+ Some("negative" | "reverse" | "flip") => {
+ return Err("an offset has no negative direction: give a negative `distance`, or a `side` to offset toward".to_string());
+ }
+ Some(other) => return Err(format!("unknown direction `{other}` (one_side, symmetric)")),
+ };
+ let distance2 = length(p, "distance2")?;
+ let instances = Self::instances(p)?;
+ let sketch = sketch_of(p)?;
+ Ok(OffsetParams { curves, distance, side, chain, flip, direction, symmetric, distance2, instances, sketch })
+ }
+
+ /// `instances`, as `offset_instances` reads it before it looks at the design: a number is a
+ /// whole number from 1 to 100, and text is an expression the handler evaluates.
+ fn instances(p: &Value) -> Read<Option<Value>> {
+ let message = format!("`instances` must be a whole number from 1 to {MAX_INSTANCES}, or an expression for one");
+ match p.get("instances") {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::Number(_)) => {
+ let count = num(p, "instances").ok_or_else(|| message.clone())?;
+ if count.fract() != 0.0 || !(1.0..=MAX_INSTANCES as f64).contains(&count) {
+ return Err(message);
+ }
+ Ok(p.get("instances").cloned())
+ }
+ Some(v) => expr(p, "instances").map(|_| Some(v.clone())).ok_or(message),
+ }
+ }
+}
+
+/// Break the association of an offset: its curves stay as ordinary geometry, with their points
+/// free to edit, and the dimension that drove them goes. Downstream features that used the
+/// offset's boundary keep that exact boundary. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = offset_break_required)]
+pub struct OffsetBreakParams {
+ /// A curve the offset made, by id.
+ #[serde(default, 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>,
+}
+
+fn offset_break_required(schema: &mut Schema) {
+ require(schema, "curve");
+}
+
+impl OffsetBreakParams {
+ fn read(p: &Value) -> Read<Self> {
+ let sketch = sketch_of(p)?;
+ let curve = text(p, "curve", "`curve` must name an offset output")?;
+ Ok(OffsetBreakParams { curve, sketch })
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Mirror, move, scale
+
+/// The mirror line of `sketch.mirror`: a curve id, `x` or `y`, or an object naming an origin
+/// axis.
+#[derive(Clone, Debug, PartialEq)]
+pub enum MirrorLine {
+ /// A straight curve's id, or `x` / `y` for a sketch axis (a curve with that id wins).
+ Curve(String),
+ /// A reference as `sketch.project` takes one; only `{axis: X|Y|Z}`, an origin axis, works.
+ Reference(Value),
+}
+
+impl JsonSchema for MirrorLine {
+ fn schema_name() -> Cow<'static, str> {
+ "MirrorLine".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A straight curve's id, or x / y for a sketch axis, or {\"axis\": \"X\" | \"Y\" | \"Z\"} for an origin axis (its projection into the sketch plane; an axis perpendicular to the plane is refused).",
+ "anyOf": [{"type": "string"}, {"type": "object", "properties": {"axis": {"type": "string"}}}]
+ })
+ }
+}
+
+/// Mirror sketch curves and points across a line, as new copies, and add symmetry constraints
+/// between each point and its copy (a point on the line stays one point, held on it). Circles
+/// copied are made equal to their originals. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = mirror_required)]
+pub struct MirrorParams {
+ /// The curves and points to mirror, by id (one id is taken as a list of one).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "StringList")]
+ pub entities: Option<Vec<String>>,
+ /// The mirror line.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "MirrorLine")]
+ pub line: Option<MirrorLine>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn mirror_required(schema: &mut Schema) {
+ require_all(schema, &["entities", "line"]);
+}
+
+impl MirrorParams {
+ fn read(p: &Value) -> Read<Self> {
+ let line = match p.get("line") {
+ None => None,
+ Some(Value::String(id)) => Some(MirrorLine::Curve(id.clone())),
+ Some(v @ Value::Object(_)) => Some(MirrorLine::Reference(v.clone())),
+ Some(_) => return Err("`line` must be a curve id, or x / y for a sketch axis".to_string()),
+ };
+ let sketch = sketch_of(p)?;
+ let entities = names(p, "entities")?;
+ Ok(MirrorParams { entities, line, sketch })
+ }
+}
+
+/// Move, turn or copy sketch curves and points: turned by `angle` about `center`, then moved by
+/// `translate`. A rotation turns the constraints tied to the sketch axes when all their geometry
+/// moves (horizontal and vertical relations and dimensions swap at odd quarter turns and stay
+/// at half turns, line angles turn with the line) and removes the horizontal and vertical ones
+/// that cannot hold at other angles. Picking a text outline or linked point moves its whole text
+/// source once, and copies of text stay editable. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = move_required)]
+pub struct MoveParams {
+ /// The curves and points to move or copy, by id (one id is taken as a list of one). With
+ /// `copy`, also drawn 3D curves, which keep their exact arcs and height above the plane.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "StringList")]
+ pub entities: Option<Vec<String>>,
+ /// The move, `[dx, dy]` in mm. Default: none.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point2")]
+ pub translate: Option<Vec2>,
+ /// The turn, in degrees (a number). Default: 0.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "angle_schema")]
+ pub angle: Option<f64>,
+ /// What the turn is about: a point [x, y] in mm or a point's id. Default: the sketch origin.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointOrId")]
+ pub center: Option<PointOrId>,
+ /// Make copies and leave the originals where they are. Default: false.
+ #[serde(default)]
+ pub copy: Option<bool>,
+ /// Turn the constraints tied to the sketch axes with the geometry; false keeps constraints
+ /// unchanged. Default: true. Not used with `copy`.
+ #[serde(default)]
+ pub rotate_constraints: Option<bool>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn move_required(schema: &mut Schema) {
+ require(schema, "entities");
+}
+
+impl MoveParams {
+ fn read(p: &Value) -> Read<Self> {
+ let translate = point(p, "translate", "`translate` must be a point [x, y]")?;
+ let angle = number(p, "angle", "`angle` must be finite")?;
+ let copy = flag(p, "copy")?;
+ let rotate_constraints = flag(p, "rotate_constraints")?;
+ let entities = names(p, "entities")?;
+ let sketch = sketch_of(p)?;
+ let center = point_or_id(p, "center")?;
+ Ok(MoveParams { entities, translate, angle, center, copy, rotate_constraints, sketch })
+ }
+}
+
+/// Scale sketch curves and points about a base point. Circles and arcs scale their radii; a
+/// fixed or projected point cannot move. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = scale_required)]
+pub struct ScaleParams {
+ /// The curves and points to scale, by id (one id is taken as a list of one).
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "StringList")]
+ pub entities: Option<Vec<String>>,
+ /// What stays put: a point [x, y] in mm or a point's id. Default: the sketch origin.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointOrId")]
+ pub base: Option<PointOrId>,
+ /// The factor, a number above 1e-9 and below 1e6.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "factor_schema")]
+ pub factor: Option<f64>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn factor_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A scale factor, a number.", "type": "number", "exclusiveMinimum": 1e-9, "exclusiveMaximum": 1e6})
+}
+
+fn scale_required(schema: &mut Schema) {
+ require_all(schema, &["entities", "factor"]);
+}
+
+impl ScaleParams {
+ fn read(p: &Value) -> Read<Self> {
+ let factor = match p.get("factor") {
+ None => None,
+ Some(_) => Some(num(p, "factor").filter(|k| *k > 1e-9 && *k < 1e6).ok_or_else(|| "`factor` must be a positive number".to_string())?),
+ };
+ let sketch = sketch_of(p)?;
+ let entities = names(p, "entities")?;
+ let base = point_or_id(p, "base")?;
+ Ok(ScaleParams { entities, base, factor, sketch })
+ }
+}
+
+// ---------------------------------------------------------------------------------------------
+// Patterns
+
+/// A pattern quantity as the handler reads it before the design is looked at: a number, or text
+/// that is an expression for one (evaluated by the handler).
+fn quantity(p: &Value, key: &str, not_a_number: &str) -> Read<Option<Value>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(Value::String(_)) => Ok(p.get(key).cloned()),
+ Some(_) => num(p, key).map(|_| p.get(key).cloned()).ok_or_else(|| not_a_number.to_string()),
+ }
+}
+
+/// A pattern's count (`count` or `count2`), as `count` reads it, but for the design.
+fn pattern_count(p: &Value, key: &str) -> Read<Option<Value>> {
+ let value = quantity(p, key, &format!("`{key}` must be a number or expression"))?;
+ if let Some(Value::Number(n)) = &value {
+ let n = n.as_f64().unwrap_or(f64::NAN);
+ if !(1.0..=MAX_COPIES as f64).contains(&n) || n.fract() != 0.0 {
+ return Err(format!("`{key}` must be a positive integer from 1 to {MAX_COPIES}"));
+ }
+ }
+ Ok(value)
+}
+
+fn alignment(p: &Value, key: &str) -> Read<Option<PatternAlignment>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(_) => crate::cmd::alignment_param(p, key, "").map(Some).map_err(message),
+ }
+}
+
+fn reversal(p: &Value, key: &str) -> Read<Option<bool>> {
+ match p.get(key) {
+ None => Ok(None),
+ Some(_) => crate::cmd::reversed_param(p, key, "").map(Some).map_err(message),
+ }
+}
+
+/// `dir` or `dir2`, as the handler reads them: a finite, nonzero vector.
+fn direction_vector(p: &Value, key: &str) -> Read<Option<Vec2>> {
+ match p.get(key) {
+ None => Ok(None),
+ // `dir2: null` is left out; `dir: null` is refused, as the handler does.
+ Some(Value::Null) if key == "dir2" => Ok(None),
+ Some(v) => params::vec2(v).and_then(Vec2::normalized).map(Some).ok_or_else(|| format!("`{key}` must be a finite nonzero vector")),
+ }
+}
+
+/// `direction` or `direction2`: the id of a sketch line, or left out (`null` too).
+fn direction_line(p: &Value, key: &str) -> Read<Option<String>> {
+ match p.get(key) {
+ None | Some(Value::Null) => Ok(None),
+ Some(Value::String(id)) => Ok(Some(id.clone())),
+ Some(_) => Err(format!("`{key}` must reference a nondegenerate sketch line")),
+ }
+}
+
+/// The pattern being edited, as `str_` reads `pattern`: text. Anything else makes a new one.
+fn pattern_id(p: &Value) -> Option<String> {
+ str_(p, "pattern").map(str::to_string)
+}
+
+fn alignment_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string", "enum": ["left", "center", "right"]})
+}
+
+fn pattern_forms(circular: bool) -> &'static [&'static [&'static str]] {
+ if circular { &[&["pattern"], &["entities", "center", "count"]] } else { &[&["pattern"], &["entities", "count", "spacing"]] }
+}
+
+/// Make copies of sketch curves and points evenly round a centre, as an associative pattern: the
+/// copies follow the originals, and the pattern keeps its own constraints. The quantity includes
+/// the original. With `pattern`, edit the pattern that id names instead of making a new one:
+/// keys left out keep their values, surviving instance ids are kept, and the pattern's type and
+/// seed entities cannot change. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = circular_required)]
+pub struct CircularPatternParams {
+ /// The curves and points to copy, by id (one id is taken as a list of one). Left out only
+ /// with `pattern`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "StringList")]
+ pub entities: Option<Vec<String>>,
+ /// The centre: a point [x, y] in mm (it makes a point you can constrain) or an existing
+ /// point's id. Left out only with `pattern`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PointOrId")]
+ pub center: Option<PointOrId>,
+ /// How many, the original included: a whole number from 2 to 500 or a unitless expression
+ /// (kept as an expression). Left out only with `pattern`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "count_schema")]
+ pub count: Option<Value>,
+ /// The total angle, in degrees: a number or an expression, nonzero and at most 360 in size.
+ /// A full turn spaces the copies angle/count apart; a partial one angle/(count-1). Default:
+ /// 360.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "pattern_angle_schema")]
+ pub angle: Option<Value>,
+ /// Where the original stands among the copies: `left`, `center` or `right`. Center
+ /// balances the copies round it. Default: right.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "alignment_schema")]
+ pub alignment: Option<PatternAlignment>,
+ /// Flip the direction, and the extra side for an even total with `center`. Default: false.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub reversed: Option<bool>,
+ /// The id of an existing circular pattern to edit instead of making a new one.
+ #[serde(default)]
+ pub pattern: Option<String>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn count_schema(_: &mut SchemaGenerator) -> Schema {
+ number_or_expression("A whole number from 1 to 500 (a circular pattern needs at least 2 to make a copy), or an expression for one.")
+}
+
+fn pattern_angle_schema(_: &mut SchemaGenerator) -> Schema {
+ number_or_expression("An angle in degrees, or an expression for one.")
+}
+
+fn circular_required(schema: &mut Schema) {
+ one_of_these(schema, pattern_forms(true));
+}
+
+impl CircularPatternParams {
+ fn read(p: &Value) -> Read<Self> {
+ let entities = names(p, "entities")?;
+ let count = pattern_count(p, "count")?;
+ let angle = match quantity(p, "angle", "`angle` must be finite")? {
+ Some(Value::Number(n)) => {
+ let total = n.as_f64().unwrap_or(f64::NAN);
+ if !(total.abs() > 1e-9 && total.abs() <= 360.0) {
+ return Err("`angle` must be nonzero and at most 360 degrees".to_string());
+ }
+ Some(Value::Number(n))
+ }
+ other => other,
+ };
+ let center = point_or_id(p, "center").map_err(|_| "`center` must be [x,y] or a point ref".to_string())?;
+ let alignment = alignment(p, "alignment")?;
+ let reversed = reversal(p, "reversed")?;
+ let pattern = pattern_id(p);
+ let sketch = sketch_of(p)?;
+ Ok(CircularPatternParams { entities, center, count, angle, alignment, reversed, pattern, sketch })
+ }
+}
+
+/// Make copies of sketch curves and points in a grid, as an associative pattern: one row along
+/// `direction` (or `dir`) and, with `count2`, more rows along `direction2` (or `dir2`). The
+/// copies follow the originals, and the pattern keeps its own constraints. Quantities include the
+/// original, at most 500 copies in all; a negative spacing reverses its direction. With
+/// `pattern`, edit the pattern that id names instead of making a new one: keys left out keep
+/// their values, surviving instance ids are kept, and the pattern's type and seed entities
+/// cannot change. One undo step.
+#[derive(Debug, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = rectangular_required)]
+pub struct RectangularPatternParams {
+ /// The curves and points to copy, by id (one id is taken as a list of one). Left out only
+ /// with `pattern`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "StringList")]
+ pub entities: Option<Vec<String>>,
+ /// How many along the first direction, the original included: a whole number from 1 to 500
+ /// or a unitless expression. Left out only with `pattern`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "count_schema")]
+ pub count: Option<Value>,
+ /// The distance between copies along the first direction, in mm: a number or a length
+ /// expression. Left out only with `pattern`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "spacing_schema")]
+ pub spacing: Option<Value>,
+ /// How many along the second direction, a whole number from 1 to 500 or a unitless
+ /// expression. Default: 1.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "count_schema")]
+ pub count2: Option<Value>,
+ /// The distance between copies along the second direction, in mm. Default: `spacing`.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "spacing_schema")]
+ pub spacing2: Option<Value>,
+ /// The first direction as a vector [x, y] (finite, not zero; it is normalised). Default:
+ /// sketch x.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Point2")]
+ pub dir: Option<Vec2>,
+ /// The second direction as a vector [x, y]. Default: perpendicular to the first.
+ #[serde(default)]
+ pub dir2: Option<Point2>,
+ /// A sketch line the first direction follows (a live reference), by id.
+ #[serde(default)]
+ pub direction: Option<String>,
+ /// A sketch line the second direction follows (a live reference), by id.
+ #[serde(default)]
+ pub direction2: Option<String>,
+ /// Where the original stands along the first direction: `left`, `center` or `right`.
+ /// Default: right.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "alignment_schema")]
+ pub alignment: Option<PatternAlignment>,
+ /// The same along the second direction. Default: right.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "alignment_schema")]
+ pub alignment2: Option<PatternAlignment>,
+ /// Reverse the placement along the first direction, and the extra side of an even total with
+ /// `center`. Default: false.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub reversed: Option<bool>,
+ /// The same along the second direction. Default: false.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "bool")]
+ pub reversed2: Option<bool>,
+ /// The id of an existing rectangular pattern to edit instead of making a new one.
+ #[serde(default)]
+ pub pattern: Option<String>,
+ /// The sketch (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+fn spacing_schema(_: &mut SchemaGenerator) -> Schema {
+ number_or_expression("A distance in mm: a number or a length expression. Negative reverses the direction.")
+}
+
+fn rectangular_required(schema: &mut Schema) {
+ one_of_these(schema, pattern_forms(false));
+}
+
+impl RectangularPatternParams {
+ fn read(p: &Value) -> Read<Self> {
+ let entities = names(p, "entities")?;
+ let count = pattern_count(p, "count")?;
+ let spacing = quantity(p, "spacing", "`spacing` must be finite")?;
+ let count2 = pattern_count(p, "count2")?;
+ let spacing2 = quantity(p, "spacing2", "`spacing2` must be finite")?;
+ let dir = direction_vector(p, "dir")?;
+ let dir2 = direction_vector(p, "dir2")?.map(Point2);
+ let direction = direction_line(p, "direction")?;
+ let direction2 = direction_line(p, "direction2")?;
+ let alignment_first = alignment(p, "alignment")?;
+ let alignment_second = alignment(p, "alignment2")?;
+ let reversed = reversal(p, "reversed")?;
+ let reversed2 = reversal(p, "reversed2")?;
+ let pattern = pattern_id(p);
+ let sketch = sketch_of(p)?;
+ Ok(RectangularPatternParams {
+ entities,
+ count,
+ spacing,
+ count2,
+ spacing2,
+ dir,
+ dir2,
+ direction,
+ direction2,
+ alignment: alignment_first,
+ alignment2: alignment_second,
+ reversed,
+ reversed2,
+ pattern,
+ sketch,
+ })
+ }
+}
+
+read_params!(
+ TrimParams,
+ TrimPathParams,
+ BreakParams,
+ ExtendParams,
+ FilletParams,
+ ChamferEqualParams,
+ ChamferTwoParams,
+ ChamferDistanceAngleParams,
+ OffsetParams,
+ OffsetBreakParams,
+ MirrorParams,
+ MoveParams,
+ ScaleParams,
+ CircularPatternParams,
+ RectangularPatternParams,
+);
+
+// ---------------------------------------------------------------------------------------------
+// Replies
+
+/// What `sketch.trim` removed from a curve, and what became of it.
+#[derive(Clone, Debug, PartialEq, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum TrimOutcome {
+ /// Nothing crossed the curve: it went whole.
+ Deleted {
+ /// The curve that went.
+ deleted: String,
+ /// Single-line offsets whose linked extents the trim released.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ offset_released: Vec<String>,
+ },
+ /// A free-form curve (a spline) was trimmed: it was replaced by pieces.
+ Freeform {
+ /// The curve that was trimmed.
+ trimmed: String,
+ /// The ids of the pieces that are left; `null` when nothing was left to cut at.
+ pieces: Option<Vec<String>>,
+ /// Single-line offsets whose linked extents the trim released.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ offset_released: Vec<String>,
+ },
+ /// The piece went; the curve keeps its id and the rest is joined to what cut it.
+ Trimmed {
+ /// The curve that was trimmed.
+ trimmed: String,
+ /// Single-line offsets whose linked extents the trim released.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ offset_released: Vec<String>,
+ },
+}
+
+impl TrimOutcome {
+ /// The outcome with the offsets whose linked extents the trim released.
+ pub fn released(mut self, ids: Vec<String>) -> Self {
+ match &mut self {
+ TrimOutcome::Deleted { offset_released, .. }
+ | TrimOutcome::Freeform { offset_released, .. }
+ | TrimOutcome::Trimmed { offset_released, .. } => {
+ *offset_released = ids;
+ }
+ }
+ self
+ }
+}
+
+/// What `sketch.trim` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct TrimResult {
+ /// What was removed.
+ pub result: TrimOutcome,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.trim.path` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct TrimPathResult {
+ /// Each trim's result, in the order the path crossed the pieces.
+ pub trimmed: Vec<TrimOutcome>,
+ /// Each removed piece as a polyline of [x, y] points, in the same order.
+ pub removed: Vec<Vec<[f64; 2]>>,
+ /// Why crossings were passed over, each reason once.
+ pub skipped: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// `true` for a `dry_run`, which changed nothing; left out otherwise.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dry_run: Option<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>,
+}
+
+/// What `sketch.break` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BreakResult {
+ /// The curve's id and its new pieces' ids, in order along it.
+ pub curves: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.extend` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExtendResult {
+ /// What moved or was made: the id of the point the line's end moved to or the new curve's
+ /// id for one curve; the meeting point's id for two.
+ pub moved: String,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.fillet` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct FilletResult {
+ /// The arcs made, one per corner, in order.
+ pub curves: Vec<String>,
+ /// The constraints added: the tangencies, and the radius dimension on the first arc with the
+ /// others equal to it.
+ pub constraints: Vec<String>,
+ /// The parameter that holds the radius.
+ pub param: String,
+ /// The points of corners kept as virtual sharp corners.
+ pub virtual_corners: Vec<String>,
+ /// The constraints and dimensions that moved to a virtual corner.
+ pub moved_to_virtual_corner: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What the `sketch.chamfer.*` commands return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ChamferResult {
+ /// The lines made, one per corner, in order.
+ pub curves: Vec<String>,
+ /// The points of corners kept as virtual sharp corners.
+ pub virtual_corners: Vec<String>,
+ /// The constraints and dimensions that moved to a virtual corner.
+ pub moved_to_virtual_corner: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// One side of an offset.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OffsetSide {
+ /// The signed distance of this side, in mm.
+ pub distance: f64,
+ /// The curves it made.
+ pub curves: Vec<String>,
+ /// The parameter that drives it; `null` for a trimmed offset, which is not linked to its
+ /// source and has no distance to drive.
+ pub param: Option<String>,
+ /// Which instance it belongs to, counting from 1.
+ pub instance: usize,
+ /// Its offset association, when the boundary has one.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub association: Option<String>,
+}
+
+/// What `sketch.offset` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OffsetResult {
+ /// Every curve the offset made, side by side and instance by instance.
+ pub curves: Vec<String>,
+ /// Every constraint it added.
+ pub constraints: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// Each side of each instance.
+ pub sides: Vec<OffsetSide>,
+ /// The parameter that drives the primary distance; `null` when only trimmed offsets were
+ /// made.
+ pub param: Option<String>,
+ /// How many instances were made.
+ pub instances: usize,
+ /// The parameter that drives `distance2`, when it was given and drives something.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub param2: Option<String>,
+ /// The offset association, when the offset made one side only and has one; with two sides
+ /// or several instances each side of `sides` has its own.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub association: Option<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>,
+}
+
+/// What `sketch.offset.break` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct OffsetBreakResult {
+ /// The curve that was named.
+ pub curve: String,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// Every curve that stopped being an offset output, when the association had several.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub curves: Option<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>,
+}
+
+/// What `sketch.mirror` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MirrorResult {
+ /// The copies of the curves, in order.
+ pub curves: Vec<String>,
+ /// The constraints added: symmetry between each point and its copy, equal circles, and a
+ /// shared point held on the line.
+ pub constraints: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.move` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MoveResult {
+ /// The curves moved, or with `copy` the copies made, by id.
+ pub curves: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `sketch.scale` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ScaleResult {
+ /// The curves scaled, by id (an ellipse's axes come with it).
+ pub curves: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What the `sketch.pattern.*` commands return.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct PatternResult {
+ /// The pattern's id: give it as `pattern` to edit it.
+ pub pattern: String,
+ /// A circular pattern's centre point id; `null` for a rectangular one.
+ pub center: Option<String>,
+ /// The curves of every instance.
+ pub curves: Vec<String>,
+ /// The constraints of every instance.
+ pub constraints: Vec<String>,
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "sketch_modify_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/sketch_modify_tests.rs b/crates/engine/src/schema/sketch_modify_tests.rs
new file mode 100644
index 0000000000..3648cdfc7a
--- /dev/null
+++ b/crates/engine/src/schema/sketch_modify_tests.rs
@@ -0,0 +1,744 @@
+use serde_json::{Value, json};
+
+use super::{
+ BreakParams, BreakResult, ChamferDistanceAngleParams, ChamferEqualParams, ChamferResult, ChamferTwoParams, CircularPatternParams, ExtendParams,
+ ExtendResult, FilletParams, FilletResult, MirrorParams, MirrorResult, MoveParams, MoveResult, OffsetBreakParams, OffsetBreakResult, OffsetParams,
+ OffsetResult, OffsetSide, PatternResult, RectangularPatternParams, ScaleParams, ScaleResult, TrimOutcome, TrimParams, TrimPathParams,
+ TrimPathResult, TrimResult,
+};
+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 id_of(r: &Value, list: &str) -> String {
+ r["created"][list][0].as_str().unwrap_or_else(|| panic!("{r}")).to_string()
+}
+
+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}");
+ }
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<TrimParams>(), &["at", "curve", "sketch"]);
+ assert_keys(input_schema_for::<TrimPathParams>(), &["dry_run", "points", "sketch"]);
+ assert_keys(input_schema_for::<BreakParams>(), &["at", "curve", "points", "sketch"]);
+ assert_keys(input_schema_for::<ExtendParams>(), &["at", "curve", "curves", "sketch"]);
+ assert_keys(input_schema_for::<FilletParams>(), &["a", "b", "point", "points", "radius", "sketch"]);
+ assert_keys(input_schema_for::<ChamferEqualParams>(), &["a", "b", "distance", "point", "points", "sketch"]);
+ assert_keys(input_schema_for::<ChamferTwoParams>(), &["a", "b", "distance", "distance2", "point", "points", "sketch"]);
+ assert_keys(input_schema_for::<ChamferDistanceAngleParams>(), &["a", "angle", "b", "distance", "point", "points", "sketch"]);
+ assert_keys(
+ input_schema_for::<OffsetParams>(),
+ &["chain", "curves", "direction", "distance", "distance2", "flip", "instances", "side", "sketch", "symmetric"],
+ );
+ assert_keys(input_schema_for::<OffsetBreakParams>(), &["curve", "sketch"]);
+ assert_keys(input_schema_for::<MirrorParams>(), &["entities", "line", "sketch"]);
+ assert_keys(input_schema_for::<MoveParams>(), &["angle", "center", "copy", "entities", "rotate_constraints", "sketch", "translate"]);
+ assert_keys(input_schema_for::<ScaleParams>(), &["base", "entities", "factor", "sketch"]);
+ assert_keys(input_schema_for::<CircularPatternParams>(), &["alignment", "angle", "center", "count", "entities", "pattern", "reversed", "sketch"]);
+ assert_keys(
+ input_schema_for::<RectangularPatternParams>(),
+ &[
+ "alignment",
+ "alignment2",
+ "count",
+ "count2",
+ "dir",
+ "dir2",
+ "direction",
+ "direction2",
+ "entities",
+ "pattern",
+ "reversed",
+ "reversed2",
+ "sketch",
+ "spacing",
+ "spacing2",
+ ],
+ );
+}
+
+#[test]
+fn strict_keeps_todays_errors() {
+ let many = |n: usize, item: Value| Value::Array(vec![item; n]);
+ assert_strict_keeps_todays_errors(&[
+ ("sketch.trim", json!({})),
+ ("sketch.trim", json!({"curve": "l1"})),
+ ("sketch.trim", json!({"curve": "l1", "at": null})),
+ ("sketch.trim", json!({"curve": "l1", "at": [1]})),
+ ("sketch.trim", json!({"curve": "l1", "at": "x"})),
+ ("sketch.trim", json!({"at": [0, 0]})),
+ ("sketch.trim", json!({"at": [0, 0], "curve": 5})),
+ ("sketch.trim", json!({"at": [0, 0], "curve": null})),
+ ("sketch.trim", json!({"at": [0, 0], "curve": "l1", "sketch": -1})),
+ ("sketch.trim", json!({"at": [0, 0], "curve": "l1", "sketch": 1.5})),
+ ("sketch.trim", json!({"at": [0, 0], "curve": "l1", "sketch": true})),
+ ("sketch.trim.path", json!({})),
+ ("sketch.trim.path", json!({"points": 5})),
+ ("sketch.trim.path", json!({"points": null})),
+ ("sketch.trim.path", json!({"points": [[0, 0]]})),
+ ("sketch.trim.path", json!({"points": [[0, 0], "x"]})),
+ ("sketch.trim.path", json!({"points": many(2001, json!([0, 0]))})),
+ ("sketch.break", json!({})),
+ ("sketch.break", json!({"curve": "l1"})),
+ ("sketch.break", json!({"curve": "l1", "at": [1, 2, 3]})),
+ ("sketch.break", json!({"curve": 7, "at": [0, 0]})),
+ ("sketch.break", json!({"curve": "l1", "points": "x"})),
+ ("sketch.break", json!({"curve": "l1", "points": null})),
+ ("sketch.break", json!({"curve": "l1", "points": [[1, 2], "x"]})),
+ ("sketch.break", json!({"curve": "l1", "points": many(1001, json!([0, 0]))})),
+ ("sketch.extend", json!({})),
+ ("sketch.extend", json!({"curve": "l1"})),
+ ("sketch.extend", json!({"at": [0, 0]})),
+ ("sketch.extend", json!({"curve": 3, "at": [0, 0]})),
+ ("sketch.extend", json!({"curves": "x"})),
+ ("sketch.extend", json!({"curves": null})),
+ ("sketch.extend", json!({"curves": ["l1"]})),
+ ("sketch.extend", json!({"curves": ["l1", 2]})),
+ ("sketch.extend", json!({"curves": ["l1", "l2"], "curve": "l1"})),
+ ("sketch.extend", json!({"curves": ["l1", "l2"], "curve": null})),
+ ("sketch.extend", json!({"curves": ["l1", "l2"], "at": [0, 0]})),
+ ("sketch.extend", json!({"curves": ["l1", "l2"], "at": [[0, 0]]})),
+ ("sketch.extend", json!({"curves": ["l1", "l2"], "at": null})),
+ ("sketch.fillet", json!({"point": "l1.end"})),
+ ("sketch.fillet", json!({"point": "l1.end", "radius": true})),
+ ("sketch.fillet", json!({"point": "l1.end", "radius": " "})),
+ ("sketch.fillet", json!({"point": "l1.end", "radius": 1e9})),
+ ("sketch.fillet", json!({"radius": 1})),
+ ("sketch.fillet", json!({"radius": 1, "point": 5})),
+ ("sketch.fillet", json!({"radius": 1, "a": "l1"})),
+ ("sketch.fillet", json!({"radius": 1, "a": "l1", "b": 2})),
+ ("sketch.fillet", json!({"radius": 1, "a": 1, "b": "l2"})),
+ ("sketch.fillet", json!({"radius": 1, "points": []})),
+ ("sketch.fillet", json!({"radius": 1, "points": many(501, json!("l1.end"))})),
+ ("sketch.fillet", json!({"radius": 1, "points": [5]})),
+ ("sketch.fillet", json!({"radius": 1, "points": [{"a": "l1"}]})),
+ ("sketch.fillet", json!({"radius": 1, "points": [{}]})),
+ ("sketch.chamfer.equal_distance", json!({"point": "l1.end"})),
+ ("sketch.chamfer.equal_distance", json!({"point": "l1.end", "distance": "2"})),
+ ("sketch.chamfer.equal_distance", json!({"point": "l1.end", "distance": null})),
+ ("sketch.chamfer.equal_distance", json!({"point": "l1.end", "distance": 1e9})),
+ ("sketch.chamfer.equal_distance", json!({"distance": 2})),
+ ("sketch.chamfer.equal_distance", json!({"distance": 2, "points": []})),
+ ("sketch.chamfer.equal_distance", json!({"distance": 2, "points": [5]})),
+ ("sketch.chamfer.two_distance", json!({"point": "l1.end", "distance2": 2})),
+ ("sketch.chamfer.two_distance", json!({"point": "l1.end", "distance": 2})),
+ ("sketch.chamfer.two_distance", json!({"point": "l1.end", "distance": 2, "distance2": "x"})),
+ ("sketch.chamfer.two_distance", json!({"distance": 2, "distance2": 3, "a": "l1"})),
+ ("sketch.chamfer.distance_angle", json!({"point": "l1.end", "distance": 2})),
+ ("sketch.chamfer.distance_angle", json!({"point": "l1.end", "distance": 2, "angle": "45"})),
+ ("sketch.chamfer.distance_angle", json!({"point": "l1.end", "angle": 45})),
+ ("sketch.chamfer.distance_angle", json!({"distance": 2, "angle": 45})),
+ ("sketch.offset", json!({})),
+ ("sketch.offset", json!({"curves": []})),
+ ("sketch.offset", json!({"curves": null, "distance": 1})),
+ ("sketch.offset", json!({"curves": 5, "distance": 1})),
+ ("sketch.offset", json!({"curves": [5], "distance": 1})),
+ ("sketch.offset", json!({"curves": many(501, json!("l1")), "distance": 1})),
+ ("sketch.offset", json!({"curves": ["l1"]})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": true})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": ""})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1e9})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "direction": "negative"})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "direction": "Reverse"})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "direction": "up"})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "distance2": null})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "distance2": true})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "instances": 0})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "instances": 101})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "instances": 2.5})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "instances": true})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "instances": ["2"]})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "instances": " "})),
+ ("sketch.offset", json!({"curves": ["l1"], "distance": 1, "sketch": []})),
+ ("sketch.offset.break", json!({})),
+ ("sketch.offset.break", json!({"curve": 5})),
+ ("sketch.offset.break", json!({"curve": null})),
+ ("sketch.offset.break", json!({"curve": "l1", "sketch": -3})),
+ ("sketch.mirror", json!({})),
+ ("sketch.mirror", json!({"entities": ["l1"]})),
+ ("sketch.mirror", json!({"entities": ["l1"], "line": 5})),
+ ("sketch.mirror", json!({"entities": ["l1"], "line": null})),
+ ("sketch.mirror", json!({"entities": ["l1"], "line": ["l2"]})),
+ ("sketch.mirror", json!({"entities": 5, "line": "l2"})),
+ ("sketch.mirror", json!({"entities": [5], "line": "l2"})),
+ ("sketch.mirror", json!({"entities": ["l1"], "line": "l2", "sketch": 1.5})),
+ ("sketch.move", json!({"entities": ["l1"], "translate": 5})),
+ ("sketch.move", json!({"entities": ["l1"], "translate": null})),
+ ("sketch.move", json!({"entities": ["l1"], "translate": [1]})),
+ ("sketch.move", json!({"entities": ["l1"], "angle": "30"})),
+ ("sketch.move", json!({"entities": ["l1"], "angle": null})),
+ ("sketch.move", json!({"entities": ["l1"], "angle": 1e9})),
+ ("sketch.move", json!({"entities": null})),
+ ("sketch.move", json!({"entities": [true]})),
+ ("sketch.move", json!({"entities": ["l1"], "center": true})),
+ ("sketch.move", json!({"entities": ["l1"], "center": null})),
+ ("sketch.move", json!({"entities": ["l1"], "center": [1]})),
+ ("sketch.scale", json!({"entities": ["l1"]})),
+ ("sketch.scale", json!({"entities": ["l1"], "factor": 0})),
+ ("sketch.scale", json!({"entities": ["l1"], "factor": "2"})),
+ ("sketch.scale", json!({"entities": ["l1"], "factor": 1e6})),
+ ("sketch.scale", json!({"entities": ["l1"], "factor": 2, "base": true})),
+ ("sketch.scale", json!({"entities": ["l1"], "factor": 2, "base": [1]})),
+ ("sketch.scale", json!({"factor": 2})),
+ ("sketch.scale", json!({"entities": "l1", "factor": 2, "sketch": false})),
+ ("sketch.pattern.circular", json!({})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0]})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": true})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": null})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 0})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 2.5})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 501})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 1e9})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": 5, "count": 3})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": null, "count": 3})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "count": 3})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 3, "angle": true})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 3, "angle": 0})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 3, "angle": 361})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 3, "alignment": "middle"})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 3, "alignment": null})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 3, "reversed": "yes"})),
+ ("sketch.pattern.circular", json!({"entities": ["l1"], "center": [20, 0], "count": 3, "reversed": null})),
+ ("sketch.pattern.circular", json!({"center": [20, 0], "count": 3})),
+ ("sketch.pattern.circular", json!({"entities": 5, "center": [20, 0], "count": 3})),
+ ("sketch.pattern.rectangular", json!({})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": true})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": null})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 1e9})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "spacing": 5})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 0, "spacing": 5})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "count2": false})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "count2": 501})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "spacing2": [1]})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "dir": [0, 0]})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "dir": null})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "dir": "x"})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "dir2": [0, 0]})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "direction": 5})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "direction2": true})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "alignment": "up"})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "alignment2": 1})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "reversed": 1})),
+ ("sketch.pattern.rectangular", json!({"entities": ["l1"], "count": 3, "spacing": 5, "reversed2": "no"})),
+ ("sketch.pattern.rectangular", json!({"count": 3, "spacing": 5})),
+ ]);
+}
+
+/// What the check says about a call, one message per problem.
+fn warnings(id: &str, p: Value) -> Vec<String> {
+ issues(id, &p).into_iter().map(|i| i.message).collect()
+}
+
+/// The keys a handler reads only in some cases are read only in those cases, so a call that works
+/// today gets no warning for what the handler never looks at, and a call the handler refuses is
+/// refused for its key with the handler's message.
+#[test]
+fn the_types_read_each_key_as_the_handler_does() {
+ let none = Vec::<String>::new();
+ // Break: `points` when the key is there, otherwise `at`.
+ assert_eq!(warnings("sketch.break", json!({"curve": "l1", "points": [[0, 1]]})), none);
+ assert_eq!(warnings("sketch.break", json!({"curve": "l1", "points": [[0, 1]], "at": 5})), none);
+ assert_eq!(warnings("sketch.break", json!({"curve": "l1", "at": [0, 1]})), none);
+ assert_eq!(warnings("sketch.break", json!({"curve": "l1", "at": 5})), ["`at` must be a point [x, y]"]);
+ assert_eq!(warnings("sketch.break", json!({"curve": "l1", "points": null, "at": [0, 1]})), ["`points` must be a list of points"]);
+ assert_eq!(warnings("sketch.break", json!({"curve": "l1", "points": [5]})), ["`points` must contain [x, y] points"]);
+ // Extend: the two-curve form when `curves` is there.
+ assert_eq!(warnings("sketch.extend", json!({"curve": "l1", "at": [0, 1]})), none);
+ assert_eq!(warnings("sketch.extend", json!({"curves": ["l1", "l2"]})), none);
+ assert_eq!(warnings("sketch.extend", json!({"curves": ["l1", "l2"], "at": [[0, 1], {"x": 1, "y": 2}]})), none);
+ assert_eq!(
+ warnings("sketch.extend", json!({"curves": ["l1", "l2"], "curve": "l1"})),
+ ["give `curve` with `at` (one curve) or `curves` (two curves), not both"]
+ );
+ assert_eq!(
+ warnings("sketch.extend", json!({"curves": ["l1", "l2"], "at": [0, 1]})),
+ ["with `curves`, `at` is one point per curve: [[x,y],[x,y]]"]
+ );
+ assert_eq!(warnings("sketch.extend", json!({"curve": "l1", "at": [[0, 1], [1, 2]]})), ["`at` must be a point [x, y]"]);
+ // Fillet and chamfers: `points` when it is a list; otherwise `point`, or `a` and `b` when
+ // `point` is not text.
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "point": "l1.end"})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": "r / 2", "a": "l1", "b": "l2"})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "point": "l1.end", "a": 5, "b": null})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "point": 7, "a": "l1", "b": "l2"})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "points": ["l1.end", {"a": "l1", "b": "l2"}, {"point": "l3.end", "a": 4}]})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "points": ["l1.end"], "point": 3, "a": 4, "b": 5})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "points": "l1.end", "point": "l2.end"})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "point": null, "a": "l1", "b": "l2"})), none);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "a": "l1"})), ["`b` must be a line"]);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "points": [{"b": "l1"}]})), ["`a` must be a line"]);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "points": [3]})), ["`a` must be a line"]);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 2, "points": []})), ["`points` must list 1…500 corners"]);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": [1], "point": "l1.end"})), ["`radius` must be a number or an expression"]);
+ assert_eq!(warnings("sketch.fillet", json!({"radius": 1e10, "point": "l1.end"})), ["`radius` must be a number between -1e9 and 1e9"]);
+ assert_eq!(warnings("sketch.chamfer.equal_distance", json!({"distance": 2, "points": ["l1.end"], "a": 1})), none);
+ assert_eq!(warnings("sketch.chamfer.two_distance", json!({"distance": 2, "distance2": -1, "a": "l1", "b": "l2"})), none);
+ assert_eq!(warnings("sketch.chamfer.distance_angle", json!({"distance": 2, "angle": 30, "point": "l1.end"})), none);
+ assert_eq!(
+ warnings("sketch.chamfer.distance_angle", json!({"distance": 2, "angle": "30", "point": "l1.end"})),
+ ["`angle` must be a number (degrees)"]
+ );
+ // Offset: `symmetric` is read unless `direction` is `symmetric`; `direction` that is not text
+ // is not read at all.
+ let offset = |extra: Value| {
+ let mut p = json!({"curves": ["l1"], "distance": 2});
+ for (k, v) in extra.as_object().into_iter().flatten() {
+ p[k] = v.clone();
+ }
+ warnings("sketch.offset", p)
+ };
+ assert_eq!(offset(json!({"direction": "Symmetric", "symmetric": "yes"})), none);
+ assert_eq!(offset(json!({"direction": "one_side", "symmetric": true})), none);
+ assert_eq!(offset(json!({"direction": 5, "symmetric": true})), none);
+ assert_eq!(offset(json!({"direction": null, "side": [1, 2], "chain": false, "flip": true})), none);
+ assert_eq!(offset(json!({"symmetric": "yes"})), ["`symmetric` must be true or false"]);
+ assert_eq!(offset(json!({"direction": "positive", "symmetric": 1})), ["`symmetric` must be true or false"]);
+ assert_eq!(offset(json!({"distance2": "d / 2", "instances": "n"})), none);
+ assert_eq!(offset(json!({"instances": 100, "side": {"x": 1, "y": 2}})), none);
+ assert_eq!(offset(json!({"instances": 2.0})), none);
+ assert_eq!(offset(json!({"instances": 0})), ["`instances` must be a whole number from 1 to 100, or an expression for one"]);
+ // A `side` that is not a point is read as left out, as the handler does.
+ assert_eq!(offset(json!({"side": "left"})), none);
+ assert_eq!(offset(json!({"flip": 1})), ["`flip` must be true or false"]);
+ assert_eq!(offset(json!({"direction": "down"})), ["unknown direction `down` (one_side, symmetric)"]);
+ assert_eq!(
+ offset(json!({"direction": "FLIP"})),
+ ["an offset has no negative direction: give a negative `distance`, or a `side` to offset toward"]
+ );
+ assert_eq!(offset(json!({"distance2": null})), ["`distance2` must be a length expression"]);
+ assert_eq!(warnings("sketch.offset", json!({"curves": "l1", "distance": "2 mm"})), none);
+ // Move and scale: a point or a point's id.
+ assert_eq!(warnings("sketch.move", json!({"entities": "l1", "translate": {"x": 1, "y": 2}, "angle": 90, "center": "p1", "copy": true})), none);
+ assert_eq!(warnings("sketch.move", json!({"entities": ["l1"], "center": [1, 2], "rotate_constraints": false})), none);
+ assert_eq!(warnings("sketch.move", json!({"entities": ["l1"], "center": [1]})), ["`center` must be [x, y] or a point id"]);
+ assert_eq!(warnings("sketch.move", json!({"entities": ["l1"], "copy": "yes"})), ["`copy` must be true or false"]);
+ assert_eq!(warnings("sketch.scale", json!({"entities": ["l1"], "factor": 2, "base": "p1"})), none);
+ assert_eq!(warnings("sketch.scale", json!({"entities": ["l1"], "factor": 2, "base": [1, 2]})), none);
+ assert_eq!(warnings("sketch.scale", json!({"entities": ["l1"], "factor": 0})), ["`factor` must be a positive number"]);
+ assert_eq!(warnings("sketch.scale", json!({"entities": ["l1"], "factor": 2, "base": 7})), ["`base` must be [x, y] or a point id"]);
+ // Mirror: a curve id, an axis, or an origin axis as an object.
+ assert_eq!(warnings("sketch.mirror", json!({"entities": ["l1", "p2"], "line": "y"})), none);
+ assert_eq!(warnings("sketch.mirror", json!({"entities": ["l1"], "line": {"axis": "Y"}})), none);
+ assert_eq!(warnings("sketch.mirror", json!({"entities": ["l1"], "line": 3})), ["`line` must be a curve id, or x / y for a sketch axis"]);
+ // Patterns: a pattern being edited needs only what changes.
+ assert_eq!(warnings("sketch.pattern.circular", json!({"pattern": "pat1"})), none);
+ assert_eq!(warnings("sketch.pattern.circular", json!({"pattern": "pat1", "count": "n + 1", "angle": "90 deg", "reversed": true})), none);
+ assert_eq!(
+ warnings("sketch.pattern.circular", json!({"entities": ["c1"], "center": "p3", "count": 3, "angle": -90, "alignment": "center"})),
+ none
+ );
+ assert_eq!(warnings("sketch.pattern.circular", json!({"pattern": 4, "count": 3})), none);
+ assert_eq!(warnings("sketch.pattern.rectangular", json!({"pattern": "pat1"})), none);
+ assert_eq!(warnings("sketch.pattern.rectangular", json!({"pattern": "pat1", "spacing": "w * 2", "count2": "m"})), none);
+ assert_eq!(
+ warnings(
+ "sketch.pattern.rectangular",
+ json!({"entities": ["c1"], "count": 3, "spacing": -5, "count2": 2, "spacing2": 4, "dir": [1, 1], "dir2": null, "direction": "l1",
+ "direction2": null, "alignment": "left", "alignment2": "center", "reversed": true, "reversed2": false})
+ ),
+ none
+ );
+ assert_eq!(
+ warnings("sketch.pattern.rectangular", json!({"entities": ["c1"], "count": 3, "spacing": 5, "dir2": [0, 0]})),
+ ["`dir2` must be a finite nonzero vector"]
+ );
+ assert_eq!(warnings("sketch.pattern.circular", json!({"pattern": "pat1", "angle": 400})), ["`angle` must be nonzero and at most 360 degrees"]);
+ assert_eq!(warnings("sketch.pattern.circular", json!({"pattern": "pat1", "center": [1]})), ["`center` must be [x,y] or a point ref"]);
+ // A key the command doesn't read is unknown to it, and says what it would have been.
+ assert_eq!(
+ warnings("sketch.pattern.circular", json!({"entities": ["c1"], "center": [1, 2], "count": 3, "spacing": 4})),
+ ["unknown key `spacing`"]
+ );
+ assert_eq!(warnings("sketch.trim", json!({"curve": "l1", "at": [1, 2], "curv": "l2"})), ["unknown key `curv`; did you mean `curve`?"]);
+}
+
+/// The schemas take the calls the handlers take, and say which keys a handler cannot do without.
+#[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::<TrimParams>(),
+ &[
+ (json!({"curve": "l1", "at": [1, 2]}), true),
+ (json!({"curve": "l1"}), false),
+ (json!({"at": [1, 2]}), false),
+ (json!({"curve": "l1", "at": 3}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<TrimPathParams>(),
+ &[
+ (json!({"points": [[0, 0], [1, 1]]}), true),
+ (json!({"points": [[0, 0], [1, 1]], "dry_run": true}), true),
+ (json!({"points": [[0, 0]]}), false),
+ (json!({}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<BreakParams>(),
+ &[
+ (json!({"curve": "l1", "at": [1, 2]}), true),
+ (json!({"curve": "l1", "points": [[1, 2]], "sketch": 4}), true),
+ (json!({"curve": "l1"}), false),
+ (json!({"at": [1, 2]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ExtendParams>(),
+ &[
+ (json!({"curve": "l1", "at": [1, 2]}), true),
+ (json!({"curves": ["l1", "l2"]}), true),
+ (json!({"curves": ["l1", "l2"], "at": [[1, 2], [3, 4]]}), true),
+ (json!({"curves": ["l1", "l2"], "curve": "l1"}), false),
+ (json!({"curves": ["l1"]}), false),
+ (json!({"curve": "l1"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<FilletParams>(),
+ &[
+ (json!({"radius": 2, "point": "l1.end"}), true),
+ (json!({"radius": "r", "a": "l1", "b": "l2"}), true),
+ (json!({"radius": 2, "points": ["l1.end", {"a": "l1", "b": "l2"}]}), true),
+ (json!({"point": "l1.end"}), false),
+ (json!({"radius": 2}), false),
+ (json!({"radius": 2, "a": "l1"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ChamferTwoParams>(),
+ &[(json!({"distance": 1, "distance2": 2, "point": "l1.end"}), true), (json!({"distance": 1, "point": "l1.end"}), false)],
+ );
+ takes(
+ input_schema_for::<OffsetParams>(),
+ &[
+ (json!({"curves": ["l1"], "distance": 2}), true),
+ (json!({"curves": "l1", "distance": "w / 2", "direction": "symmetric", "instances": 3, "side": [1, 2]}), true),
+ (json!({"curves": ["l1"]}), false),
+ (json!({"distance": 2}), false),
+ (json!({"curves": ["l1"], "distance": 2, "instances": 101}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<ScaleParams>(),
+ &[
+ (json!({"entities": ["l1"], "factor": 2, "base": "p1"}), true),
+ (json!({"entities": ["l1"], "factor": 0}), false),
+ (json!({"entities": ["l1"]}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<CircularPatternParams>(),
+ &[
+ (json!({"entities": ["c1"], "center": [1, 2], "count": 4}), true),
+ (json!({"entities": ["c1"], "center": "p1", "count": "n", "angle": "90 deg", "alignment": "center"}), true),
+ (json!({"pattern": "pat1", "count": 5}), true),
+ (json!({"entities": ["c1"], "count": 4}), false),
+ (json!({"entities": ["c1"], "center": [1, 2], "count": 4, "alignment": "middle"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<RectangularPatternParams>(),
+ &[
+ (json!({"entities": ["c1"], "count": 3, "spacing": 5, "dir": [1, 0], "dir2": [0, 1], "count2": 2}), true),
+ (json!({"pattern": "pat1"}), true),
+ (json!({"entities": ["c1"], "count": 3}), false),
+ ],
+ );
+}
+
+fn matches(schema: schemars::Schema, what: &str, reply: &Value) {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, reply), "{what}: {reply} doesn't match {schema}");
+ assert!(reply.get("param_warnings").is_none(), "{what}: {reply}");
+}
+
+/// A line of the square's sketch that crosses its left and right sides.
+fn crossing_line(s: &mut Session) -> String {
+ id_of(&run(s, "sketch.line", json!({"points": [[-20, 3], [20, 3]], "infer": false})), "curves")
+}
+
+#[test]
+fn trim_and_break_replies_match_the_output_schema() {
+ // Trim: a piece goes (the curve keeps its id), a curve nothing crosses goes whole, and a
+ // spline is replaced by pieces or goes.
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let line = crossing_line(&mut s);
+ let far = id_of(&run(&mut s, "sketch.line", json!({"points": [[40, 40], [50, 40]], "infer": false})), "curves");
+ let spline = id_of(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[-5, 0], [0, 20], [5, 0]]})), "curves");
+ let lone = id_of(&run(&mut s, "sketch.spline.fit_point", json!({"points": [[60, 60], [70, 65], [80, 60]]})), "curves");
+ let trimmed = run(&mut s, "sketch.trim", json!({"curve": line, "at": [15, 3]}));
+ assert_eq!(trimmed["result"], json!({"trimmed": line}), "{trimmed}");
+ matches(output_schema_for::<TrimResult>(), "sketch.trim", &trimmed);
+ let sketch = s.active_sketch;
+ let deleted = run(&mut s, "sketch.trim", json!({"curve": far, "at": [45, 40], "sketch": sketch}));
+ assert_eq!(deleted["result"], json!({"deleted": far}), "{deleted}");
+ matches(output_schema_for::<TrimResult>(), "sketch.trim", &deleted);
+ let split = run(&mut s, "sketch.trim", json!({"curve": spline, "at": [0, 20]}));
+ assert_eq!(split["result"]["trimmed"], json!(spline), "{split}");
+ assert!(split["result"]["pieces"].is_array(), "{split}");
+ matches(output_schema_for::<TrimResult>(), "sketch.trim", &split);
+ let whole = run(&mut s, "sketch.trim", json!({"curve": lone, "at": [70, 65]}));
+ assert_eq!(whole["result"], json!({"trimmed": lone, "pieces": null}), "{whole}");
+ matches(output_schema_for::<TrimResult>(), "sketch.trim", &whole);
+
+ // A line that is a single-line offset's source releases its linked extents.
+ let (mut s, sides) = editing(ParamCheck::Warn);
+ let made = run(&mut s, "sketch.offset", json!({"curves": [sides[0]], "distance": 2}));
+ assert!(made["curves"].is_array(), "{made}");
+ let cutter = id_of(&run(&mut s, "sketch.line", json!({"points": [[0, -30], [0, 30]], "infer": false})), "curves");
+ let released = run(&mut s, "sketch.trim", json!({"curve": sides[0], "at": [5, -10]}));
+ matches(output_schema_for::<TrimResult>(), "sketch.trim", &released);
+ let _ = cutter;
+
+ // Trim along a path, and its dry run.
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let path = json!({"points": [[-20, 3], [20, 3]]});
+ let dry = run(&mut s, "sketch.trim.path", json!({"points": path["points"], "dry_run": true}));
+ assert_eq!(dry["dry_run"], json!(true), "{dry}");
+ let schema = output_schema_for::<TrimPathResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &dry), "{dry}");
+ assert!(dry.get("param_warnings").is_none(), "{dry}");
+ let done = run(&mut s, "sketch.trim.path", path);
+ assert!(done.get("dry_run").is_none() && done["trimmed"].as_array().is_some_and(|t| !t.is_empty()), "{done}");
+ matches(output_schema_for::<TrimPathResult>(), "sketch.trim.path", &done);
+
+ // Break, at the crossings and at given positions.
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let line = crossing_line(&mut s);
+ let broken = run(&mut s, "sketch.break", json!({"curve": line, "at": [0, 3]}));
+ assert!(broken["curves"].as_array().is_some_and(|c| c.len() == 3), "{broken}");
+ matches(output_schema_for::<BreakResult>(), "sketch.break", &broken);
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let line = id_of(&run(&mut s, "sketch.line", json!({"points": [[-5, 30], [5, 30]], "infer": false})), "curves");
+ let broken = run(&mut s, "sketch.break", json!({"curve": line, "points": [[-2, 30], [2, 31], [2, 30]]}));
+ assert!(broken["curves"].as_array().is_some_and(|c| c.len() == 3), "{broken}");
+ matches(output_schema_for::<BreakResult>(), "sketch.break", &broken);
+}
+
+#[test]
+fn extend_replies_match_the_output_schema() {
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let short = id_of(&run(&mut s, "sketch.line", json!({"points": [[0, 0], [5, 0]], "infer": false})), "curves");
+ let extended = run(&mut s, "sketch.extend", json!({"curve": short, "at": [5, 0]}));
+ matches(output_schema_for::<ExtendResult>(), "sketch.extend", &extended);
+ let a = id_of(&run(&mut s, "sketch.line", json!({"points": [[30, 0], [30, 5]], "infer": false})), "curves");
+ let b = id_of(&run(&mut s, "sketch.line", json!({"points": [[40, 20], [45, 20]], "infer": false})), "curves");
+ let met = run(&mut s, "sketch.extend", json!({"curves": [a, b]}));
+ matches(output_schema_for::<ExtendResult>(), "sketch.extend", &met);
+ let c = id_of(&run(&mut s, "sketch.line", json!({"points": [[60, 0], [60, 5]], "infer": false})), "curves");
+ let d = id_of(&run(&mut s, "sketch.line", json!({"points": [[70, 20], [75, 20]], "infer": false})), "curves");
+ let met = run(&mut s, "sketch.extend", json!({"curves": [c, d], "at": [[60, 5], [70, 20]]}));
+ matches(output_schema_for::<ExtendResult>(), "sketch.extend", &met);
+}
+
+#[test]
+fn fillet_and_chamfer_replies_match_the_output_schema() {
+ let fillet = output_schema_for::<FilletResult>();
+ let chamfer = output_schema_for::<ChamferResult>();
+ for p in [
+ json!({"point": "l2.end", "radius": 2}),
+ json!({"a": "l1", "b": "l2", "radius": "1 + 1"}),
+ json!({"points": ["l1.end", {"a": "l2", "b": "l3"}, {"point": "l3.end"}], "radius": 2}),
+ json!({"points": ["l1.end"], "point": 3, "a": 1, "radius": 2}),
+ ] {
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let r = run(&mut s, "sketch.fillet", p.clone());
+ assert!(r["param"].is_string() && r["curves"].as_array().is_some_and(|c| !c.is_empty()), "{r}");
+ matches(fillet.clone(), &format!("sketch.fillet {p}"), &r);
+ }
+ for (id, p) in [
+ ("sketch.chamfer.equal_distance", json!({"point": "l2.end", "distance": 2})),
+ ("sketch.chamfer.equal_distance", json!({"points": ["l1.end", {"a": "l2", "b": "l3"}], "distance": 2})),
+ ("sketch.chamfer.two_distance", json!({"a": "l1", "b": "l2", "distance": 2, "distance2": 3})),
+ ("sketch.chamfer.distance_angle", json!({"point": "l2.end", "distance": 2, "angle": 40})),
+ ] {
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let r = run(&mut s, id, p.clone());
+ assert!(r["curves"].as_array().is_some_and(|c| !c.is_empty()), "{r}");
+ matches(chamfer.clone(), &format!("{id} {p}"), &r);
+ }
+}
+
+#[test]
+fn offset_replies_match_the_output_schema() {
+ let schema = output_schema_for::<OffsetResult>();
+ for p in [
+ json!({"curves": ["l1", "l2", "l3", "l4"], "distance": 2}),
+ json!({"curves": ["l1", "l2", "l3", "l4"], "distance": "2 mm", "flip": true, "chain": false}),
+ json!({"curves": ["l1"], "distance": 2, "side": [0, 30]}),
+ json!({"curves": "l1", "distance": 2, "direction": "symmetric"}),
+ json!({"curves": ["l1"], "distance": 2, "symmetric": true}),
+ json!({"curves": ["l1"], "distance": 2, "distance2": 3, "side": [0, 30]}),
+ json!({"curves": ["l1"], "distance": 2, "instances": 3, "side": [0, 30]}),
+ json!({"curves": ["l1"], "distance": 2, "direction": "one_side", "instances": "1 + 1", "side": [0, 30]}),
+ ] {
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let r = run(&mut s, "sketch.offset", p.clone());
+ assert!(r["sides"].as_array().is_some_and(|c| !c.is_empty()), "{r}");
+ matches(schema.clone(), &format!("sketch.offset {p}"), &r);
+ }
+ // Break the association of what an offset made, a single curve's and a closed boundary's.
+ for sources in [json!(["l1"]), json!(["l1", "l2", "l3", "l4"])] {
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let made = run(&mut s, "sketch.offset", json!({"curves": sources, "distance": 2, "side": [0, 30]}));
+ let output = made["curves"][0].as_str().unwrap_or_default().to_string();
+ let r = run(&mut s, "sketch.offset.break", json!({"curve": output}));
+ assert_eq!(r["curve"], json!(output), "{r}");
+ matches(output_schema_for::<OffsetBreakResult>(), "sketch.offset.break", &r);
+ }
+}
+
+#[test]
+fn mirror_move_scale_and_pattern_replies_match_the_output_schema() {
+ let mirror = output_schema_for::<MirrorResult>();
+ for line in [json!("l3"), json!("y"), json!({"axis": "Y"})] {
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let r = run(&mut s, "sketch.mirror", json!({"entities": ["l1"], "line": line}));
+ assert!(r["curves"].as_array().is_some_and(|c| !c.is_empty()), "{r}");
+ matches(mirror.clone(), &format!("sketch.mirror {line}"), &r);
+ }
+ let moved = output_schema_for::<MoveResult>();
+ let scaled = output_schema_for::<ScaleResult>();
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let c = id_of(&run(&mut s, "sketch.circle.center", json!({"center": [30, 0], "radius": 3})), "curves");
+ let r = run(&mut s, "sketch.move", json!({"entities": [c], "translate": [1, 2], "angle": 15, "center": [0, 0]}));
+ matches(moved.clone(), "sketch.move", &r);
+ let r = run(&mut s, "sketch.move", json!({"entities": c, "translate": {"x": 5, "y": 0}, "copy": true, "rotate_constraints": false}));
+ assert_eq!(r["curves"].as_array().map(Vec::len), Some(1), "{r}");
+ matches(moved, "sketch.move", &r);
+ let r = run(&mut s, "sketch.scale", json!({"entities": [c], "factor": 2, "base": [0, 0]}));
+ matches(scaled.clone(), "sketch.scale", &r);
+ let r = run(&mut s, "sketch.scale", json!({"entities": [c], "factor": 0.5}));
+ matches(scaled, "sketch.scale", &r);
+
+ let pattern = output_schema_for::<PatternResult>();
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let c = id_of(&run(&mut s, "sketch.circle.center", json!({"center": [30, 0], "radius": 2})), "curves");
+ let made = run(&mut s, "sketch.pattern.circular", json!({"entities": [c], "center": [0, 0], "count": 4}));
+ assert!(made["center"].is_string(), "{made}");
+ matches(pattern.clone(), "sketch.pattern.circular", &made);
+ let edited = run(&mut s, "sketch.pattern.circular", json!({"pattern": made["pattern"], "count": 5, "angle": 180, "alignment": "center"}));
+ assert_eq!(edited["pattern"], made["pattern"], "{edited}");
+ matches(pattern.clone(), "sketch.pattern.circular", &edited);
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let c = id_of(&run(&mut s, "sketch.circle.center", json!({"center": [30, 30], "radius": 2})), "curves");
+ let made =
+ run(&mut s, "sketch.pattern.rectangular", json!({"entities": [c], "count": 3, "spacing": 8, "count2": 2, "spacing2": "6 mm", "dir": [1, 0]}));
+ assert!(made["center"].is_null(), "{made}");
+ matches(pattern.clone(), "sketch.pattern.rectangular", &made);
+ let edited =
+ run(&mut s, "sketch.pattern.rectangular", json!({"pattern": made["pattern"], "spacing": 9, "alignment": "center", "reversed2": true}));
+ matches(pattern, "sketch.pattern.rectangular", &edited);
+}
+
+/// A misspelt key still runs in Warn, and says so, with a reply that matches.
+#[test]
+fn a_misspelt_key_is_reported_in_warn() {
+ let line = |s: &mut Session| id_of(&run(s, "sketch.line", json!({"points": [[0, 0], [5, 0]], "infer": false})), "curves");
+ let calls: Vec<(&str, fn(&mut Session) -> Value)> = vec![
+ ("sketch.trim", |s| json!({"curve": crossing_line(s), "at": [15, 3], "atx": [1, 2]})),
+ ("sketch.trim.path", |_| json!({"points": [[-20, 3], [20, 3]], "point": [1, 1]})),
+ ("sketch.break", |s| json!({"curve": crossing_line(s), "at": [0, 3], "curv": "l1"})),
+ (
+ "sketch.extend",
+ |s| json!({"curve": id_of(&run(s, "sketch.line", json!({"points": [[0, 0], [5, 0]], "infer": false})), "curves"), "at": [5, 0], "att": 1}),
+ ),
+ ("sketch.fillet", |_| json!({"point": "l2.end", "radius": 2, "radious": 3})),
+ ("sketch.chamfer.equal_distance", |_| json!({"point": "l2.end", "distance": 2, "distence": 3})),
+ ("sketch.chamfer.two_distance", |_| json!({"point": "l2.end", "distance": 2, "distance2": 1, "distence": 3})),
+ ("sketch.chamfer.distance_angle", |_| json!({"point": "l2.end", "distance": 2, "angle": 40, "angel": 3})),
+ ("sketch.offset", |_| json!({"curves": ["l1"], "distance": 2, "side": [0, 30], "distence": 3})),
+ ("sketch.mirror", |_| json!({"entities": ["l1"], "line": "l3", "lines": 1})),
+ ("sketch.move", |_| json!({"entities": ["l1"], "translate": [1, 2], "translat": 1})),
+ ("sketch.scale", |_| json!({"entities": ["l1"], "factor": 2, "facter": 1})),
+ ];
+ for (id, call) in calls {
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let p = call(&mut s);
+ let r = run(&mut s, id, p.clone());
+ let warned = r["param_warnings"].as_array().unwrap_or_else(|| panic!("{id} {p}: {r}"));
+ assert_eq!(warned.len(), 1, "{id}: {r}");
+ assert!(warned[0].as_str().is_some_and(|w| w.starts_with("unknown key `")), "{id}: {r}");
+ }
+ // The ones that need a shape of their own.
+ let (mut s, _) = editing(ParamCheck::Warn);
+ let a = line(&mut s);
+ let c = id_of(&run(&mut s, "sketch.circle.center", json!({"center": [30, 0], "radius": 2})), "curves");
+ for (id, p) in [
+ ("sketch.offset.break", None),
+ ("sketch.pattern.circular", Some(json!({"entities": [c], "center": [0, 0], "count": 3, "cnt": 1}))),
+ ("sketch.pattern.rectangular", Some(json!({"entities": [c], "count": 3, "spacing": 8, "spaceing": 1}))),
+ ] {
+ let Some(p) = p else { continue };
+ let r = run(&mut s, id, p.clone());
+ let warned = r["param_warnings"].as_array().unwrap_or_else(|| panic!("{id} {p}: {r}"));
+ assert_eq!(warned.len(), 1, "{id}: {r}");
+ }
+ let made = run(&mut s, "sketch.offset", json!({"curves": [a], "distance": 1, "side": [0, 30]}));
+ let output = made["curves"][0].as_str().unwrap_or_default().to_string();
+ let r = run(&mut s, "sketch.offset.break", json!({"curve": output, "sketches": 2}));
+ assert!(r["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{r}");
+ let schema = output_schema_for::<OffsetBreakResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");
+}
+
+/// The reply types serialize to the JSON the handlers built before: a sketch command's reply
+/// also carries the `created` the session adds, and an absent `param2` or `association` is left
+/// out.
+#[test]
+fn replies_keep_their_shape() {
+ let keys = |v: &Value| v.as_object().map(|o| o.keys().cloned().collect::<std::collections::BTreeSet<_>>()).unwrap_or_default();
+ let set = |names: &[&str]| names.iter().map(|n| n.to_string()).collect::<std::collections::BTreeSet<_>>();
+ let (mut s, _) = editing(ParamCheck::Off);
+ let r = run(&mut s, "sketch.offset", json!({"curves": ["l1", "l2", "l3", "l4"], "distance": 2}));
+ assert_eq!(keys(&r), set(&["constraints", "created", "curves", "instances", "param", "sides", "sketch"]), "{r}");
+ assert!(r["sketch"]["solved"].is_boolean() && r["sketch"]["dof"].is_number(), "{r}");
+ assert_eq!(keys(&r["sides"][0]), set(&["curves", "distance", "instance", "param"]), "{r}");
+ let (mut s, _) = editing(ParamCheck::Off);
+ let r = run(&mut s, "sketch.offset", json!({"curves": ["l1"], "distance": 2, "distance2": 1, "side": [0, 30]}));
+ assert!(r.get("association").is_none() && r["param2"].is_string(), "{r}");
+ let r = run(&mut s, "sketch.fillet", json!({"point": "l2.end", "radius": 2}));
+ assert_eq!(keys(&r), set(&["constraints", "created", "curves", "moved_to_virtual_corner", "param", "sketch", "virtual_corners"]), "{r}");
+ let side = OffsetSide { distance: 1.5, curves: vec!["l1".into()], param: None, instance: 1, association: Some("o1".into()) };
+ assert_eq!(
+ serde_json::to_value(&side).unwrap_or_default(),
+ json!({"distance": 1.5, "curves": ["l1"], "param": null, "instance": 1, "association": "o1"})
+ );
+ let trimmed = TrimOutcome::Trimmed { trimmed: "l1".into(), offset_released: Vec::new() }.released(vec!["l9".into()]);
+ assert_eq!(serde_json::to_value(&trimmed).unwrap_or_default(), json!({"trimmed": "l1", "offset_released": ["l9"]}));
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 80b7ede8ac..95944e26da 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -105,13 +105,9 @@ sketch.auto_constrain
sketch.auto_constrain_from_datum
sketch.auto_project
sketch.blend_curve
-sketch.break
sketch.break_link
sketch.centerline
sketch.chain
-sketch.chamfer.distance_angle
-sketch.chamfer.equal_distance
-sketch.chamfer.two_distance
sketch.circle.center
sketch.circle.three_point
sketch.circle.three_tangent
@@ -143,8 +139,6 @@ sketch.draw.dimensioned
sketch.edit_text
sketch.ellipse
sketch.export_dxf
-sketch.extend
-sketch.fillet
sketch.finish_auto_constrain
sketch.fit_curves_to_section
sketch.glyphs
@@ -159,15 +153,9 @@ sketch.isoparametric_curve
sketch.line
sketch.line.midpoint
sketch.line3d
-sketch.mirror
-sketch.move
sketch.move3d
sketch.move_point
-sketch.offset
-sketch.offset.break
sketch.options
-sketch.pattern.circular
-sketch.pattern.rectangular
sketch.point
sketch.point3d
sketch.polygon.circumscribed
@@ -180,7 +168,6 @@ sketch.rectangle.rounded
sketch.rectangle.three_point
sketch.rectangle.two_point
sketch.redefine
-sketch.scale
sketch.slot.arc_center
sketch.slot.arc_three_point
sketch.slot.center_point
@@ -195,8 +182,6 @@ sketch.spline3d
sketch.spun_profile
sketch.text
sketch.toggle_driven
-sketch.trim
-sketch.trim.path
solid.align
solid.chamfer
solid.coil