Skip to content

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

Agents and scripts: Inspect Document, Measure, Inspect Sketch, the command list and the material commands describe their exact parameters and reply (#12498) (#12591)

PeppaWutz7c9c1699de7f
diff --git a/crates/engine/src/cmd/inspect.rs b/crates/engine/src/cmd/inspect.rs
index 06516e8b5e..4685884eb3 100644
--- a/crates/engine/src/cmd/inspect.rs
+++ b/crates/engine/src/cmd/inspect.rs
@@ -12,8 +12,12 @@ use solidcraft_sketch::CurveKind;
use super::CommandSpec;
use crate::params::{bad, bool_, str_, string_list};
use crate::schema::inspect::{
- BodyFeaturesParams, BodyListParams, FaceCylinder, ModelBodyFeatures, ModelEdge, ModelEdges, ModelFace, ModelFaces, ModelThread, ModelThreads,
- ModelThreadsParams,
+ BodyFailure, BodyFeaturesParams, BodyFigures, BodyListParams, BodyMeasurement, BodyName, BodyNames, BodyOutcome, BoundingBox, CommandEntry,
+ CommandsParams, CurveShape, DocumentBody, DocumentBodyDetail, DocumentInspectParams, DocumentInspectResult, DocumentParam, DocumentSketch,
+ FaceCylinder, KernelCounts, ListedMaterial, MaterialAssignParams, MaterialAssignResult, MaterialListParams, MaterialListResult, MeasureParams,
+ MeasureResult, MeasureTotal, Measured, MeasuredBodies, MeasuredBody, ModelBodyFeatures, ModelEdge, ModelEdges, ModelFace, ModelFaces,
+ ModelThread, ModelThreads, ModelThreadsParams, SketchConstraint, SketchCurve, SketchInspectParams, SketchInspected, SketchPoint, SketchProfile,
+ SketchWire, TimelineEntry, WireArcInfo,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
@@ -21,6 +25,12 @@ use crate::{EngineError, Result, Session};
const BODY_LIST_CONTRACT: TypedContract<BodyListParams> = TypedContract::new();
const THREADS_CONTRACT: TypedContract<ModelThreadsParams> = TypedContract::new();
const BODY_FEATURES_CONTRACT: TypedContract<BodyFeaturesParams> = TypedContract::new();
+const MEASURE_CONTRACT: TypedContract<MeasureParams> = TypedContract::new();
+const DOCUMENT_INSPECT_CONTRACT: TypedContract<DocumentInspectParams> = TypedContract::new();
+const SKETCH_INSPECT_CONTRACT: TypedContract<SketchInspectParams> = TypedContract::new();
+const MATERIAL_ASSIGN_CONTRACT: TypedContract<MaterialAssignParams> = TypedContract::new();
+const MATERIAL_LIST_CONTRACT: TypedContract<MaterialListParams> = TypedContract::new();
+const COMMANDS_CONTRACT: TypedContract<CommandsParams> = TypedContract::new();
#[path = "appearance_chain.rs"]
mod appearance_chain;
@@ -35,19 +45,32 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("inspect.colored_components", "Component Colors", colored_components)
.at("SOLID", "INSPECT").icon("colored_components").noundo()
.params("enabled?: bool (omitted: toggle); temporary component colours, without changing appearances"),
- CommandSpec::new("inspect.measure", "Measure", measure)
+ CommandSpec::new("inspect.measure", "Measure", crate::checked!("inspect.measure", measure))
.at("SOLID", "INSPECT")
.icon("measure")
.key("I")
.noundo()
+ .contract(&MEASURE_CONTRACT)
+ .output(output_schema_for::<MeasureResult>)
.params("bodies?: [names] (default all); names_only?: bool (each world body's name and its definition's, nothing measured) → closed per body; volume_mm3, center_of_mass, density_g_cm3 and mass_g only for closed, consistently oriented bodies; area, bbox and counts for all; total.open_bodies_skipped counts bodies excluded from volume/mass totals; or items: [1-2 selections] (face/edge: type, body, point; index optional) → length/area/volume; diameter, radius, circumference or arc_length/angle_deg of circles, arcs and cylinders; slot sizes; min (distance_mm, from, to), max, center_distance (centre to centre, or from an axis) and angle"),
- CommandSpec::new("document.inspect", "Inspect Design", inspect).icon("inspect").noundo().params("measure?: bool (include body measurements); sketch_counts?: bool (each sketch also gives its plane and its number of points and constraints)"),
+ CommandSpec::new("document.inspect", "Inspect Design", crate::checked!("document.inspect", inspect))
+ .icon("inspect")
+ .noundo()
+ .contract(&DOCUMENT_INSPECT_CONTRACT)
+ .output(output_schema_for::<DocumentInspectResult>)
+ .params("measure?: bool (include body measurements); sketch_counts?: bool (each sketch also gives its plane and its number of points and constraints)"),
CommandSpec::new("document.revision", "Design Revision", revision).icon("inspect").noundo().params(
"→ document_id (this open design's id: kept while it stays open, another for each design started or opened), \
revision (moves whenever the design, what is hidden or a component's uncaptured position changes, \
never on a selection or a view; from one counter for the whole run, so it never repeats). Read-only",
),
- CommandSpec::new("sketch.inspect", "Inspect Sketch", sketch_inspect).at("SKETCH", "INSPECT").icon("inspect").noundo().params("sketch?: id|name (default active)"),
+ CommandSpec::new("sketch.inspect", "Inspect Sketch", crate::checked!("sketch.inspect", sketch_inspect))
+ .at("SKETCH", "INSPECT")
+ .icon("inspect")
+ .noundo()
+ .contract(&SKETCH_INSPECT_CONTRACT)
+ .output(output_schema_for::<SketchInspected>)
+ .params("sketch?: id|name (default active)"),
CommandSpec::new("model.edges", "List Edges", crate::checked!("model.edges", model_edges))
.icon("inspect")
.noundo()
@@ -79,9 +102,11 @@ pub static COMMANDS: &[CommandSpec] = &[
"body?: name (a placed copy's name means the body it shows; default every body) → bodies: [{body, features: [{id, name}]}], \
in timeline order the feature that created each body, every later one that changed it, and those of bodies consumed into it. Read-only",
),
- CommandSpec::new("material.assign", "Physical Material", physical_material)
+ CommandSpec::new("material.assign", "Physical Material", crate::checked!("material.assign", physical_material))
.at("SOLID", "MODIFY")
.icon("material")
+ .contract(&MATERIAL_ASSIGN_CONTRACT)
+ .output(output_schema_for::<MaterialAssignResult>)
.params("bodies: [names]; material: name (Steel, Aluminum, ABS Plastic, …, or one made with material.create; `material.list`)"),
CommandSpec::new("appearance.assign", "Appearance", crate::checked!("appearance.assign", appearance))
.at("SOLID", "MODIFY")
@@ -118,11 +143,18 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&LIST_CONTRACT)
.output(crate::schema::output_schema_for::<AppearanceListResult>)
.params("body?: name (or a placed copy's, `KB (K:2)`: the body it shows) → assigned appearances; with body, its resolved look and its faces' (face index, look)"),
- CommandSpec::new("material.list", "List Materials", material_list).icon("list")
+ CommandSpec::new("material.list", "List Materials", crate::checked!("material.list", material_list))
+ .icon("list")
.noundo()
.doc_only()
+ .contract(&MATERIAL_LIST_CONTRACT)
+ .output(output_schema_for::<MaterialListResult>)
.params("→ built-in and design-owned materials (user: true, look, optional physical_card/physical_validation/density_comparison). Read-only; candidate engineering records do not certify sources or supply a solver"),
- CommandSpec::new("engine.commands", "List Commands", commands).icon("list").noundo(),
+ CommandSpec::new("engine.commands", "List Commands", crate::checked!("engine.commands", commands))
+ .icon("list")
+ .noundo()
+ .contract(&COMMANDS_CONTRACT)
+ .output(output_schema_for::<Vec<CommandEntry>>),
CommandSpec::new("engine.describe", "Describe Command", crate::checked!("engine.describe", describe))
.icon("list")
.noundo()
@@ -142,7 +174,7 @@ pub(crate) fn encloses_volume(body: &solidcraft_kernel::Body) -> bool {
}
pub fn measure_json(b: &solidcraft_doc::ModelBody) -> Value {
- measure_sheet_json(b, None)
+ serde_json::to_value(measure_sheet(b, None)).unwrap_or_default()
}
pub(super) fn measure_body(
@@ -164,27 +196,53 @@ pub(super) fn measure_body(
Ok(measured)
}
-fn measure_sheet_json(b: &solidcraft_doc::ModelBody, definitions: Option<&solidcraft_doc::ModelState>) -> Value {
+fn measure_sheet(b: &solidcraft_doc::ModelBody, definitions: Option<&solidcraft_doc::ModelState>) -> BodyMeasurement {
+ let name = b.name.clone();
match measure_body(b, definitions) {
Ok(m) => {
let closed = encloses_volume(&b.body);
- json!({
- "name": b.name,
- "closed": closed,
- "volume_mm3": closed.then_some(m.volume),
- "area_mm2": m.area,
- "center_of_mass": closed.then_some(m.centroid),
- "bbox": {"min": m.bbox.min, "max": m.bbox.max},
- "faces": m.merged.faces,
- "edges": m.merged.edges,
- "vertices": m.merged.vertices,
- "face_types": m.merged.face_types,
- "kernel": {"faces": m.faces, "edges": m.edges, "vertices": m.vertices, "shells": m.shells},
- "measured_by": m.measured_by,
- "notes": m.notes,
- })
+ let outcome = BodyOutcome::Measured(BodyFigures {
+ closed,
+ volume_mm3: closed.then_some(m.volume),
+ area_mm2: m.area,
+ center_of_mass: closed.then(|| m.centroid.into()),
+ bbox: BoundingBox { min: m.bbox.min.into(), max: m.bbox.max.into() },
+ faces: count(m.merged.faces),
+ edges: count(m.merged.edges),
+ vertices: count(m.merged.vertices),
+ face_types: m.merged.face_types,
+ kernel: KernelCounts { faces: m.faces, edges: m.edges, vertices: m.vertices, shells: m.shells },
+ measured_by: m.measured_by.to_string(),
+ notes: m.notes,
+ });
+ BodyMeasurement { name, outcome }
+ }
+ Err(e) => measure_failed(name, e.to_string()),
+ }
+}
+
+fn measure_failed(name: String, error: String) -> BodyMeasurement {
+ BodyMeasurement { name, outcome: BodyOutcome::Failed(BodyFailure { error, faces: None, edges: None, vertices: None }) }
+}
+
+/// A topology count as the replies give it.
+fn count(n: usize) -> i64 {
+ i64::try_from(n).unwrap_or(0)
+}
+
+/// A reply as JSON: the commands build their replies from the types their output schemas
+/// describe, so the two can't drift apart.
+fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
+}
+
+impl BodyMeasurement {
+ /// The volume, when the body has one that is a number.
+ fn volume(&self) -> Option<f64> {
+ match &self.outcome {
+ BodyOutcome::Measured(f) => f.volume_mm3.filter(|v| v.is_finite()),
+ BodyOutcome::Failed(_) => None,
}
- Err(e) => json!({"name": b.name, "error": e.to_string()}),
}
}
@@ -201,138 +259,217 @@ fn measure(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, "unknown body name"));
}
if bool_(p, "names_only").unwrap_or(false) {
- let bodies: Vec<_> = selected.iter().map(|b| json!({"name": b.name, "definition": b.definition_name()})).collect();
- return Ok(json!({"body_count": bodies.len(), "bodies": bodies}));
+ let bodies: Vec<_> = selected.iter().map(|b| BodyName { name: b.name.clone(), definition: b.definition_name().to_string() }).collect();
+ let measured = Measured::Names(BodyNames { body_count: bodies.len(), bodies });
+ return typed_reply(cmd, MeasureResult { measured, param_warnings: Vec::new() });
}
// Each body is measured on its own: on all cores, in body order.
- let mut bodies: Vec<Value> = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_sheet_json(b, Some(&definitions)))
+ let measurements: Vec<BodyMeasurement> = solidcraft_kernel::map_on_threads(&selected, 16, |b| measure_sheet(b, Some(&definitions)))
.into_iter()
.zip(&selected)
- .map(|(m, b)| m.unwrap_or_else(|| json!({"name": b.name, "error": "measuring this body failed"})))
+ .map(|(m, b)| m.unwrap_or_else(|| measure_failed(b.name.clone(), "measuring this body failed".into())))
.collect();
// Mass from each body's material.
- for (b, body) in bodies.iter_mut().zip(selected) {
+ let mut bodies: Vec<MeasuredBody> = Vec::with_capacity(measurements.len());
+ for (measurement, body) in measurements.into_iter().zip(selected) {
let source = body.definition_name();
// Every body's material, measured or not: naming it takes no measuring.
- b["material"] = json!(s.doc.body_material(source));
- if let Some(v) = b["volume_mm3"].as_f64() {
+ let mut b = MeasuredBody { measurement, material: s.doc.body_material(source), density_g_cm3: None, mass_g: None, sheet_metal: None };
+ if let Some(v) = b.measurement.volume() {
let rho = s.doc.density(source);
- b["density_g_cm3"] = json!(rho);
- b["mass_g"] = json!(v * rho / 1000.0);
+ b.density_g_cm3 = Some(rho);
+ b.mass_g = Some(v * rho / 1000.0);
}
// Only Measure exposes sheet boundary counts; document.inspect keeps kernel counts.
if let Some(sheet) = definitions.sheets.iter().find(|sheet| sheet.body == source) {
let (df, de, dv) = sheet.round_hole_correction();
- for (key, delta) in [("faces", df), ("edges", de), ("vertices", dv)] {
- b[key] = json!(b["kernel"][key].as_i64().unwrap_or(0) + delta);
+ match &mut b.measurement.outcome {
+ BodyOutcome::Measured(f) => {
+ f.faces = count(f.kernel.faces) + df;
+ f.edges = count(f.kernel.edges) + de;
+ f.vertices = count(f.kernel.vertices) + dv;
+ }
+ BodyOutcome::Failed(x) => (x.faces, x.edges, x.vertices) = (Some(df), Some(de), Some(dv)),
}
- b["sheet_metal"] = json!(true);
+ b.sheet_metal = Some(true);
}
+ bodies.push(b);
}
- let skipped = bodies.iter().filter(|b| b["closed"] == false).count();
- let tv: f64 = bodies.iter().filter_map(|b| b["volume_mm3"].as_f64()).sum();
- let ta: f64 = bodies.iter().filter_map(|b| b["area_mm2"].as_f64()).sum();
- let tf: u64 = bodies.iter().filter_map(|b| b["faces"].as_u64()).sum();
- let te: u64 = bodies.iter().filter_map(|b| b["edges"].as_u64()).sum();
- let tvx: u64 = bodies.iter().filter_map(|b| b["vertices"].as_u64()).sum();
- let tm: f64 = bodies.iter().filter_map(|b| b["mass_g"].as_f64()).sum();
- Ok(
- json!({"body_count": bodies.len(), "bodies": bodies, "total": {"open_bodies_skipped": skipped, "volume_mm3": tv, "area_mm2": ta, "mass_g": tm, "faces": tf, "edges": te, "vertices": tvx}}),
+ fn figures(b: &MeasuredBody) -> Option<&BodyFigures> {
+ match &b.measurement.outcome {
+ BodyOutcome::Measured(f) => Some(f),
+ BodyOutcome::Failed(_) => None,
+ }
+ }
+ let counted = |n: Option<i64>| n.and_then(|n| u64::try_from(n).ok());
+ let faces = |b: &MeasuredBody| match &b.measurement.outcome {
+ BodyOutcome::Measured(f) => (counted(Some(f.faces)), counted(Some(f.edges)), counted(Some(f.vertices))),
+ BodyOutcome::Failed(x) => (counted(x.faces), counted(x.edges), counted(x.vertices)),
+ };
+ let total = MeasureTotal {
+ open_bodies_skipped: bodies.iter().filter(|b| figures(b).is_some_and(|f| !f.closed)).count(),
+ volume_mm3: bodies.iter().filter_map(|b| b.measurement.volume()).sum(),
+ area_mm2: bodies.iter().filter_map(|b| figures(b)).map(|f| f.area_mm2).filter(|a| a.is_finite()).sum(),
+ mass_g: bodies.iter().filter_map(|b| b.mass_g).filter(|m| m.is_finite()).sum(),
+ faces: bodies.iter().filter_map(|b| faces(b).0).sum(),
+ edges: bodies.iter().filter_map(|b| faces(b).1).sum(),
+ vertices: bodies.iter().filter_map(|b| faces(b).2).sum(),
+ };
+ typed_reply(
+ cmd,
+ MeasureResult { measured: Measured::Bodies(MeasuredBodies { body_count: bodies.len(), bodies, total }), param_warnings: Vec::new() },
)
}
+/// A 2D position as the replies give it.
+fn at2(p: solidcore_record::Vec2) -> [f64; 2] {
+ [p.x, p.y]
+}
+
/// Sketch `id`, placed where the placed model `world` has it (its component's placement).
-fn sketch_json(s: &Session, world: &solidcraft_doc::ModelState, id: u64) -> Option<Value> {
+fn sketch_json(s: &Session, world: &solidcraft_doc::ModelState, id: u64) -> Option<SketchInspected> {
let state = s.model.state();
let ss = state.sketch(id)?;
let plane = world.sketch(id).map(|w| w.plane).unwrap_or(ss.plane);
let sk = &ss.sketch;
- let curves: Vec<Value> = sk
+ let curves: Vec<SketchCurve> = sk
.curves
.iter()
.enumerate()
.map(|(i, c)| {
let det = ss.report.curve_determined.get(i).copied().unwrap_or(false);
let pid = |k: usize| sk.points.get(k).map(|p| p.id.clone()).unwrap_or_default();
- let mut v = match c.kind {
- CurveKind::Line { a, b } => json!({"id": c.id, "type": "line", "start": pid(a), "end": pid(b), "start_at": sk.point(a), "end_at": sk.point(b), "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
- CurveKind::Circle { c: cc, r } => json!({"id": c.id, "type": "circle", "center": pid(cc), "center_at": sk.point(cc), "radius": r, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
- CurveKind::Arc { c: cc, a, b } => json!({"id": c.id, "type": "arc", "center": pid(cc), "start": pid(a), "end": pid(b), "center_at": sk.point(cc), "start_at": sk.point(a), "end_at": sk.point(b), "radius": sk.radius(i), "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
- CurveKind::Ellipse { c: cc, m, r } => json!({"id": c.id, "type": "ellipse", "center": pid(cc), "major": pid(m), "center_at": sk.point(cc), "major_at": sk.point(m), "minor_radius": r, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
- CurveKind::Spline { ref pts, control, degree, periodic, ref nurbs } => {
- let mut v = json!({"id": c.id, "type": "spline", "points": pts.iter().map(|q| pid(*q)).collect::<Vec<_>>(), "points_at": pts.iter().map(|q| sk.point(*q)).collect::<Vec<_>>(), "control": control, "degree": degree, "periodic": periodic, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det});
+ let at = |k: usize| sk.point(k).map(at2);
+ let shape = match c.kind {
+ CurveKind::Line { a, b } => CurveShape::Line { start: pid(a), end: pid(b), start_at: at(a), end_at: at(b) },
+ CurveKind::Circle { c: cc, r } => CurveShape::Circle { center: pid(cc), center_at: at(cc), radius: r },
+ CurveKind::Arc { c: cc, a, b } => CurveShape::Arc {
+ center: pid(cc),
+ start: pid(a),
+ end: pid(b),
+ center_at: at(cc),
+ start_at: at(a),
+ end_at: at(b),
+ radius: sk.radius(i),
+ },
+ CurveKind::Ellipse { c: cc, m, r } => {
+ CurveShape::Ellipse { center: pid(cc), major: pid(m), center_at: at(cc), major_at: at(m), minor_radius: r }
+ }
+ CurveKind::Spline { ref pts, control, degree, periodic, ref nurbs } => CurveShape::Spline {
+ points: pts.iter().map(|q| pid(*q)).collect(),
+ points_at: pts.iter().map(|q| at(*q)).collect(),
+ control,
+ degree,
+ periodic,
// A control spline with its own knots (a projected free-form edge) says them.
- if let (Some(n), Some(o)) = (nurbs, v.as_object_mut()) {
- o.insert("knots".into(), json!(n.knots));
- if !n.weights.is_empty() {
- o.insert("weights".into(), json!(n.weights));
- }
- }
- v
+ knots: nurbs.as_ref().map(|n| n.knots.clone()),
+ weights: nurbs.as_ref().filter(|n| !n.weights.is_empty()).map(|n| n.weights.clone()),
+ },
+ CurveKind::Conic { a, b, apex, rho } => {
+ CurveShape::Conic { start: pid(a), end: pid(b), apex: pid(apex), start_at: at(a), end_at: at(b), apex_at: at(apex), rho }
}
- CurveKind::Conic { a, b, apex, rho } => json!({"id": c.id, "type": "conic", "start": pid(a), "end": pid(b), "apex": pid(apex), "start_at": sk.point(a), "end_at": sk.point(b), "apex_at": sk.point(apex), "rho": rho, "construction": c.construction, "fixed": sk.curve_locked(i), "fully_constrained": det}),
};
- if let (Some(l), Some(o)) = (&c.link, v.as_object_mut()) {
- o.insert("link".into(), json!(l));
+ SketchCurve {
+ id: c.id.clone(),
+ shape,
+ construction: c.construction,
+ fixed: sk.curve_locked(i),
+ fully_constrained: det,
+ link: c.link.clone(),
}
- v
})
.collect();
let locked = sk.locked_points();
- let points: Vec<Value> = sk
+ let points: Vec<SketchPoint> = sk
.points
.iter()
.enumerate()
- .map(|(i, p)| json!({"id": p.id, "at": p.pos, "world": plane.to_world(p.pos), "fixed": locked.get(i).copied().unwrap_or(false), "link": p.link, "fully_constrained": ss.report.point_determined.get(i).copied().unwrap_or(false)}))
+ .map(|(i, p)| SketchPoint {
+ id: p.id.clone(),
+ at: at2(p.pos),
+ world: plane.to_world(p.pos).into(),
+ fixed: locked.get(i).copied().unwrap_or(false),
+ link: p.link.clone(),
+ fully_constrained: ss.report.point_determined.get(i).copied().unwrap_or(false),
+ })
.collect();
- let constraints: Vec<Value> = sk
+ let constraints: Vec<SketchConstraint> = sk
.constraints
.iter()
.map(|c| {
- let mut v = serde_json::to_value(&c.kind).unwrap_or_default();
- if let Some(o) = v.as_object_mut() {
- o.insert("id".into(), json!(c.id));
- o.insert("name".into(), json!(c.kind.name()));
- if let Some(p) = &c.param {
- o.insert("param".into(), json!(p));
- o.insert("expression".into(), json!(s.doc.param(p).map(|x| x.expr.clone())));
- }
+ let mut kind = match serde_json::to_value(&c.kind) {
+ Ok(Value::Object(kind)) => kind,
+ _ => Default::default(),
+ };
+ // The constraint's own keys win over any of the kind's.
+ for key in ["id", "name", "param", "expression"] {
+ kind.remove(key);
+ }
+ SketchConstraint {
+ id: c.id.clone(),
+ name: c.kind.name().to_string(),
+ param: c.param.clone(),
+ expression: c.param.as_ref().map(|p| s.doc.param(p).map(|x| x.expr.clone())),
+ kind,
}
- v
})
.collect();
- let profiles: Vec<Value> = ss
+ let profiles: Vec<SketchProfile> = ss
.profiles
.iter()
.enumerate()
// A loop records one entry per piece it walks, and a conic or spline is walked as many
// short pieces: each loop names a curve once, in loop order.
- .map(|(i, p)| {
- let holes: Vec<Vec<String>> = p.hole_curves.iter().map(|h| solidcraft_sketch::distinct_curves(h)).collect();
- json!({"index": i, "area_mm2": p.area, "centroid_sketch": p.centroid, "curves": solidcraft_sketch::distinct_curves(&p.outer_curves), "holes": holes})
+ .map(|(i, p)| SketchProfile {
+ index: i,
+ area_mm2: p.area,
+ centroid_sketch: at2(p.centroid),
+ curves: solidcraft_sketch::distinct_curves(&p.outer_curves),
+ holes: p.hole_curves.iter().map(|h| solidcraft_sketch::distinct_curves(h)).collect(),
})
.collect();
- Some(json!({
- "id": id,
- "name": ss.name,
- "plane": ss.plane,
- "status": ss.report.status,
- "dof": ss.report.dof,
- "fully_constrained": ss.report.fully_constrained(),
- "failing": ss.report.failing,
- "curves": curves,
- "points": points,
- "constraints": constraints,
- "profiles": profiles,
- "links": sk.links,
- "wires": sk.wires.iter().map(|w| json!({"id": w.id, "points": w.pts.len(), "start": w.pts.first(), "end": w.pts.last(), "link": w.link, "arc": w.arc.map(|a| json!({"center": a.center, "radius": a.radius, "start": a.start, "end": a.end, "sweep_deg": solidcraft_sketch::arc_sweep(&a).to_degrees()}))})).collect::<Vec<_>>(),
- "visible": crate::view::sketch_shown(s, id),
- }))
+ let wires = sk
+ .wires
+ .iter()
+ .map(|w| SketchWire {
+ id: w.id.clone(),
+ points: w.pts.len(),
+ start: w.pts.first().map(|&p| p.into()),
+ end: w.pts.last().map(|&p| p.into()),
+ link: w.link.clone(),
+ arc: w.arc.map(|a| WireArcInfo {
+ center: a.center.into(),
+ radius: a.radius,
+ start: a.start.into(),
+ end: a.end.into(),
+ sweep_deg: solidcraft_sketch::arc_sweep(&a).to_degrees(),
+ }),
+ })
+ .collect();
+ Some(SketchInspected {
+ id,
+ name: ss.name.clone(),
+ plane: serde_json::to_value(ss.plane).unwrap_or_default(),
+ status: ss.report.status.into(),
+ dof: ss.report.dof,
+ fully_constrained: ss.report.fully_constrained(),
+ failing: ss.report.failing.clone(),
+ curves,
+ points,
+ constraints,
+ profiles,
+ links: serde_json::to_value(&sk.links).unwrap_or_default(),
+ wires,
+ visible: crate::view::sketch_shown(s, id),
+ param_warnings: Vec::new(),
+ })
}
fn sketch_inspect(s: &mut Session, p: &Value) -> Result<Value> {
let id = super::sketch_store::target(s, p, "sketch.inspect")?;
- sketch_json(s, &*s.world_state()?, id).ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into()))
+ let inspected = sketch_json(s, &*s.world_state()?, id)
+ .ok_or_else(|| EngineError::Other("that sketch is not evaluated (rolled back or not a sketch)".into()))?;
+ typed_reply("sketch.inspect", inspected)
}
/// Revisions of every design of this run (#6646).
@@ -391,24 +528,38 @@ fn revision(s: &mut Session, _p: &Value) -> Result<Value> {
fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.model.state();
let (vals, perr) = s.doc.param_values();
- let params: Vec<Value> = s
+ let params: Vec<DocumentParam> = s
.doc
.params
.iter()
- .map(|p| json!({"name": p.name, "expression": p.expr, "unit": p.unit, "value": vals.get(&p.name).map(|v| v.v), "model": p.model, "comment": p.comment, "error": perr.get(&p.name)}))
+ .map(|p| DocumentParam {
+ name: p.name.clone(),
+ expression: p.expr.clone(),
+ unit: p.unit.clone(),
+ value: vals.get(&p.name).map(|v| v.v),
+ model: p.model,
+ comment: p.comment.clone(),
+ error: perr.get(&p.name).cloned(),
+ })
.collect();
let marker = s.doc.marker.unwrap_or(s.doc.features.len());
- let timeline: Vec<Value> = s
+ let timeline: Vec<TimelineEntry> = s
.doc
.features
.iter()
.enumerate()
.map(|(i, f)| {
let r = s.model.result(f.id);
- json!({
- "id": f.id, "name": f.name, "type": f.kind.type_name(), "suppressed": f.suppressed, "rolled_back": i >= marker,
- "error": r.and_then(|r| r.error.clone()), "warning": r.and_then(|r| r.warning.clone()), "ms": r.map(|r| r.ms),
- })
+ TimelineEntry {
+ id: f.id,
+ name: f.name.clone(),
+ kind: f.kind.type_name().to_string(),
+ suppressed: f.suppressed,
+ rolled_back: i >= marker,
+ error: r.and_then(|r| r.error.clone()),
+ warning: r.and_then(|r| r.warning.clone()),
+ ms: r.map(|r| r.ms),
+ }
})
.collect();
let definitions = s.model.state();
@@ -416,46 +567,69 @@ fn inspect(s: &mut Session, p: &Value) -> Result<Value> {
let with_counts = bool_(p, "sketch_counts").unwrap_or(false);
// Each body is measured on its own: on all cores, in body order (as `inspect.measure`).
let mut measured =
- if with_measure { solidcraft_kernel::map_on_threads(&st.bodies, 16, |b| measure_sheet_json(b, Some(&definitions))) } else { Vec::new() }
+ if with_measure { solidcraft_kernel::map_on_threads(&st.bodies, 16, |b| measure_sheet(b, Some(&definitions))) } else { Vec::new() }
.into_iter();
- let bodies: Vec<Value> = st
+ let bodies: Vec<DocumentBody> = st
.bodies
.iter()
.map(|b| {
- let mut v = match measured.next() {
- Some(m) => m.unwrap_or_else(|| json!({"name": b.name, "error": "measuring this body failed"})),
- None => json!({"name": b.name, "feature": b.feature}),
- };
- if let Some(o) = v.as_object_mut() {
- o.insert("visible".into(), json!(s.body_visible(&b.name)));
- if s.body_removed_later(&b.name) {
- // Editing a sketch rolls the timeline back; this body is deleted further on.
- o.insert("removed_later".into(), json!(true));
+ let detail = match measured.next() {
+ Some(m) => {
+ DocumentBodyDetail::Measured(Box::new(m.unwrap_or_else(|| measure_failed(b.name.clone(), "measuring this body failed".into()))))
}
- }
- v
+ None => DocumentBodyDetail::Listed { name: b.name.clone(), feature: b.feature },
+ };
+ // Editing a sketch rolls the timeline back; a body deleted further on is `removed_later`.
+ DocumentBody { detail, visible: s.body_visible(&b.name), removed_later: s.body_removed_later(&b.name).then_some(true) }
})
.collect();
- let sketches: Vec<Value> = st
+ let sketches: Vec<DocumentSketch> = st
.sketches
.iter()
.map(|ss| {
- let mut v = json!({"id": ss.feature, "name": ss.name, "dof": ss.report.dof, "status": ss.report.status, "curves": ss.sketch.curves.len(), "profiles": ss.profiles.len(), "visible": crate::view::sketch_shown(s, ss.feature)});
+ let mut v = DocumentSketch {
+ id: ss.feature,
+ name: ss.name.clone(),
+ dof: ss.report.dof,
+ status: ss.report.status.into(),
+ curves: ss.sketch.curves.len(),
+ profiles: ss.profiles.len(),
+ visible: crate::view::sketch_shown(s, ss.feature),
+ plane: None,
+ points: None,
+ constraints: None,
+ };
// A summary that stands in for the sketch's contents (the compact MCP inspect_design).
- if with_counts && let Some(o) = v.as_object_mut() {
- o.insert("plane".into(), json!(ss.plane));
- o.insert("points".into(), json!(ss.sketch.points.len()));
- o.insert("constraints".into(), json!(ss.sketch.constraints.len()));
+ if with_counts {
+ v.plane = Some(serde_json::to_value(ss.plane).unwrap_or_default());
+ v.points = Some(ss.sketch.points.len());
+ v.constraints = Some(ss.sketch.constraints.len());
}
v
})
.collect();
- Ok(json!({
- "name": s.doc.name, "units": s.doc.units, "metadata": s.doc.metadata, "path": s.path, "dirty": s.is_dirty(), "revision": s.revision,
- "active_sketch": s.active_sketch, "marker": marker,
- "params": params, "timeline": timeline, "bodies": bodies, "sketches": sketches,
- "selection": s.selection, "undo": s.undo.len(), "redo": s.redo.len(), "hidden_origin": s.visibility.hidden_origin,
- }))
+ typed_reply(
+ "document.inspect",
+ DocumentInspectResult {
+ name: s.doc.name.clone(),
+ units: s.doc.units.clone(),
+ metadata: s.doc.metadata.0.clone(),
+ path: s.path.clone(),
+ dirty: s.is_dirty(),
+ revision: s.revision,
+ active_sketch: s.active_sketch,
+ marker,
+ params,
+ timeline,
+ bodies,
+ sketches,
+ selection: serde_json::to_value(&s.selection).unwrap_or_default(),
+ undo: s.undo.len(),
+ redo: s.redo.len(),
+ hidden_origin: s.visibility.hidden_origin.clone(),
+ param_warnings: Vec::new(),
+ },
+ )
}
fn body_of<'a>(st: &'a solidcraft_doc::ModelState, p: &Value, cmd: &str) -> Result<&'a solidcraft_doc::ModelBody> {
@@ -544,7 +718,8 @@ fn describe(_s: &mut Session, p: &Value) -> Result<Value> {
}
fn commands(s: &mut Session, _p: &Value) -> Result<Value> {
- Ok(Value::Array(crate::command_specs().iter().map(|c| serde_json::to_value(c.info(s)).unwrap_or_default()).collect()))
+ let list: Vec<CommandEntry> = crate::command_specs().iter().map(|c| c.info(s).into()).collect();
+ typed_reply("engine.commands", list)
}
fn model_threads(s: &mut Session, _p: &Value) -> Result<Value> {
@@ -568,7 +743,7 @@ fn physical_material(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut().materials.insert(b.clone(), canonical.clone());
}
}
- Ok(json!({"bodies": bodies, "material": canonical}))
+ typed_reply(cmd, MaterialAssignResult { bodies, material: canonical, param_warnings: Vec::new() })
}
/// A colour parameter: `"#rrggbb"` or `[r, g, b]` (0–255).
@@ -915,18 +1090,18 @@ fn appearance_list(s: &mut Session, p: &Value) -> Result<Value> {
}
fn material_list(s: &mut Session, _p: &Value) -> Result<Value> {
- let built_in = solidcraft_doc::MATERIALS.iter().map(|(n, d)| json!({"name": n, "density_g_cm3": d}));
+ let built_in = solidcraft_doc::MATERIALS.iter().map(|(n, d)| ListedMaterial::BuiltIn { name: n.to_string(), density_g_cm3: *d });
let user = s
.doc
.user_materials
.iter()
.map(|m| {
- let mut out = super::materials::material_json(m)?;
- out["appearance"] = json!(s.doc.material_look(&m.name).as_ref().map(look_json));
- Ok(out)
+ let mut out = super::materials::listed_material(m)?;
+ out.appearance = s.doc.material_look(&m.name).as_ref().map(LookReply::from);
+ Ok(ListedMaterial::Design(Box::new(out)))
})
.collect::<Result<Vec<_>>>()?;
- Ok(json!({"materials": built_in.chain(user).collect::<Vec<_>>()}))
+ typed_reply("material.list", MaterialListResult { materials: built_in.chain(user).collect(), param_warnings: Vec::new() })
}
fn colored_components(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/cmd/materials.rs b/crates/engine/src/cmd/materials.rs
index 2b68a02dc3..519e7ddee9 100644
--- a/crates/engine/src/cmd/materials.rs
+++ b/crates/engine/src/cmd/materials.rs
@@ -159,9 +159,9 @@ fn material_reply(cmd: &str, m: &UserMaterial) -> Result<MaterialReply> {
Ok(out)
}
-/// [`material_reply`] as JSON, for `material.list` (`cmd/inspect.rs`), which isn't converted yet.
-pub(super) fn material_json(m: &UserMaterial) -> Result<Value> {
- reply("material.list", material_reply("material.list", m)?)
+/// [`material_reply`] for `material.list` (`cmd/inspect.rs`).
+pub(super) fn listed_material(m: &UserMaterial) -> Result<MaterialReply> {
+ material_reply("material.list", m)
}
fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
diff --git a/crates/engine/src/cmd/measure_sel.rs b/crates/engine/src/cmd/measure_sel.rs
index 0f998ad7df..1eb805a10f 100644
--- a/crates/engine/src/cmd/measure_sel.rs
+++ b/crates/engine/src/cmd/measure_sel.rs
@@ -11,6 +11,7 @@ use solidcraft_geom::{Mesh, UnitVec3};
use super::measure_shape::{Shape, Slot, add_round, centre};
use crate::params::bad;
+use crate::schema::inspect::{MeasureKind, MeasureResult, Measured, MeasuredItems};
use crate::{Result, Sel, Session};
/// Geometry of a picked item, as points or triangles.
@@ -665,16 +666,20 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result<Value> {
.ok_or_else(|| bad(cmd, "an item can't be measured (pick vertices, edges, faces, bodies, sketch curves or profiles)"))?,
);
}
- let mut out = json!({"items": described.iter().map(|d| d.json.clone()).collect::<Vec<_>>()});
+ let mut out =
+ MeasuredItems { items: described.iter().map(|d| d.json.as_object().cloned().unwrap_or_default()).collect(), ..MeasuredItems::default() };
if let [one] = described.as_slice() {
- for k in ["diameter", "radius", "circumference", "angle_deg", "arc_length", "center", "slot"] {
- if let Some(v) = one.json.get(k) {
- out[k] = v.clone();
- }
- }
+ let copy = |k: &str| one.json.get(k).cloned();
+ out.diameter = copy("diameter");
+ out.radius = copy("radius");
+ out.circumference = copy("circumference");
+ out.angle_deg = copy("angle_deg");
+ out.arc_length = copy("arc_length");
+ out.center = copy("center");
+ out.slot = copy("slot");
if let Some(sl) = &one.slot {
- out["center_from"] = json!(sl.centres.0);
- out["center_to"] = json!(sl.centres.1);
+ out.center_from = Some(sl.centres.0.into());
+ out.center_to = Some(sl.centres.1.into());
}
}
if let [a, b] = described.as_slice() {
@@ -698,42 +703,45 @@ pub(crate) fn measure_items(s: &Session, items: &Value) -> Result<Value> {
max = Some(exact);
}
if let (Some((p, q)), Some(d)) = (near, min) {
- out["distance_mm"] = json!(d);
- out["from"] = json!(p);
- out["to"] = json!(q);
- out["delta"] = json!(q - p);
- out["min"] = json!(d);
+ out.set_closest(d, p, q);
}
let unbounded = |i: usize| matches!(sels.get(i), Some(Sel::Plane { .. } | Sel::Axis { .. }));
if let Some((d, p, q)) = exact_min(&a.shape, &b.shape, near.map(|(p, _)| p), (unbounded(0), unbounded(1)))
.filter(|(d, p, q)| d.is_finite() && p.is_finite() && q.is_finite())
{
- out["distance_mm"] = json!(d);
- out["from"] = json!(p);
- out["to"] = json!(q);
- out["delta"] = json!(q - p);
- out["min"] = json!(d);
+ out.set_closest(d, p, q);
}
if let (Some((p, q)), Some(d)) = (far, max) {
- out["max"] = json!(d);
- out["max_from"] = json!(p);
- out["max_to"] = json!(q);
- out["max_delta"] = json!(q - p);
+ out.max = Some(d);
+ out.max_from = Some(p.into());
+ out.max_to = Some(q.into());
+ out.max_delta = Some((q - p).into());
}
if let Some(c) = c {
- out["center_distance"] = json!(c.distance);
- out["center_from"] = json!(c.from);
- out["center_to"] = json!(c.to);
- out["center_delta"] = json!(c.to - c.from);
+ out.center_distance = Some(c.distance);
+ out.center_from = Some(c.from.into());
+ out.center_to = Some(c.to.into());
+ out.center_delta = Some((c.to - c.from).into());
}
- out["measure"] = json!(if c.is_some() { "center" } else { "min" });
+ out.measure = Some(if c.is_some() { MeasureKind::Center } else { MeasureKind::Min });
if let (Some(da), Some(db)) = (a.dir, b.dir) {
let both_faces = matches!(sels.as_slice(), [Sel::Face { .. }, Sel::Face { .. }]);
let cos = if both_faces { da.dot(db) } else { corner_cos(a.shape, b.shape).unwrap_or_else(|| da.dot(db).abs()) };
- out["angle_deg"] = json!(cos.clamp(-1.0, 1.0).acos().to_degrees());
+ out.angle_deg = Some(json!(cos.clamp(-1.0, 1.0).acos().to_degrees()));
}
}
- Ok(out)
+ serde_json::to_value(MeasureResult { measured: Measured::Items(Box::new(out)), param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()))
+}
+
+impl MeasuredItems {
+ /// The closest distance between two items and where it is: `distance_mm` and `min` are one.
+ fn set_closest(&mut self, d: f64, p: Vec3, q: Vec3) {
+ self.distance_mm = Some(d);
+ self.min = Some(d);
+ self.from = Some(p.into());
+ self.to = Some(q.into());
+ self.delta = Some((q - p).into());
+ }
}
/// Farthest pair of points between two pieces of geometry (on their samples and vertices).
diff --git a/crates/engine/src/schema/inspect.rs b/crates/engine/src/schema/inspect.rs
index 3472f792e2..aa7fcf450c 100644
--- a/crates/engine/src/schema/inspect.rs
+++ b/crates/engine/src/schema/inspect.rs
@@ -1,8 +1,22 @@
//! Contracts and result types for the commands in `cmd/inspect.rs`.
+//!
+//! The handlers read their parameters from the raw JSON, so each key here reads as its handler
+//! reads it and fails with the handler's message. Whether a body, a sketch or a material exists
+//! stays the handler's to check. A key the handler refuses when it is left out (`material.assign`'s
+//! `bodies` and `material`) 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 (#12498).
-use schemars::JsonSchema;
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
+use std::borrow::Cow;
+use std::collections::BTreeMap;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::{Map, Value, json};
+
+use super::check::{located, whole};
+use super::materials::MaterialReply;
+use crate::params;
/// Which command to describe.
#[derive(Debug, Deserialize, JsonSchema)]
@@ -278,6 +292,831 @@ impl From<&solidcraft_doc::ThreadInfo> for ModelThread {
}
}
+/// Adds `keys` to the schema's `required` list: for a key the type has optional so that the
+/// handler, not the check, refuses it when it's left out.
+fn require_keys(schema: &mut Schema, keys: &[&str]) {
+ let mut required = match schema.get("required") {
+ Some(Value::Array(required)) => required.clone(),
+ _ => Vec::new(),
+ };
+ for key in keys {
+ if !required.iter().any(|k| k == key) {
+ required.push((*key).into());
+ }
+ }
+ schema.insert("required".into(), Value::Array(required));
+}
+
+fn bodies_and_material_required(schema: &mut Schema) {
+ require_keys(schema, &["bodies", "material"]);
+}
+
+/// The message of a handler's parameter error, for a reader the contract shares.
+fn message(e: crate::EngineError) -> String {
+ match e {
+ crate::EngineError::BadParams { msg, .. } => msg,
+ other => other.to_string(),
+ }
+}
+
+/// `bodies`: a name or a list of names, read by `params::string_list` itself, with its messages
+/// (`null` is no names).
+fn body_names<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<String>>, D::Error> {
+ let v = Value::deserialize(d)?;
+ params::string_list("inspect", &json!({ "bodies": v }), "bodies").map(Some).map_err(|e| D::Error::custom(whole(message(e))))
+}
+
+fn body_names_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "maxItems": params::MAX_STRING_LIST}, {"type": "null"}]})
+}
+
+/// Read the design: its name, units, properties, parameters, timeline, bodies and sketches, the
+/// selection and the undo and redo depth. Read-only.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct DocumentInspectParams {
+ /// Measure each body too (volume, area, centre of mass, box, counts, as `inspect.measure`
+ /// does), in place of its feature. Default: false.
+ #[serde(default)]
+ pub measure: Option<bool>,
+ /// Give each sketch also its plane and its number of points and constraints. Default: false.
+ #[serde(default)]
+ pub sketch_counts: Option<bool>,
+}
+
+/// What `document.inspect` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DocumentInspectResult {
+ /// The design's name.
+ pub name: String,
+ /// Its length unit.
+ pub units: String,
+ /// Its metadata object as saved, other tools' keys included.
+ pub metadata: Map<String, Value>,
+ /// The file it is saved in; `null` when it has none.
+ pub path: Option<String>,
+ /// Whether it has changes that are not saved.
+ pub dirty: bool,
+ /// How many times the session's design changed.
+ pub revision: u64,
+ /// The sketch being edited, by feature id; `null` when none.
+ pub active_sketch: Option<u64>,
+ /// The timeline marker: features from this index on are rolled back.
+ pub marker: usize,
+ /// The design's parameters.
+ pub params: Vec<DocumentParam>,
+ /// Its features, in timeline order.
+ pub timeline: Vec<TimelineEntry>,
+ /// Its bodies.
+ pub bodies: Vec<DocumentBody>,
+ /// Its sketches.
+ pub sketches: Vec<DocumentSketch>,
+ /// What is selected, each as the selection commands take it.
+ #[schemars(with = "Vec<Map<String, Value>>")]
+ pub selection: Value,
+ /// How many undo steps there are.
+ pub undo: usize,
+ /// How many redo steps there are.
+ pub redo: usize,
+ /// The parts of the origin that are hidden, by name.
+ pub hidden_origin: 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>,
+}
+
+/// A parameter of the design.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DocumentParam {
+ pub name: String,
+ /// What it is defined as.
+ pub expression: String,
+ /// `mm`, `deg` or empty (no unit).
+ pub unit: String,
+ /// What the expression comes to; `null` when it doesn't evaluate.
+ pub value: Option<f64>,
+ /// Whether a dimension or feature made it, not the user.
+ pub model: bool,
+ pub comment: String,
+ /// Why the expression doesn't evaluate; `null` when it does.
+ pub error: Option<String>,
+}
+
+/// A feature of the timeline.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct TimelineEntry {
+ pub id: u64,
+ pub name: String,
+ /// The feature's kind, such as `Extrude`.
+ #[serde(rename = "type")]
+ pub kind: String,
+ pub suppressed: bool,
+ /// Whether the timeline marker has rolled it back.
+ pub rolled_back: bool,
+ /// Why it failed; `null` when it did not.
+ pub error: Option<String>,
+ pub warning: Option<String>,
+ /// How long it took to evaluate (ms); `null` when it has no result.
+ pub ms: Option<f64>,
+}
+
+/// A body of the design: measured with `measure`, else with the feature that made it.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DocumentBody {
+ #[serde(flatten)]
+ pub detail: DocumentBodyDetail,
+ /// Whether it is shown.
+ pub visible: bool,
+ /// Present, and true, when the timeline is rolled back and the body is deleted further on.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub removed_later: Option<bool>,
+}
+
+/// What a body entry says of the body itself.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum DocumentBodyDetail {
+ /// Without `measure`.
+ Listed {
+ name: String,
+ /// The feature that made it, by id.
+ feature: u64,
+ },
+ /// With `measure`.
+ Measured(Box<BodyMeasurement>),
+}
+
+/// One body measured: its name and the measurement or why there is none.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyMeasurement {
+ pub name: String,
+ #[serde(flatten)]
+ pub outcome: BodyOutcome,
+}
+
+/// A body's measurement.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum BodyOutcome {
+ Measured(BodyFigures),
+ Failed(BodyFailure),
+}
+
+/// The measurements of a body.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyFigures {
+ /// Whether it encloses a volume.
+ pub closed: bool,
+ /// Its volume (mm³); `null` unless it is closed.
+ pub volume_mm3: Option<f64>,
+ /// Its surface area (mm²).
+ pub area_mm2: f64,
+ /// Its centre of mass at uniform density; `null` unless it is closed.
+ pub center_of_mass: Option<[f64; 3]>,
+ pub bbox: BoundingBox,
+ /// Faces, with split pieces of one analytic surface counted once (a sheet metal body's in
+ /// `inspect.measure`: with its round holes counted as the design shows them).
+ pub faces: i64,
+ pub edges: i64,
+ pub vertices: i64,
+ /// The merged faces by kind of surface.
+ pub face_types: BTreeMap<String, usize>,
+ /// The kernel's own counts, which split closed curves and surfaces.
+ pub kernel: KernelCounts,
+ /// What volume, area and centre come from: `smlib` (exact) or `mesh` (a mesh body's own
+ /// triangles).
+ pub measured_by: String,
+ /// Anything the measurement says about itself.
+ pub notes: Vec<String>,
+}
+
+/// Why a body has no measurement.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyFailure {
+ pub error: String,
+ /// `inspect.measure` only, for a sheet metal body: its hole-corrected count, which has
+ /// nothing to correct.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub faces: Option<i64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub edges: Option<i64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub vertices: Option<i64>,
+}
+
+/// An axis-aligned box (mm).
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BoundingBox {
+ pub min: [f64; 3],
+ pub max: [f64; 3],
+}
+
+/// A body's topology counts as the kernel has them.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct KernelCounts {
+ pub faces: usize,
+ pub edges: usize,
+ pub vertices: usize,
+ pub shells: usize,
+}
+
+/// A sketch of the design, in short.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DocumentSketch {
+ /// Its feature id.
+ pub id: u64,
+ pub name: String,
+ /// Its remaining degrees of freedom (0: fully constrained).
+ pub dof: usize,
+ pub status: SketchStatus,
+ /// How many curves it has.
+ pub curves: usize,
+ /// How many profiles it closes.
+ pub profiles: usize,
+ /// Whether it is shown.
+ pub visible: bool,
+ /// With `sketch_counts`: where it lies.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<Map<String, Value>>")]
+ pub plane: Option<Value>,
+ /// With `sketch_counts`: how many points it has.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub points: Option<usize>,
+ /// With `sketch_counts`: how many constraints it has.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub constraints: Option<usize>,
+}
+
+/// Whether a sketch's constraints solved.
+#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum SketchStatus {
+ Solved,
+ Failed,
+}
+
+impl From<solidcraft_sketch::SolveStatus> for SketchStatus {
+ fn from(s: solidcraft_sketch::SolveStatus) -> Self {
+ match s {
+ solidcraft_sketch::SolveStatus::Solved => SketchStatus::Solved,
+ solidcraft_sketch::SolveStatus::Failed => SketchStatus::Failed,
+ }
+ }
+}
+
+/// How `inspect.measure` selects: bodies, or one or two picked items. With `items`, `bodies` and
+/// `names_only` are not read, so the check leaves them alone.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct MeasureKeys {
+ /// The bodies to measure, by name. Default: all. Not read with `items`.
+ #[serde(default, deserialize_with = "body_names", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "body_names_schema")]
+ pub bodies: Option<Vec<String>>,
+ /// Give each body's name and its definition's and measure nothing. Default: false. Not read
+ /// with `items`.
+ #[serde(default)]
+ pub names_only: Option<bool>,
+ /// One or two selections to measure, instead of bodies: a face or edge `{type, body, point}`
+ /// (`index` is optional), or a body, vertex, sketch curve or profile as `Sel` has it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "items_schema")]
+ pub items: Option<Vec<Value>>,
+}
+
+fn items_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "array", "items": {"type": "object"}, "minItems": 1, "maxItems": 1000})
+}
+
+/// `inspect.measure`'s parameters: [`MeasureKeys`], read as the handler reads them: with `items`
+/// given (even as `null`) only `items` is read; without it, `bodies` and `names_only`.
+#[derive(Debug)]
+pub struct MeasureParams(pub MeasureKeys);
+
+impl<'de> Deserialize<'de> for MeasureParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let value = Value::deserialize(d)?;
+ if let Some(items) = value.get("items") {
+ let list = items.as_array().ok_or_else(|| D::Error::custom(whole("`items` must be a list of selections")))?;
+ if list.is_empty() || list.len() > 1000 {
+ return Err(D::Error::custom(whole("measure one or two items")));
+ }
+ return Ok(MeasureParams(MeasureKeys { bodies: None, names_only: None, items: Some(list.clone()) }));
+ }
+ serde_path_to_error::deserialize(&value).map(MeasureParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for MeasureParams {
+ fn schema_name() -> Cow<'static, str> {
+ "MeasureParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ MeasureKeys::json_schema(generator)
+ }
+}
+
+/// What `inspect.measure` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MeasureResult {
+ #[serde(flatten)]
+ pub measured: Measured,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// The shapes of `inspect.measure`'s reply.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum Measured {
+ /// With `items`.
+ Items(Box<MeasuredItems>),
+ /// With `names_only`.
+ Names(BodyNames),
+ /// Bodies.
+ Bodies(MeasuredBodies),
+}
+
+/// Each world body's name and its definition's.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyNames {
+ pub body_count: usize,
+ pub bodies: Vec<BodyName>,
+}
+
+/// A body by its name and its definition's.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyName {
+ pub name: String,
+ pub definition: String,
+}
+
+/// The bodies measured, with their totals.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MeasuredBodies {
+ pub body_count: usize,
+ pub bodies: Vec<MeasuredBody>,
+ pub total: MeasureTotal,
+}
+
+/// A body measured, with its material and mass.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MeasuredBody {
+ #[serde(flatten)]
+ pub measurement: BodyMeasurement,
+ /// Its material's name.
+ pub material: String,
+ /// The material's density; only for a body with a volume.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub density_g_cm3: Option<f64>,
+ /// Its mass (g); only for a body with a volume.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mass_g: Option<f64>,
+ /// True for a sheet metal body, whose counts are its own, with round holes as the design
+ /// shows them.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sheet_metal: Option<bool>,
+}
+
+/// The sum over the bodies measured.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MeasureTotal {
+ /// How many bodies are left out of the volume and mass because they enclose none.
+ pub open_bodies_skipped: usize,
+ pub volume_mm3: f64,
+ pub area_mm2: f64,
+ pub mass_g: f64,
+ pub faces: u64,
+ pub edges: u64,
+ pub vertices: u64,
+}
+
+/// One or two picked items measured: each item, then what its shape gives (for one item) or what
+/// lies between the two.
+#[derive(Debug, Default, Serialize, JsonSchema)]
+pub struct MeasuredItems {
+ /// Each item described: its kind, what it is and its own figures.
+ pub items: Vec<Map<String, Value>>,
+ /// One item that is round: its diameter (mm).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<f64>")]
+ pub diameter: Option<Value>,
+ /// Its radius (mm).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<f64>")]
+ pub radius: Option<Value>,
+ /// A full circle's circumference (mm).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<f64>")]
+ pub circumference: Option<Value>,
+ /// An arc's sweep in degrees; two items: the angle between them.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<f64>")]
+ pub angle_deg: Option<Value>,
+ /// An arc's length (mm).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<f64>")]
+ pub arc_length: Option<Value>,
+ /// One round item's centre.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<[f64; 3]>")]
+ pub center: Option<Value>,
+ /// One slot: its `width`, `center_distance`, `overall_length` and the two `centers`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<Map<String, Value>>")]
+ pub slot: Option<Value>,
+ /// One slot: where its first end is centred; two items: the first item's centre.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub center_from: Option<[f64; 3]>,
+ /// One slot: its second end's centre; two items: the second's.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub center_to: Option<[f64; 3]>,
+ /// Two items: the closest distance between them (mm).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub distance_mm: Option<f64>,
+ /// Two items: where it starts on the first. A coordinate is `null` where it isn't a number: two planes that meet have no
+ /// such point to name (their distance is 0).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<[Option<f64>; 3]>")]
+ pub from: Option<[f64; 3]>,
+ /// Two items: where it ends on the second. A coordinate is `null` where it isn't a number: two planes that meet have no
+ /// such point to name (their distance is 0).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<[Option<f64>; 3]>")]
+ pub to: Option<[f64; 3]>,
+ /// Two items: `to` minus `from`. A coordinate is `null` where it isn't a number: two planes that meet have no
+ /// such point to name (their distance is 0).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<[Option<f64>; 3]>")]
+ pub delta: Option<[f64; 3]>,
+ /// Two items: the closest distance, as `distance_mm`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub min: Option<f64>,
+ /// Two items: the farthest distance (mm).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max_from: Option<[f64; 3]>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max_to: Option<[f64; 3]>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub max_delta: Option<[f64; 3]>,
+ /// Two items: the distance between their centres (or from an axis) (mm).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub center_distance: Option<f64>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub center_delta: Option<[f64; 3]>,
+ /// Two items: which distance is the one to read, `center` or `min`.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub measure: Option<MeasureKind>,
+}
+
+/// Which of two items' distances is the one to read.
+#[derive(Clone, Copy, Debug, Serialize, JsonSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum MeasureKind {
+ Center,
+ Min,
+}
+
+/// List every command: its id, label, place on the toolbar, icon, shortcut, parameter prose and
+/// whether it can run now.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CommandsParams {}
+
+/// One command of `engine.commands`' list.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct CommandEntry {
+ /// The command's id, such as `solid.extrude`.
+ pub id: String,
+ pub label: String,
+ /// The toolbar tab it is on; empty when it is on none.
+ pub tab: String,
+ /// The panel of that tab.
+ pub panel: String,
+ pub icon: String,
+ pub shortcut: Option<String>,
+ /// The parameter documentation, as prose (`engine.describe` has the schemas).
+ pub params: String,
+ /// Whether it can run in the session's state now.
+ pub enabled: bool,
+ /// Why it can't; `null` when it can.
+ pub disabled_reason: Option<String>,
+ /// For a command that is planned and not built yet: what is planned.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub planned: Option<String>,
+}
+
+impl From<crate::cmd::CommandInfo> for CommandEntry {
+ fn from(c: crate::cmd::CommandInfo) -> Self {
+ CommandEntry {
+ id: c.id.into(),
+ label: c.label.into(),
+ tab: c.tab.into(),
+ panel: c.panel.into(),
+ icon: c.icon.into(),
+ shortcut: c.shortcut.map(Into::into),
+ params: c.params.into(),
+ enabled: c.enabled,
+ disabled_reason: c.disabled_reason,
+ planned: c.planned.map(Into::into),
+ }
+ }
+}
+
+/// `material.list` takes no parameters.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct MaterialListParams {}
+
+/// What `material.list` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MaterialListResult {
+ /// The built-in materials, then the design's own.
+ pub materials: Vec<ListedMaterial>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// A material in the list.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum ListedMaterial {
+ /// A built-in material.
+ BuiltIn {
+ name: String,
+ /// Its density (g/cm³).
+ density_g_cm3: f64,
+ },
+ /// One this design defines, with `user` true, its look and its physical card when it has
+ /// one.
+ Design(Box<MaterialReply>),
+}
+
+/// A name as `material.assign` reads `material`: text, with the handler's message for anything
+/// else, `null` included.
+fn material_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(s) => Ok(Some(s)),
+ _ => Err(D::Error::custom(whole("`material` must be a material name"))),
+ }
+}
+
+/// Give bodies a physical material (a built-in one, or one made with `material.create`), which
+/// their mass and density come from. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = bodies_and_material_required)]
+pub struct MaterialAssignParams {
+ // Optional in the type and required in the schema (`bodies_and_material_required`).
+ /// The bodies, by name: one or a list, at least one, each an existing body.
+ #[serde(default, deserialize_with = "body_names", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "material_bodies_schema")]
+ pub bodies: Option<Vec<String>>,
+ /// The material's name (Steel, Aluminum, ABS Plastic, …, or one made with `material.create`;
+ /// `material.list` lists them). Letter case and spaces at either end don't matter.
+ #[serde(default, deserialize_with = "material_name", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "material_schema")]
+ pub material: Option<String>,
+}
+
+fn material_bodies_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"anyOf": [{"type": "string"}, {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": params::MAX_STRING_LIST}]})
+}
+
+fn material_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string"})
+}
+
+/// What `material.assign` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct MaterialAssignResult {
+ /// The bodies that got the material.
+ pub bodies: Vec<String>,
+ /// The material's name as the design has it.
+ pub material: 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>,
+}
+
+/// A sketch by its feature id (a number) or its name, as `sketch.inspect` reads `sketch`.
+#[derive(Clone, Debug, PartialEq)]
+pub enum SketchTarget {
+ Id(u64),
+ Name(String),
+}
+
+impl<'de> Deserialize<'de> for SketchTarget {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Number(n) => n.as_u64().map(SketchTarget::Id),
+ Value::String(s) => Some(SketchTarget::Name(s)),
+ _ => None,
+ }
+ .ok_or_else(|| D::Error::custom(whole("`sketch` must be an id or a name")))
+ }
+}
+
+impl JsonSchema for SketchTarget {
+ fn schema_name() -> Cow<'static, str> {
+ "SketchTarget".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A sketch's feature id (a number, never a name) or its name.",
+ "anyOf": [{"type": "integer", "minimum": 0, "maximum": u64::MAX}, {"type": "string"}]
+ })
+ }
+}
+
+/// Read a sketch: its curves, points, constraints, profiles, links and 3D curves, with what is
+/// determined and what is not. Read-only.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct SketchInspectParams {
+ /// The sketch. Default (also `null`): the one being edited.
+ #[serde(default)]
+ pub sketch: Option<SketchTarget>,
+}
+
+/// What `sketch.inspect` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchInspected {
+ /// The sketch's feature id.
+ pub id: u64,
+ pub name: String,
+ /// Where it lies, as saved.
+ #[schemars(with = "Map<String, Value>")]
+ pub plane: Value,
+ pub status: SketchStatus,
+ /// Its remaining degrees of freedom (0: fully constrained).
+ pub dof: usize,
+ pub fully_constrained: bool,
+ /// The constraints still violated after a failed solve.
+ pub failing: Vec<String>,
+ pub curves: Vec<SketchCurve>,
+ pub points: Vec<SketchPoint>,
+ pub constraints: Vec<SketchConstraint>,
+ pub profiles: Vec<SketchProfile>,
+ /// Links to geometry outside the sketch (projections, intersections, includes), as saved.
+ #[schemars(with = "Vec<Map<String, Value>>")]
+ pub links: Value,
+ /// Its 3D curves.
+ pub wires: Vec<SketchWire>,
+ /// Whether it is shown.
+ pub visible: 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>,
+}
+
+/// A curve of a sketch: its id, what it is and how it is held.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchCurve {
+ pub id: String,
+ #[serde(flatten)]
+ pub shape: CurveShape,
+ pub construction: bool,
+ /// Whether it is locked (fixed, or linked).
+ pub fixed: bool,
+ /// Whether everything that defines it is determined by constraints.
+ pub fully_constrained: bool,
+ /// For a linked curve: the link that owns it.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub link: Option<String>,
+}
+
+/// A curve's kind and its points, by id and (`_at`) by position `[x, y]` in the sketch's plane.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum CurveShape {
+ Line {
+ start: String,
+ end: String,
+ start_at: Option<[f64; 2]>,
+ end_at: Option<[f64; 2]>,
+ },
+ Circle {
+ center: String,
+ center_at: Option<[f64; 2]>,
+ radius: f64,
+ },
+ Arc {
+ center: String,
+ start: String,
+ end: String,
+ center_at: Option<[f64; 2]>,
+ start_at: Option<[f64; 2]>,
+ end_at: Option<[f64; 2]>,
+ radius: Option<f64>,
+ },
+ Ellipse {
+ center: String,
+ /// The end of the major axis.
+ major: String,
+ center_at: Option<[f64; 2]>,
+ major_at: Option<[f64; 2]>,
+ minor_radius: f64,
+ },
+ Spline {
+ points: Vec<String>,
+ points_at: Vec<Option<[f64; 2]>>,
+ /// Whether `points` are control points of a B-spline, not fit points.
+ control: bool,
+ degree: u8,
+ periodic: bool,
+ /// A control spline with its own knots (a projected free-form edge).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ knots: Option<Vec<f64>>,
+ /// Its weights, when it has any.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ weights: Option<Vec<f64>>,
+ },
+ Conic {
+ start: String,
+ end: String,
+ apex: String,
+ start_at: Option<[f64; 2]>,
+ end_at: Option<[f64; 2]>,
+ apex_at: Option<[f64; 2]>,
+ rho: f64,
+ },
+}
+
+/// A point of a sketch.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchPoint {
+ pub id: String,
+ /// Its position `[x, y]` in the sketch's plane (mm).
+ pub at: [f64; 2],
+ /// Where that is in the design (mm).
+ pub world: [f64; 3],
+ /// Whether it is locked (fixed, or linked).
+ pub fixed: bool,
+ /// For a linked point: the link that owns it; `null` otherwise.
+ pub link: Option<String>,
+ pub fully_constrained: bool,
+}
+
+/// A constraint or dimension: its id, its kind's name and the kind's own fields (`type`, then
+/// the points and curves it ties, a value…), as saved.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchConstraint {
+ pub id: String,
+ /// The kind in short, such as `Horizontal`.
+ pub name: String,
+ /// For a dimension: the parameter that drives it.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub param: Option<String>,
+ /// With `param`: the parameter's expression; `null` when the design has no such parameter.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Option<String>")]
+ pub expression: Option<Option<String>>,
+ #[serde(flatten)]
+ pub kind: Map<String, Value>,
+}
+
+/// A region the sketch closes.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchProfile {
+ pub index: usize,
+ pub area_mm2: f64,
+ /// Its centroid `[x, y]` in the sketch's plane.
+ pub centroid_sketch: [f64; 2],
+ /// The curves of its outer loop, each once, in loop order.
+ pub curves: Vec<String>,
+ /// The curves of each hole's loop.
+ pub holes: Vec<Vec<String>>,
+}
+
+/// A 3D curve a sketch carries.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct SketchWire {
+ pub id: String,
+ /// How many points its polyline has.
+ pub points: usize,
+ pub start: Option<[f64; 3]>,
+ pub end: Option<[f64; 3]>,
+ /// For a linked curve: the link that owns it; `null` otherwise.
+ pub link: Option<String>,
+ /// For an exact circular arc: its geometry; `null` otherwise.
+ pub arc: Option<WireArcInfo>,
+}
+
+/// An exact circular arc of a 3D curve.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct WireArcInfo {
+ pub center: [f64; 3],
+ pub radius: f64,
+ pub start: [f64; 3],
+ pub end: [f64; 3],
+ /// Its sweep (degrees).
+ pub sweep_deg: f64,
+}
+
#[cfg(test)]
#[path = "inspect_tests.rs"]
mod tests;
diff --git a/crates/engine/src/schema/inspect_tests.rs b/crates/engine/src/schema/inspect_tests.rs
index ea47e36cb3..a15cd85f9f 100644
--- a/crates/engine/src/schema/inspect_tests.rs
+++ b/crates/engine/src/schema/inspect_tests.rs
@@ -1,6 +1,10 @@
use serde_json::{Value, json};
-use super::{BodyFeaturesParams, BodyListParams, DescribeParams, ModelBodyFeatures, ModelEdges, ModelFaces, ModelThreads, ModelThreadsParams};
+use super::{
+ BodyFeaturesParams, BodyListParams, CommandEntry, CommandsParams, DescribeParams, DocumentInspectParams, DocumentInspectResult,
+ MaterialAssignParams, MaterialAssignResult, MaterialListParams, MaterialListResult, MeasureParams, MeasureResult, ModelBodyFeatures, ModelEdges,
+ ModelFaces, ModelThreads, ModelThreadsParams, SketchInspectParams, SketchInspected,
+};
use crate::Session;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
@@ -90,6 +94,419 @@ fn describe_returns_both_schemas() {
assert!(e.as_deref().is_some_and(|e| e.contains("did you mean `solid.extrude`")), "{e:?}");
}
+#[test]
+fn inspect_schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<DocumentInspectParams>(), &["measure", "sketch_counts"]);
+ assert_keys(input_schema_for::<MeasureParams>(), &["bodies", "items", "names_only"]);
+ assert_keys(input_schema_for::<CommandsParams>(), &[]);
+ assert_keys(input_schema_for::<MaterialListParams>(), &[]);
+ assert_keys(input_schema_for::<MaterialAssignParams>(), &["bodies", "material"]);
+ assert_keys(input_schema_for::<SketchInspectParams>(), &["sketch"]);
+}
+
+#[test]
+fn strict_keeps_todays_errors_of_the_inspect_commands() {
+ assert_strict_keeps_todays_errors(&[
+ ("material.assign", json!({})),
+ ("material.assign", json!({"bodies": ["A"]})),
+ ("material.assign", json!({"bodies": ["A"], "material": 4})),
+ ("material.assign", json!({"bodies": ["A"], "material": null})),
+ ("material.assign", json!({"bodies": ["A"], "material": ["Steel"]})),
+ ("material.assign", json!({"bodies": 5, "material": "Steel"})),
+ ("material.assign", json!({"bodies": [5], "material": "Steel"})),
+ ("material.assign", json!({"bodies": [], "material": "Steel"})),
+ ("material.assign", json!({"bodies": null, "material": "Steel"})),
+ ("material.assign", json!({"material": "Steel"})),
+ ("material.assign", json!({"bodies": ["Nope"], "material": "Steel"})),
+ ("material.assign", json!({"bodies": ["Nope"], "material": "Unobtainium"})),
+ ("inspect.measure", json!({"bodies": 5})),
+ ("inspect.measure", json!({"bodies": [5]})),
+ ("inspect.measure", json!({"bodies": ["Nope"]})),
+ ("inspect.measure", json!({"items": null})),
+ ("inspect.measure", json!({"items": "x"})),
+ ("inspect.measure", json!({"items": {}})),
+ ("inspect.measure", json!({"items": []})),
+ ("inspect.measure", json!({"items": "x", "bodies": 5})),
+ ("inspect.measure", json!({"items": [1], "bodies": 5, "names_only": "yes"})),
+ ("inspect.measure", json!({"items": [{"type": "body", "name": "Nope"}]})),
+ ("sketch.inspect", json!({"sketch": true})),
+ ("sketch.inspect", json!({"sketch": -1})),
+ ("sketch.inspect", json!({"sketch": 1.5})),
+ ("sketch.inspect", json!({"sketch": [1]})),
+ ("sketch.inspect", json!({"sketch": {}})),
+ ("sketch.inspect", json!({"sketch": "Nope"})),
+ ("sketch.inspect", json!({"sketch": 99999})),
+ ]);
+}
+
+/// Each type reads a key as its handler does: with `items` only `items` is read, without it
+/// `bodies` and `names_only`; `material.assign` leaves a missing or empty `bodies` and a missing
+/// `material` to the handler's own message; `sketch` is an id, a name or `null`.
+#[test]
+fn the_types_read_each_key_as_the_handler_does() {
+ let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();
+ let none = Vec::<String>::new();
+ // inspect.measure: the keys read depend on the form.
+ let pick = json!([{"type": "face", "body": "A", "point": [1, 2, 3]}]);
+ assert_eq!(issues("inspect.measure", json!({})), none);
+ assert_eq!(issues("inspect.measure", json!({"bodies": ["A"], "names_only": true})), none);
+ assert_eq!(issues("inspect.measure", json!({"bodies": null, "names_only": null})), none);
+ assert_eq!(issues("inspect.measure", json!({"items": pick})), none);
+ assert_eq!(issues("inspect.measure", json!({"items": pick, "bodies": 5, "names_only": "yes"})), none);
+ assert_eq!(issues("inspect.measure", json!({"bodies": 5})), ["`bodies` must be a list of names; it is 5"]);
+ assert_eq!(issues("inspect.measure", json!({"bodies": ["A", 7]})), ["`bodies` must list names; the entry 2 is 7"]);
+ assert_eq!(issues("inspect.measure", json!({"names_only": "yes"})), ["`names_only` must be true or false"]);
+ assert_eq!(issues("inspect.measure", json!({"items": null})), ["`items` must be a list of selections"]);
+ assert_eq!(issues("inspect.measure", json!({"items": "x", "bodies": 5})), ["`items` must be a list of selections"]);
+ assert_eq!(issues("inspect.measure", json!({"items": []})), ["measure one or two items"]);
+ assert_eq!(issues("inspect.measure", json!({"items": vec![json!({}); 1001]})), ["measure one or two items"]);
+ // material.assign.
+ assert_eq!(issues("material.assign", json!({"bodies": ["A"], "material": "Steel"})), none);
+ assert_eq!(issues("material.assign", json!({"bodies": "A", "material": " steel "})), none);
+ assert_eq!(issues("material.assign", json!({"material": "Steel"})), none);
+ assert_eq!(issues("material.assign", json!({"bodies": [], "material": "Steel"})), none);
+ assert_eq!(issues("material.assign", json!({"bodies": null})), none);
+ assert_eq!(issues("material.assign", json!({"bodies": 5, "material": "Steel"})), ["`bodies` must be a list of names; it is 5"]);
+ assert_eq!(issues("material.assign", json!({"bodies": ["A"], "material": 4})), ["`material` must be a material name"]);
+ assert_eq!(issues("material.assign", json!({"bodies": ["A"], "material": null})), ["`material` must be a material name"]);
+ // sketch.inspect.
+ for ok in [json!({}), json!({"sketch": null}), json!({"sketch": 3}), json!({"sketch": "Base"}), json!({"sketch": "7"})] {
+ assert_eq!(issues("sketch.inspect", ok.clone()), none, "{ok}");
+ }
+ for bad in [json!(true), json!(-1), json!(1.5), json!([1]), json!({"id": 1})] {
+ assert_eq!(issues("sketch.inspect", json!({ "sketch": bad.clone() })), ["`sketch` must be an id or a name"], "{bad}");
+ }
+ // document.inspect's flags are plain booleans, `null` is left out.
+ assert_eq!(issues("document.inspect", json!({"measure": true, "sketch_counts": null})), none);
+ assert_eq!(issues("document.inspect", json!({"measure": "yes"})), ["`measure` must be true or false"]);
+ // Neither list command takes a key.
+ assert_eq!(issues("engine.commands", json!({"x": 1})), ["unknown key `x`"]);
+ assert_eq!(issues("material.list", json!({"x": 1})), ["unknown key `x`"]);
+}
+
+/// The schemas say what the handlers need: `material.assign` can't do without `bodies` and
+/// `material`, though its type leaves them to the handler's message; `inspect.measure` takes
+/// bodies or items.
+#[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::<MaterialAssignParams>(),
+ &[
+ (json!({"bodies": ["A"], "material": "Steel"}), true),
+ (json!({"bodies": "A", "material": "Steel"}), true),
+ (json!({"material": "Steel"}), false),
+ (json!({"bodies": ["A"]}), false),
+ (json!({"bodies": [], "material": "Steel"}), false),
+ (json!({"bodies": ["A"], "material": 4}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<MeasureParams>(),
+ &[
+ (json!({}), true),
+ (json!({"bodies": ["A"], "names_only": true}), true),
+ (json!({"bodies": "A"}), true),
+ (json!({"bodies": null}), true),
+ (json!({"items": [{"type": "body", "name": "A"}]}), true),
+ (json!({"items": []}), false),
+ (json!({"items": "x"}), false),
+ (json!({"bodies": 5}), false),
+ (json!({"names_only": "yes"}), false),
+ ],
+ );
+ takes(
+ input_schema_for::<SketchInspectParams>(),
+ &[
+ (json!({}), true),
+ (json!({"sketch": 3}), true),
+ (json!({"sketch": "Base"}), true),
+ (json!({"sketch": null}), true),
+ (json!({"sketch": -1}), false),
+ (json!({"sketch": true}), false),
+ ],
+ );
+ takes(input_schema_for::<DocumentInspectParams>(), &[(json!({"measure": true, "sketch_counts": false}), true), (json!({"measure": 1}), false)]);
+ takes(input_schema_for::<CommandsParams>(), &[(json!({}), true), (json!({"x": 1}), false)]);
+}
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+/// A reply matches its output schema and, in Warn, carries `param_warnings` only when told to.
+fn matches<T: schemars::JsonSchema>(id: &str, reply: &Value, warned: bool) {
+ let schema = output_schema_for::<T>();
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");
+ assert_eq!(reply.get("param_warnings").is_some(), warned, "{id}: {reply}");
+}
+
+/// A design with a box, a cylinder, a sheet metal body, a sketch of every curve kind with a
+/// dimension, and a sketch that projects a face: returns the first sketch's feature id.
+fn design(s: &mut Session) -> u64 {
+ run(s, "solid.box", json!({"length": 10, "width": 20, "height": 30, "body_name": "Block"}));
+ run(s, "solid.cylinder", json!({"radius": 4, "height": 20, "base": [40, 0, 0], "body_name": "Shaft"}));
+ run(s, "material.create", json!({"name": "Alloy", "density_g_cm3": 2.5, "color": "#ff0000"}));
+ run(
+ s,
+ "material.create",
+ json!({"name": "Painted", "density_g_cm3": 1.5, "color": "#00ff00", "pbr": {"metallic": 0.5, "roughness": 0.5, "dielectric_ior": 1.5}}),
+ );
+ run(s, "sheet.manage_rules", json!({"name": "R1", "thickness": "1 mm", "bend_radius": "1 mm", "active": true}));
+ run(s, "sketch.create", json!({"plane": "XY", "name": "Base"}));
+ run(s, "sketch.rectangle.two_point", json!({"p0": [60, 0], "p1": [100, 30]}));
+ run(s, "sketch.finish", json!({}));
+ run(s, "sheet.flange", json!({"sketch": "Base"}));
+ run(s, "sketch.create", json!({"plane": "XZ", "name": "Shapes"}));
+ run(s, "sketch.line", json!({"points": [[0, 0], [40, 0], [40, 20]]}));
+ run(s, "sketch.circle.center", json!({"center": [10, 10], "radius": 3}));
+ run(s, "sketch.circle.center", json!({"center": [10, 10], "radius": 1}));
+ run(s, "sketch.arc.three_point", json!({"start": [50, 0], "end": [60, 10], "through": [58, 3]}));
+ run(s, "sketch.ellipse", json!({"center": [-30, 0], "major": [-20, 0], "minor_radius": 5}));
+ run(s, "sketch.spline.fit_point", json!({"points": [[0, 40], [10, 50], [20, 40], [30, 50]]}));
+ run(s, "sketch.spline.control_point", json!({"points": [[0, 60], [10, 70], [20, 60], [30, 70]]}));
+ run(s, "sketch.conic", json!({"start": [0, 80], "end": [30, 80], "apex": [15, 100], "rho": 0.4}));
+ run(s, "sketch.dimension", json!({"entities": ["c1"]}));
+ run(s, "sketch.dimension", json!({"entities": ["l1"], "value": 40}));
+ run(s, "sketch.construction", json!({"curves": ["l2"]}));
+ let id = run(s, "sketch.inspect", json!({}))["id"].as_u64().unwrap_or_default();
+ run(s, "sketch.finish", json!({}));
+ run(s, "sketch.create", json!({"plane": {"origin": [0, 0, 30], "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "name": "Top"}));
+ run(s, "sketch.project", json!({"refs": [{"face": [5, 10, 30], "body": "Block"}]}));
+ run(s, "sketch.finish", json!({}));
+ id
+}
+
+/// Real calls of `document.inspect` in Warn, each form: the replies match the output schema
+/// without `param_warnings`, and say what the design has.
+#[test]
+fn document_inspect_replies_match_its_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let shapes = design(&mut s);
+ run(&mut s, "sketch.edit", json!({"sketch": shapes}));
+ for p in [
+ json!({}),
+ json!({"measure": true}),
+ json!({"sketch_counts": true}),
+ json!({"measure": true, "sketch_counts": true}),
+ json!({"measure": false, "sketch_counts": null}),
+ ] {
+ let r = run(&mut s, "document.inspect", p.clone());
+ matches::<DocumentInspectResult>("document.inspect", &r, false);
+ assert_eq!(r["active_sketch"], json!(shapes), "{r}");
+ assert_eq!(r["bodies"].as_array().map(Vec::len), Some(3), "{p}: {r}");
+ assert_eq!(r["bodies"][0].get("area_mm2").is_some(), p["measure"] == true, "{p}: {r}");
+ assert_eq!(r["bodies"][0].get("feature").is_some(), p["measure"] != true, "{p}: {r}");
+ assert_eq!(r["sketches"][0].get("plane").is_some(), p["sketch_counts"] == true, "{p}: {r}");
+ }
+ let r = run(&mut s, "document.inspect", json!({"measure": true}));
+ assert!(r["params"].as_array().is_some_and(|p| p.iter().any(|x| x["name"].is_string() && x["model"] == true)), "{r}");
+ assert!(r["timeline"].as_array().is_some_and(|t| t.iter().any(|x| x["type"].is_string() && x["ms"].is_number())), "{r}");
+ run(&mut s, "browser.visibility", json!({"items": ["Shaft"], "visible": false}));
+ let r = run(&mut s, "document.inspect", json!({}));
+ matches::<DocumentInspectResult>("document.inspect", &r, false);
+ assert_eq!(r["bodies"][1]["visible"], false, "{r}");
+ // A body that a rolled-back later feature deletes says so.
+ run(&mut s, "sketch.finish", json!({}));
+ run(&mut s, "solid.remove", json!({"bodies": ["Shaft"]}));
+ run(&mut s, "timeline.roll_to", json!({"feature": "Shapes"}));
+ run(&mut s, "sketch.edit", json!({"sketch": shapes}));
+ let r = run(&mut s, "document.inspect", json!({}));
+ matches::<DocumentInspectResult>("document.inspect", &r, false);
+ assert!(r["bodies"].as_array().is_some_and(|b| b.iter().any(|b| b["removed_later"] == true)), "{r}");
+}
+
+/// `inspect.measure` in each form: bodies (with sheet metal and a material), names only, one
+/// item and two, in Warn without warnings. Everything it ignores with `items` is ignored.
+#[test]
+fn measure_replies_match_its_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let shapes = design(&mut s);
+ run(&mut s, "material.assign", json!({"bodies": ["Block"], "material": "Alloy"}));
+ let id = "inspect.measure";
+ let all = run(&mut s, id, json!({}));
+ matches::<MeasureResult>(id, &all, false);
+ assert_eq!(all["body_count"], 3, "{all}");
+ assert_eq!(all["bodies"][0]["material"], "Alloy", "{all}");
+ assert!((all["bodies"][0]["mass_g"].as_f64().unwrap_or_default() - 15.0).abs() < 1e-6, "{all}");
+ assert!(all["bodies"].as_array().is_some_and(|b| b.iter().any(|b| b["sheet_metal"] == true)), "{all}");
+ assert_eq!(all["total"]["open_bodies_skipped"], 0, "{all}");
+ for p in [json!({"bodies": ["Block"]}), json!({"bodies": "Shaft", "names_only": false}), json!({"bodies": null})] {
+ matches::<MeasureResult>(id, &run(&mut s, id, p), false);
+ }
+ let names = run(&mut s, id, json!({"names_only": true}));
+ assert_eq!(names["bodies"][0], json!({"name": "Block", "definition": "Block"}), "{names}");
+ matches::<MeasureResult>(id, &names, false);
+ matches::<MeasureResult>(id, &run(&mut s, id, json!({"bodies": ["Block"], "names_only": true})), false);
+
+ let face = |body: &str, p: [i32; 3]| json!({"type": "face", "body": body, "point": p});
+ let curve = |c: &str| json!({"type": "sketch_curve", "id": c, "sketch": shapes});
+ for items in [
+ json!([face("Block", [5, 10, 30])]),
+ json!([face("Shaft", [44, 0, 10])]),
+ json!([face("Block", [5, 10, 30]), face("Block", [5, 10, 0])]),
+ json!([face("Block", [5, 10, 30]), face("Block", [10, 10, 15])]),
+ json!([face("Shaft", [44, 0, 10]), face("Block", [5, 10, 30])]),
+ json!([{"type": "edge", "body": "Block", "point": [5, 0, 30]}, {"type": "edge", "body": "Block", "point": [5, 20, 30]}]),
+ json!([{"type": "body", "name": "Block"}]),
+ json!([{"type": "body", "name": "Block"}, {"type": "body", "name": "Shaft"}]),
+ json!([{"type": "vertex", "body": "Block", "point": [0, 0, 0]}, {"type": "vertex", "body": "Block", "point": [10, 20, 30]}]),
+ json!([curve("c1")]),
+ json!([curve("a1")]),
+ json!([curve("l1")]),
+ json!([curve("c1"), curve("c2")]),
+ json!([curve("l1"), curve("l2")]),
+ json!([curve("c1"), curve("l1")]),
+ json!([curve("a1"), face("Block", [5, 10, 30])]),
+ ] {
+ let r = run(&mut s, id, json!({ "items": items }));
+ matches::<MeasureResult>(id, &r, false);
+ assert!(r["items"].as_array().is_some_and(|i| i.len() == items.as_array().map_or(0, Vec::len)), "{r}");
+ }
+ let one = run(&mut s, id, json!({"items": [curve("c1")]}));
+ assert!(one["diameter"] == 6.0 && one["circumference"].is_number() && one["center"].is_array(), "{one}");
+ let arc = run(&mut s, id, json!({"items": [curve("a1")]}));
+ assert!(arc["arc_length"].is_number() && arc["angle_deg"].is_number() && arc.get("circumference").is_none(), "{arc}");
+ let two = run(&mut s, id, json!({"items": [face("Block", [5, 10, 30]), face("Block", [5, 10, 0])]}));
+ assert!(two["distance_mm"] == 30.0 && two["min"] == 30.0 && two["measure"] == "min" && two["angle_deg"].is_number(), "{two}");
+ let pair = run(&mut s, id, json!({"items": [curve("c1"), curve("c2")]}));
+ assert!(pair["measure"] == "center" && pair["center_distance"].is_number(), "{pair}");
+ // With `items`, `bodies` and `names_only` are not read at all.
+ let r = run(&mut s, id, json!({"items": [face("Block", [5, 10, 30])], "bodies": 7, "names_only": "yes"}));
+ matches::<MeasureResult>(id, &r, false);
+}
+
+/// `sketch.inspect` of every curve kind, a dimension and a projected link, by id, by name and as
+/// the sketch being edited, in Warn without warnings.
+#[test]
+fn sketch_inspect_replies_match_its_schema() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let shapes = design(&mut s);
+ let id = "sketch.inspect";
+ for p in [json!({"sketch": shapes}), json!({"sketch": "Shapes"}), json!({"sketch": "Top"}), json!({"sketch": "Base"})] {
+ matches::<SketchInspected>(id, &run(&mut s, id, p), false);
+ }
+ let r = run(&mut s, id, json!({"sketch": "Shapes"}));
+ let kinds: Vec<&str> = r["curves"].as_array().into_iter().flatten().filter_map(|c| c["type"].as_str()).collect();
+ for kind in ["line", "circle", "arc", "ellipse", "spline", "conic"] {
+ assert!(kinds.contains(&kind), "{kind} in {kinds:?}");
+ }
+ assert!(
+ r["constraints"].as_array().is_some_and(|c| c.iter().any(|c| c["param"].is_string() && c["expression"].is_string() && c["type"].is_string())),
+ "{r}"
+ );
+ assert!(r["profiles"][0]["holes"].is_array() && r["points"][0]["link"].is_null(), "{r}");
+ let top = run(&mut s, id, json!({"sketch": "Top"}));
+ assert!(top["links"][0]["id"].is_string() && top["curves"][0]["link"].is_string(), "{top}");
+ run(&mut s, "sketch.edit", json!({"sketch": "Shapes"}));
+ for p in [json!({}), json!({"sketch": null}), json!({"sketch": shapes.to_string()})] {
+ let r = run(&mut s, id, p);
+ matches::<SketchInspected>(id, &r, false);
+ assert_eq!(r["name"], "Shapes", "{r}");
+ }
+}
+
+/// `material.assign` (a name, a list, the default material) and `material.list` (built-in
+/// materials and the design's, with and without a look) in Warn without warnings.
+#[test]
+fn material_replies_match_their_schemas() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ design(&mut s);
+ let id = "material.assign";
+ let r = run(&mut s, id, json!({"bodies": ["Block"], "material": "alloy"}));
+ assert_eq!(r, json!({"bodies": ["Block"], "material": "Alloy"}));
+ matches::<MaterialAssignResult>(id, &r, false);
+ let r = run(&mut s, id, json!({"bodies": "Shaft", "material": " steel "}));
+ assert_eq!(r["material"], "Steel", "{r}");
+ matches::<MaterialAssignResult>(id, &r, false);
+ matches::<MaterialAssignResult>(id, &run(&mut s, id, json!({"bodies": ["Block", "Shaft"], "material": "Painted"})), false);
+ matches::<MaterialAssignResult>(id, &run(&mut s, id, json!({"bodies": ["Block"], "material": "Steel"})), false);
+
+ let listed = run(&mut s, "material.list", json!({}));
+ matches::<MaterialListResult>("material.list", &listed, false);
+ let materials = listed["materials"].as_array().cloned().unwrap_or_default();
+ assert_eq!(materials[0].as_object().map(|m| m.len()), Some(2), "{listed}");
+ let mine = |name: &str| materials.iter().find(|m| m["name"] == name).cloned().unwrap_or_default();
+ assert!(mine("Alloy")["user"] == true && mine("Alloy")["appearance"]["color"] == "#ff0000", "{listed}");
+ assert!(mine("Painted")["appearance"]["pbr"]["metallic"] == 0.5, "{listed}");
+ assert!(mine("Steel").get("user").is_none() && mine("Steel").get("appearance").is_none(), "{listed}");
+ run(&mut s, "material.create", json!({"name": "Bare", "density_g_cm3": 1.0}));
+ let listed = run(&mut s, "material.list", json!({}));
+ matches::<MaterialListResult>("material.list", &listed, false);
+ let bare = listed["materials"].as_array().into_iter().flatten().find(|m| m["name"] == "Bare").cloned().unwrap_or_default();
+ assert!(bare["appearance"].is_null() && bare["user"] == true, "{listed}");
+}
+
+/// `engine.commands` replies with a list, which carries no `param_warnings`: Strict is where a
+/// stray key is refused. The list has every command, and each entry matches its schema.
+#[test]
+fn the_command_list_matches_its_schema() {
+ let mut strict = Session { param_check: ParamCheck::Strict, ..Session::default() };
+ let list = run(&mut strict, "engine.commands", json!({}));
+ let schema = output_schema_for::<Vec<CommandEntry>>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &list), "{list}");
+ assert_eq!(list.as_array().map(Vec::len), Some(crate::command_specs().len()));
+ assert!(list.as_array().is_some_and(|l| l.iter().any(|c| c["id"] == "engine.commands" && c["enabled"] == true && c["shortcut"].is_null())));
+ assert!(list.as_array().is_some_and(|l| l.iter().any(|c| c["id"] == "inspect.measure" && c["shortcut"] == "I")));
+ let error = strict.execute("engine.commands", &json!({"lst": 1})).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains("unknown key `lst`"), "{error}");
+ let mut warn = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ assert!(run(&mut warn, "engine.commands", json!({"lst": 1})).is_array());
+}
+
+/// A misspelt key runs in Warn and is reported, with a reply that still matches its schema.
+#[test]
+fn a_misspelt_key_is_reported_in_warn() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let shapes = design(&mut s);
+ let schemas = |id: &str| match id {
+ "document.inspect" => output_schema_for::<DocumentInspectResult>(),
+ "inspect.measure" => output_schema_for::<MeasureResult>(),
+ "material.assign" => output_schema_for::<MaterialAssignResult>(),
+ "material.list" => output_schema_for::<MaterialListResult>(),
+ _ => output_schema_for::<SketchInspected>(),
+ };
+ for (id, p, suggestion) in [
+ ("document.inspect", json!({"mesure": true}), "measure"),
+ ("document.inspect", json!({"sketch_count": true}), "sketch_counts"),
+ ("inspect.measure", json!({"bodes": ["Block"]}), "bodies"),
+ ("inspect.measure", json!({"name_only": true}), "names_only"),
+ ("material.assign", json!({"bodies": ["Block"], "materal": "Steel", "material": "Steel"}), "material"),
+ ("material.list", json!({"materials": true}), ""),
+ ("sketch.inspect", json!({"sketch": shapes, "sketchs": 1}), "sketch"),
+ ] {
+ let r = run(&mut s, id, p.clone());
+ let warnings: Vec<&str> = r["param_warnings"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
+ assert_eq!(warnings.len(), 1, "{id} {p}: {r}");
+ assert!(warnings[0].starts_with("unknown key `") && warnings[0].contains(suggestion), "{id}: {warnings:?}");
+ let schema = schemas(id);
+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id}: {r}");
+ }
+}
+
+/// Shapes the real designs above don't reach: a body whose measurement failed (a sheet metal
+/// one carries its corrected counts) and the null coordinates of two planes that meet.
+#[test]
+fn rare_reply_shapes_serialize_as_before_and_match_the_schema() {
+ use super::{BodyFailure, BodyMeasurement, BodyOutcome, Measured, MeasuredItems};
+ let failed = BodyMeasurement {
+ name: "B".into(),
+ outcome: BodyOutcome::Failed(BodyFailure { error: "boom".into(), faces: Some(2), edges: None, vertices: None }),
+ };
+ assert_eq!(serde_json::to_value(&failed).unwrap_or_default(), json!({"name": "B", "error": "boom", "faces": 2}));
+ let items = MeasuredItems { from: Some([f64::NAN, 0.0, 0.0]), distance_mm: Some(0.0), ..MeasuredItems::default() };
+ let reply = serde_json::to_value(MeasureResult { measured: Measured::Items(Box::new(items)), param_warnings: Vec::new() }).unwrap_or_default();
+ assert_eq!(reply["from"], json!([null, 0.0, 0.0]));
+ let schema = output_schema_for::<MeasureResult>();
+ assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}");
+}
+
/// #11945: each body lists the features that built it, in timeline order: its own box, the fillet
/// that changed it, and the cutting box a Combine consumed into it with that Combine. Another body
/// keeps only its own. Rolled back before the Combine, neither it nor the tool's box are listed.
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index f68f1f8250..31a4267a4e 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -11,8 +11,6 @@ doc.open
doc.recover
doc.recovery_discard
doc.recovery_list
-document.inspect
-engine.commands
face.delete
file.export
file.insert_mesh
@@ -22,7 +20,6 @@ file.save
file.save_as
file.save_mesh
file.slicers
-inspect.measure
joint.cam
joint.gear
joint.motion_link
@@ -32,8 +29,6 @@ joint.reach
joint.rigid_group
joint.screw
joint.sweep
-material.assign
-material.list
mesh.convert
motion.export_animation
motion.interference
@@ -79,7 +74,6 @@ sketch.fit_curves_to_section
sketch.include_3d
sketch.insert_dxf
sketch.insert_svg
-sketch.inspect
sketch.intersect
sketch.intersection_curve
sketch.isoparametric_curve