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 exploded view commands describe their exact parameters and reply (#12501) (#12594)

PeppaWutz6085423d0d0b
diff --git a/crates/engine/src/cmd/motion.rs b/crates/engine/src/cmd/motion.rs
index 4ac55c35e8..99c41680f0 100644
--- a/crates/engine/src/cmd/motion.rs
+++ b/crates/engine/src/cmd/motion.rs
@@ -16,8 +16,10 @@ use super::joints::{cannot_move, effective_values, joint_id, occurrence_id, plac
use crate::params::{bad, bool_, str_, vec3};
use crate::schema::motion::{
ContactCheck, ContactCollision, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetChange,
- ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams,
- MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo, MotionStudyParams, MotionStudySaved,
+ ContactSetCreated, ContactSetEdited, ContactSetInfo, ContactSets, ContactSwitch, ExplodeCreateParams, ExplodeCreated, ExplodeDeleteParams,
+ ExplodeDeleted, ExplodeListParams, ExplodeMoveInfo, ExplodeShowParams, ExplodeShown, ExplodeViews, ExplodedViewInfo, FindLimitsParams,
+ FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted, MotionStudyInfo, MotionStudyKeyInfo,
+ MotionStudyParams, MotionStudySaved,
};
use crate::schema::motion_play::{
DriveReport, ExportParams, PartPose, PlayParams, Pose, StudyExport, StudyExported, StudyPlayed, StudySample, UnmovedJoint,
@@ -53,6 +55,10 @@ const CONTACT_EDIT_CONTRACT: TypedContract<ContactEditParams> = TypedContract::n
const STUDY_CONTRACT: TypedContract<MotionStudyParams> = TypedContract::new();
const STUDY_DELETE_CONTRACT: TypedContract<MotionStudyDeleteParams> = TypedContract::new();
const STUDY_LIST_CONTRACT: TypedContract<MotionListParams> = TypedContract::new();
+const EXPLODE_CREATE_CONTRACT: TypedContract<ExplodeCreateParams> = TypedContract::new();
+const EXPLODE_SHOW_CONTRACT: TypedContract<ExplodeShowParams> = TypedContract::new();
+const EXPLODE_LIST_CONTRACT: TypedContract<ExplodeListParams> = TypedContract::new();
+const EXPLODE_DELETE_CONTRACT: TypedContract<ExplodeDeleteParams> = TypedContract::new();
const PLAY_CONTRACT: TypedContract<PlayParams> = TypedContract::new();
const EXPORT_CONTRACT: TypedContract<ExportParams> = TypedContract::new();
@@ -175,16 +181,32 @@ pub static COMMANDS: &[CommandSpec] = &[
.contract(&STUDY_DELETE_CONTRACT)
.output(output_schema_for::<MotionStudyDeleted>)
.params("study"),
- CommandSpec::new("explode.create", "Exploded View", explode_create).at("SOLID", "ASSEMBLE").icon("explode").enabled(has_parts_to_explode).params(
- "name?; scale? (automatic: each occurrence pushed away from the assembly's centre by scale × its offset, default 1); \
- moves?: [{occurrence, translate: [x,y,z]}] (instead of automatic)",
- ),
- CommandSpec::new("explode.show", "Show Exploded View", explode_show)
+ CommandSpec::new("explode.create", "Exploded View", crate::checked!("explode.create", explode_create))
+ .at("SOLID", "ASSEMBLE")
+ .icon("explode")
+ .enabled(has_parts_to_explode)
+ .contract(&EXPLODE_CREATE_CONTRACT)
+ .output(output_schema_for::<ExplodeCreated>)
+ .params(
+ "name?; scale? (automatic: each occurrence pushed away from the assembly's centre by scale × its offset, default 1); \
+ moves?: [{occurrence, translate: [x,y,z]}] (instead of automatic)",
+ ),
+ CommandSpec::new("explode.show", "Show Exploded View", crate::checked!("explode.show", explode_show))
.icon("explode")
.noundo()
+ .contract(&EXPLODE_SHOW_CONTRACT)
+ .output(output_schema_for::<ExplodeShown>)
.params("view: id|name (or none: back to the assembled placement) — shown only; the design keeps its placements"),
- CommandSpec::new("explode.list", "List Exploded Views", explode_list).icon("list").noundo(),
- CommandSpec::new("explode.delete", "Delete Exploded View", explode_delete).icon("delete").params("view"),
+ CommandSpec::new("explode.list", "List Exploded Views", crate::checked!("explode.list", explode_list))
+ .icon("list")
+ .noundo()
+ .contract(&EXPLODE_LIST_CONTRACT)
+ .output(output_schema_for::<ExplodeViews>),
+ CommandSpec::new("explode.delete", "Delete Exploded View", crate::checked!("explode.delete", explode_delete))
+ .icon("delete")
+ .contract(&EXPLODE_DELETE_CONTRACT)
+ .output(output_schema_for::<ExplodeDeleted>)
+ .params("view"),
];
const MAX_ITEMS: usize = 10_000;
@@ -1233,7 +1255,8 @@ fn explode_create(s: &mut Session, p: &Value) -> Result<Value> {
let name =
str_(p, "name").map(str::to_string).unwrap_or_else(|| free_name("Exploded View", s.doc.assembly.exploded.iter().map(|v| v.name.as_str())));
s.doc_mut().assembly.exploded.push(ExplodedView { id, name: name.clone(), moves: moves.clone() });
- Ok(json!({"view": id, "name": name, "moves": moves.iter().map(|(o, t)| json!({"occurrence": o, "translate": t})).collect::<Vec<_>>()}))
+ let moves = moves.iter().map(ExplodeMoveInfo::from).collect();
+ typed_reply(cmd, ExplodeCreated { view: id, name, moves, param_warnings: Vec::new() })
}
fn explode_show(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1242,7 +1265,7 @@ fn explode_show(s: &mut Session, p: &Value) -> Result<Value> {
s.pending_moves.clear();
s.exploded.clear();
s.revision += 1;
- return Ok(json!({"view": null}));
+ return typed_reply(cmd, ExplodeShown { view: None, name: None, param_warnings: Vec::new() });
}
let i = view_index(s, p, cmd)?;
let v = s.doc.assembly.exploded.get(i).cloned().ok_or_else(|| bad(cmd, "view"))?;
@@ -1254,7 +1277,7 @@ fn explode_show(s: &mut Session, p: &Value) -> Result<Value> {
s.exploded.clone_from(&moves);
s.pending_moves = moves;
s.revision += 1;
- Ok(json!({"view": v.id, "name": v.name}))
+ typed_reply(cmd, ExplodeShown { view: Some(v.id), name: Some(v.name), param_warnings: Vec::new() })
}
/// Whether the pending moves are an exploded view shown (`explode.show`), which places the
@@ -1287,13 +1310,14 @@ fn exploded_at(moves: &[(u64, Mat, Vec3)], amount: f64) -> std::collections::BTr
}
fn explode_list(s: &mut Session, _p: &Value) -> Result<Value> {
- Ok(json!({"views": s.doc.assembly.exploded}))
+ let views = s.doc.assembly.exploded.iter().map(ExplodedViewInfo::from).collect();
+ typed_reply("explode.list", ExplodeViews { views, param_warnings: Vec::new() })
}
fn explode_delete(s: &mut Session, p: &Value) -> Result<Value> {
let i = view_index(s, p, "explode.delete")?;
let v = s.doc_mut().assembly.exploded.remove(i);
- Ok(json!({"deleted": v.name}))
+ typed_reply("explode.delete", ExplodeDeleted { deleted: v.name, param_warnings: Vec::new() })
}
/// World position of a point of an occurrence (tests).
diff --git a/crates/engine/src/schema/motion.rs b/crates/engine/src/schema/motion.rs
index bb51ecda58..0137143f19 100644
--- a/crates/engine/src/schema/motion.rs
+++ b/crates/engine/src/schema/motion.rs
@@ -7,7 +7,9 @@ use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{Value, json};
-use super::check::whole;
+use solidcraft_geom::Vec3Geom as _;
+
+use super::check::{located, whole};
/// Find where each value of a joint can go before the parts it moves touch another body. The
/// design is not changed.
@@ -625,6 +627,268 @@ pub struct MotionStudyDeleted {
pub param_warnings: Vec<String>,
}
+// ---- Exploded views (#12501) ----
+//
+// The exploded view handlers read their parameters from the raw JSON, so each key here reads as
+// its handler reads it and fails with its message. Whether an occurrence or a view exists stays
+// the handler's to check.
+
+/// Make an exploded view: occurrences moved apart, shown with `explode.show`. The design keeps
+/// its placements. One undo step. With `moves`, each occurrence moves as given; without, every
+/// top-level occurrence is pushed away from the assembly's centre by `scale` times its offset.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ExplodeCreateKeys {
+ /// The view's name. Default: "Exploded View" and the first number no view's name has.
+ #[serde(default)]
+ pub name: Option<String>,
+ /// For the automatic view: how far each occurrence is pushed away from the assembly's
+ /// centre, as a multiple of its offset from it (a number from -100 to 100). Default: 1.
+ /// Not read, and so not checked, when `moves` is given.
+ #[serde(default, deserialize_with = "explode_scale", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "explode_scale_schema")]
+ pub scale: Option<f64>,
+ /// The moves, instead of the automatic view (at most 10 000): each an `occurrence` (by id or
+ /// name, or a component's name for its first occurrence) and its `translate`, in mm, as
+ /// [x, y, z] or {x, y, z}, less than 1e7 in length. An occurrence named twice is moved by
+ /// the last.
+ #[serde(default, deserialize_with = "explode_moves", skip_serializing_if = "Option::is_none")]
+ #[schemars(schema_with = "explode_moves_schema")]
+ pub moves: Option<Vec<Value>>,
+}
+
+/// `explode.create`'s parameters: [`ExplodeCreateKeys`], where `scale` is read only without
+/// `moves`, as the handler does.
+#[derive(Debug)]
+pub struct ExplodeCreateParams(pub ExplodeCreateKeys);
+
+impl<'de> Deserialize<'de> for ExplodeCreateParams {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let mut value = Value::deserialize(d)?;
+ // `moves`, even `null`, is what the handler goes by: it never reads `scale` then.
+ if let Some(keys) = value.as_object_mut()
+ && keys.contains_key("moves")
+ {
+ keys.remove("scale");
+ }
+ serde_path_to_error::deserialize(&value).map(ExplodeCreateParams).map_err(|e| D::Error::custom(located(&e)))
+ }
+}
+
+impl JsonSchema for ExplodeCreateParams {
+ fn schema_name() -> Cow<'static, str> {
+ "ExplodeCreateParams".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ ExplodeCreateKeys::json_schema(generator)
+ }
+}
+
+/// `scale`: a number of at most 100 in size, with the handler's message for anything else,
+/// `null` included.
+fn explode_scale<'de, D: Deserializer<'de>>(d: D) -> Result<Option<f64>, D::Error> {
+ Value::deserialize(d)?
+ .as_f64()
+ .filter(|x| x.is_finite() && x.abs() <= 100.0)
+ .map(Some)
+ .ok_or_else(|| D::Error::custom(whole("`scale` must be a number up to 100")))
+}
+
+fn explode_scale_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "For the automatic view: how far each occurrence is pushed away from the assembly's centre, as a multiple of its offset from it (a number from -100 to 100). Default: 1. Not read, and so not checked, when `moves` is given.",
+ "type": "number",
+ "minimum": -100,
+ "maximum": 100
+ })
+}
+
+/// Why the handler refuses `item`, one of `moves`, before looking at the design.
+/// The handler also looks each occurrence up as it goes, so a call with an unknown occurrence in
+/// an earlier move and a malformed later one gets the handler's "no occurrence" message with the
+/// check off and this shape message in strict; both refuse the call.
+fn explode_move_problem(item: &Value) -> Option<&'static str> {
+ if !matches!(item.get("occurrence"), Some(Value::Number(_) | Value::String(_))) {
+ return Some("an occurrence must be an id or a name");
+ }
+ let translate = item.get("translate").and_then(crate::params::vec3).filter(|v| v.len() < 1e7);
+ translate.is_none().then_some("each move needs `translate`: [x, y, z]")
+}
+
+/// `moves`: a list of at most 10 000 moves, each checked as [`explode_move_problem`] says. Given,
+/// `null` included, it must be a list, as the handler reads it.
+fn explode_moves<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<Value>>, D::Error> {
+ let Value::Array(moves) = Value::deserialize(d)? else {
+ return Err(D::Error::custom(whole("`moves` must be a list")));
+ };
+ if moves.len() > MAX_EXPLODE_ITEMS {
+ return Err(D::Error::custom(whole("too many moves")));
+ }
+ if let Some(problem) = moves.iter().find_map(explode_move_problem) {
+ return Err(D::Error::custom(whole(problem)));
+ }
+ Ok(Some(moves))
+}
+
+/// The most moves a view takes, and the most views a design has, as `cmd/motion.rs`'s `MAX_ITEMS`.
+const MAX_EXPLODE_ITEMS: usize = 10_000;
+
+fn explode_moves_schema(_: &mut SchemaGenerator) -> Schema {
+ let c = json!({"type": "number", "exclusiveMinimum": -1e7, "exclusiveMaximum": 1e7});
+ json_schema!({
+ "description": "The moves, instead of the automatic view (at most 10 000): each an `occurrence` (by id or name, or a component's name for its first occurrence) and its `translate`, in mm, as [x, y, z] or {x, y, z}, less than 1e7 in length. An occurrence named twice is moved by the last.",
+ "type": "array",
+ "maxItems": MAX_EXPLODE_ITEMS,
+ "items": {
+ "type": "object",
+ "required": ["occurrence", "translate"],
+ "properties": {
+ "occurrence": {"type": ["number", "string"]},
+ "translate": {
+ "anyOf": [
+ {"type": "array", "items": c, "minItems": 3, "maxItems": 3},
+ {"type": "object", "properties": {"x": c, "y": c, "z": c}, "required": ["x", "y", "z"]}
+ ]
+ }
+ }
+ }
+ })
+}
+
+/// An exploded view by its id (a number) or its name.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ViewRef(pub Value);
+
+impl<'de> Deserialize<'de> for ViewRef {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ v @ (Value::Number(_) | Value::String(_)) => Ok(ViewRef(v)),
+ _ => Err(D::Error::custom(whole("`view` must be an id or a name"))),
+ }
+ }
+}
+
+impl JsonSchema for ViewRef {
+ fn schema_name() -> Cow<'static, str> {
+ "ViewRef".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "An exploded view's id (a number) or its name.", "type": ["number", "string"]})
+ }
+}
+
+/// Show an exploded view in the model: the occurrences are drawn moved apart, and the design
+/// keeps its placements. Without a view (or `none`), show the assembled placement again.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ExplodeShowParams {
+ /// The view to show, by id (a number) or name. Default: none, which shows the assembled
+ /// placement; `null` and the text `none` (in any case) mean the same.
+ #[serde(default)]
+ pub view: Option<ViewRef>,
+}
+
+/// List the design's exploded views. Nothing is changed.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct ExplodeListParams {}
+
+/// Delete an exploded view. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = view_required)]
+pub struct ExplodeDeleteParams {
+ // Required in the schema (`view_required`), optional in the type: left out, the handler
+ // refuses it with its own message, not the check's "is required". `null` is refused too.
+ /// The view to delete, by id (a number) or name.
+ #[serde(default, deserialize_with = "some_view", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ViewRef")]
+ pub view: Option<ViewRef>,
+}
+
+/// `view`: an id or a name, with the handler's message for anything else, `null` included.
+fn some_view<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ViewRef>, D::Error> {
+ ViewRef::deserialize(d).map(Some)
+}
+
+fn view_required(schema: &mut Schema) {
+ require(schema, "view");
+}
+
+/// One move of an exploded view.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExplodeMoveInfo {
+ /// The occurrence, by id.
+ pub occurrence: u64,
+ /// How far it moves, in mm (world).
+ pub translate: [f64; 3],
+}
+
+impl From<&(u64, solidcore_record::Vec3)> for ExplodeMoveInfo {
+ fn from((occurrence, t): &(u64, solidcore_record::Vec3)) -> Self {
+ ExplodeMoveInfo { occurrence: *occurrence, translate: [t.x, t.y, t.z] }
+ }
+}
+
+/// What `explode.create` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExplodeCreated {
+ /// The new view's id.
+ pub view: u64,
+ pub name: String,
+ pub moves: Vec<ExplodeMoveInfo>,
+ /// 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 `explode.show` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExplodeShown {
+ /// The view shown, by id; `null` when the assembled placement is shown.
+ pub view: Option<u64>,
+ /// The view's name; not there when the assembled placement is shown.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub name: 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 `explode.list` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExplodeViews {
+ pub views: Vec<ExplodedViewInfo>,
+ /// 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>,
+}
+
+/// An exploded view, as the design saves it.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExplodedViewInfo {
+ pub id: u64,
+ pub name: String,
+ /// [occurrence id, translation in mm] pairs.
+ pub moves: Vec<(u64, [f64; 3])>,
+}
+
+impl From<&solidcraft_doc::motion::ExplodedView> for ExplodedViewInfo {
+ fn from(view: &solidcraft_doc::motion::ExplodedView) -> Self {
+ let moves = view.moves.iter().map(|(o, t)| (*o, [t.x, t.y, t.z])).collect();
+ ExplodedViewInfo { id: view.id, name: view.name.clone(), moves }
+ }
+}
+
+/// What `explode.delete` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ExplodeDeleted {
+ /// The deleted view's name.
+ pub deleted: 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>,
+}
+
#[cfg(test)]
#[path = "motion_tests.rs"]
mod tests;
diff --git a/crates/engine/src/schema/motion_tests.rs b/crates/engine/src/schema/motion_tests.rs
index 1546b0a0f6..6da88d6469 100644
--- a/crates/engine/src/schema/motion_tests.rs
+++ b/crates/engine/src/schema/motion_tests.rs
@@ -2,7 +2,8 @@ use serde_json::{Value, json};
use super::{
ContactCheck, ContactCreateParams, ContactEditParams, ContactEnableParams, ContactNoParams, ContactSetCreated, ContactSetEdited, ContactSets,
- ContactSwitch, FindLimitsParams, FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted,
+ ContactSwitch, ExplodeCreateParams, ExplodeCreated, ExplodeDeleteParams, ExplodeDeleted, ExplodeListParams, ExplodeShowParams, ExplodeShown,
+ ExplodeViews, FindLimitsParams, FindLimitsResult, MotionListParams, MotionStudies, MotionStudyDeleteParams, MotionStudyDeleted,
MotionStudyParams, MotionStudySaved,
};
use crate::Session;
@@ -19,6 +20,10 @@ fn schemas_and_the_key_check_agree() {
assert_keys(input_schema_for::<MotionStudyParams>(), &["keys", "name", "steps", "study"]);
assert_keys(input_schema_for::<MotionListParams>(), &[]);
assert_keys(input_schema_for::<MotionStudyDeleteParams>(), &["study"]);
+ assert_keys(input_schema_for::<ExplodeCreateParams>(), &["moves", "name", "scale"]);
+ assert_keys(input_schema_for::<ExplodeShowParams>(), &["view"]);
+ assert_keys(input_schema_for::<ExplodeListParams>(), &[]);
+ assert_keys(input_schema_for::<ExplodeDeleteParams>(), &["view"]);
}
#[test]
@@ -259,3 +264,203 @@ fn motion_studies_reply_with_their_schemas() {
let error = s.execute("motion.study", &p).err().map(|e| e.to_string()).unwrap_or_default();
assert!(error.contains("`step`"), "{error}");
}
+
+/// The exploded view commands in a design with three occurrences, in Off and in Strict: each call
+/// the handler refuses is refused with the same message. They need the door's occurrences, so
+/// the shared helper doesn't fit.
+#[test]
+fn strict_keeps_the_exploded_views_errors() {
+ let many: Vec<Value> = (0..10_001).map(|_| move_of(json!("Door"), json!([1, 2, 3]))).collect();
+ for (id, p) in [
+ ("explode.create", json!({"moves": null})),
+ ("explode.create", json!({"moves": "Door"})),
+ ("explode.create", json!({"moves": {"occurrence": "Door", "translate": [1, 2, 3]}})),
+ ("explode.create", json!({"moves": many})),
+ ("explode.create", json!({"moves": [{}]})),
+ ("explode.create", json!({"moves": [true]})),
+ ("explode.create", json!({"moves": [move_of(json!(null), json!([1, 2, 3]))]})),
+ ("explode.create", json!({"moves": [move_of(json!(true), json!([1, 2, 3]))]})),
+ ("explode.create", json!({"moves": [move_of(json!(["Door"]), json!([1, 2, 3]))]})),
+ ("explode.create", json!({"moves": [move_of(json!("Nope"), json!([1, 2, 3]))]})),
+ ("explode.create", json!({"moves": [{"occurrence": "Door"}]})),
+ ("explode.create", json!({"moves": [move_of(json!("Door"), json!(null))]})),
+ ("explode.create", json!({"moves": [move_of(json!("Door"), json!([1, 2]))]})),
+ ("explode.create", json!({"moves": [move_of(json!("Door"), json!({"x": 1, "y": 2}))]})),
+ ("explode.create", json!({"moves": [move_of(json!("Door"), json!(["a", 2, 3]))]})),
+ ("explode.create", json!({"moves": [move_of(json!("Door"), json!([1e7, 0, 0]))]})),
+ ("explode.create", json!({"moves": [move_of(json!("Door"), json!([8e6, 8e6, 0]))]})),
+ ("explode.create", json!({"moves": [move_of(json!("Door"), json!([1, 2, 3])), {"translate": [1, 2, 3]}]})),
+ ("explode.create", json!({"scale": "2"})),
+ ("explode.create", json!({"scale": null})),
+ ("explode.create", json!({"scale": true})),
+ ("explode.create", json!({"scale": 100.5})),
+ ("explode.create", json!({"scale": -101})),
+ ("explode.show", json!({"view": true})),
+ ("explode.show", json!({"view": [1]})),
+ ("explode.show", json!({"view": {"id": 1}})),
+ ("explode.show", json!({"view": "Nope"})),
+ ("explode.show", json!({"view": 7})),
+ ("explode.delete", json!({})),
+ ("explode.delete", json!({"view": null})),
+ ("explode.delete", json!({"view": false})),
+ ("explode.delete", json!({"view": ["Apart"]})),
+ ("explode.delete", json!({"view": "Nope"})),
+ ] {
+ let error = |level: ParamCheck| {
+ let mut s = door();
+ s.param_check = level;
+ s.execute(id, &p).err().map(|e| e.to_string())
+ };
+ let off = error(ParamCheck::Off);
+ assert!(off.is_some(), "{id} {p} should fail today");
+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
+ }
+}
+
+fn move_of(occurrence: Value, translate: Value) -> Value {
+ json!({"occurrence": occurrence, "translate": translate})
+}
+
+/// The exploded view types read each key as the handlers do: `scale` only without `moves`, a move
+/// by an occurrence's id or name with a point in either form, `view` left out, `null` or `none`
+/// to show the assembled placement but refused by `explode.delete`, and keys a move carries
+/// besides its two ignored. Each case is also checked against the schema.
+#[test]
+fn the_exploded_view_types_read_the_keys_as_the_handlers_do() {
+ let issues = |id: &str, p: &Value| crate::schema::issues(id, p).into_iter().map(|i| i.message).collect::<Vec<_>>();
+ let ok = |id: &str, p: Value, takes: bool| assert_eq!(issues(id, &p).is_empty(), takes, "{id} {p}: {:?}", issues(id, &p));
+ let schema_takes = |schema: schemars::Schema, p: Value, takes: bool| {
+ let schema = schema.as_value();
+ assert_eq!(conforms(schema, schema, &p), takes, "{p}");
+ };
+ // `scale` is read only when `moves` is not there; `moves` is read when it is there at all.
+ let one = move_of(json!(3), json!({"x": 1, "y": 2, "z": 3}));
+ for (p, takes) in [
+ (json!({}), true),
+ (json!({"name": "Apart", "scale": 2.5}), true),
+ (json!({"scale": -100}), true),
+ (json!({"scale": 101}), false),
+ (json!({"scale": "2"}), false),
+ (json!({"scale": null}), false),
+ (json!({"moves": [], "scale": "ignored"}), true),
+ (json!({"moves": [one.clone()], "scale": null}), true),
+ (json!({"moves": [{"occurrence": "Door", "translate": [0, 0, 5], "note": "ignored"}]}), true),
+ (json!({"moves": null, "scale": 2}), false),
+ (json!({"moves": "Door"}), false),
+ (json!({"moves": [{"occurrence": "Door"}]}), false),
+ (json!({"moves": [{"occurrence": true, "translate": [0, 0, 5]}]}), false),
+ (json!({"moves": [{"occurrence": "Door", "translate": [0, 0, 1e7]}]}), false),
+ ] {
+ ok("explode.create", p, takes);
+ }
+ schema_takes(input_schema_for::<ExplodeCreateParams>(), json!({"moves": [one], "name": "N"}), true);
+ schema_takes(input_schema_for::<ExplodeCreateParams>(), json!({"moves": [{"occurrence": "Door"}]}), false);
+ schema_takes(input_schema_for::<ExplodeCreateParams>(), json!({"scale": 101}), false);
+ // Showing: no view, `null` and `none` in any case show the assembled placement.
+ for (p, takes) in [
+ (json!({}), true),
+ (json!({"view": null}), true),
+ (json!({"view": "None"}), true),
+ (json!({"view": "Apart"}), true),
+ (json!({"view": 4}), true),
+ (json!({"view": true}), false),
+ (json!({"view": ["Apart"]}), false),
+ ] {
+ ok("explode.show", p.clone(), takes);
+ schema_takes(input_schema_for::<ExplodeShowParams>(), p, takes);
+ }
+ // Deleting needs a view, by id or name.
+ for (p, takes) in [(json!({"view": "Apart"}), true), (json!({"view": 4}), true), (json!({}), false), (json!({"view": null}), false)] {
+ schema_takes(input_schema_for::<ExplodeDeleteParams>(), p, takes);
+ }
+ ok("explode.delete", json!({"view": "Apart"}), true);
+ assert_eq!(issues("explode.delete", &json!({"view": null})), ["`view` must be an id or a name"]);
+ assert_eq!(issues("explode.delete", &json!({})), Vec::<String>::new(), "the handler gives its own message for a missing view");
+ assert_eq!(issues("explode.show", &json!({"view": true})), ["`view` must be an id or a name"]);
+ assert_eq!(issues("explode.create", &json!({"scale": "x"})), ["`scale` must be a number up to 100"]);
+ assert_eq!(issues("explode.create", &json!({"moves": 1})), ["`moves` must be a list"]);
+ assert_eq!(issues("explode.create", &json!({"moves": [{}]})), ["an occurrence must be an id or a name"]);
+ assert_eq!(issues("explode.create", &json!({"moves": [{"occurrence": 1}]})), ["each move needs `translate`: [x, y, z]"]);
+ assert_eq!(issues("explode.list", &json!({"x": 1})).len(), 1);
+}
+
+/// Making, showing, listing and deleting exploded views reply as the output schemas say, in Warn
+/// without warnings, with the JSON the handlers have always returned. A misspelt key gets
+/// `param_warnings` in Warn, since the handlers ignore unknown keys, and strict refuses it.
+#[test]
+fn exploded_views_reply_with_their_schemas() {
+ let mut s = door();
+ s.param_check = ParamCheck::Warn;
+ let run = |s: &mut Session, id: &str, p: Value, schema: schemars::Schema| {
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ r
+ };
+ let auto = run(&mut s, "explode.create", json!({}), output_schema_for::<ExplodeCreated>());
+ assert_eq!(auto["name"], "Exploded View1", "{auto}");
+ assert_eq!(auto["moves"].as_array().map(Vec::len), Some(3), "{auto}");
+ assert!(auto["moves"][0]["occurrence"].is_u64() && auto["moves"][0]["translate"].as_array().is_some_and(|t| t.len() == 3), "{auto}");
+ let scaled = run(&mut s, "explode.create", json!({"name": "Far", "scale": 2.5}), output_schema_for::<ExplodeCreated>());
+ assert_eq!(scaled["name"], "Far", "{scaled}");
+ run(&mut s, "explode.create", json!({"scale": -1}), output_schema_for::<ExplodeCreated>());
+ // `scale` is not read with `moves`, so a bad one is no problem.
+ let by_hand = run(
+ &mut s,
+ "explode.create",
+ json!({"name": "Hand", "scale": "ignored", "moves": [move_of(json!("Door"), json!([0, 0, 50])), move_of(json!("Slide"), json!({"x": 1, "y": 2, "z": 3}))]}),
+ output_schema_for::<ExplodeCreated>(),
+ );
+ let (door_id, slide_id) = (by_hand["moves"][0]["occurrence"].clone(), by_hand["moves"][1]["occurrence"].clone());
+ let expected = json!({
+ "view": by_hand["view"],
+ "name": "Hand",
+ "moves": [{"occurrence": door_id, "translate": [0.0, 0.0, 50.0]}, {"occurrence": slide_id, "translate": [1.0, 2.0, 3.0]}]
+ });
+ assert_eq!(by_hand, expected);
+ run(&mut s, "explode.create", json!({"name": "Empty", "moves": []}), output_schema_for::<ExplodeCreated>());
+
+ let list = run(&mut s, "explode.list", json!({}), output_schema_for::<ExplodeViews>());
+ assert_eq!(list["views"].as_array().map(Vec::len), Some(5), "{list}");
+ // Exactly what the design's own views serialize to, as the handler returned them before.
+ assert_eq!(list["views"], serde_json::to_value(&s.doc.assembly.exploded).unwrap_or_default());
+ assert_eq!(list["views"][3], json!({"id": by_hand["view"], "name": "Hand", "moves": [[door_id, [0.0, 0.0, 50.0]], [slide_id, [1.0, 2.0, 3.0]]]}));
+
+ // Shown by name, by id and, to put the assembled placement back, by nothing, `null` or `none`.
+ let r = run(&mut s, "explode.show", json!({"view": "Hand"}), output_schema_for::<ExplodeShown>());
+ assert_eq!(r, json!({"view": by_hand["view"], "name": "Hand"}));
+ let r = run(&mut s, "explode.show", json!({"view": scaled["view"]}), output_schema_for::<ExplodeShown>());
+ assert_eq!(r, json!({"view": scaled["view"], "name": "Far"}));
+ for p in [json!({}), json!({"view": null}), json!({"view": "None"})] {
+ run(&mut s, "explode.show", json!({"view": "Hand"}), output_schema_for::<ExplodeShown>());
+ let r = run(&mut s, "explode.show", p, output_schema_for::<ExplodeShown>());
+ assert_eq!(r, json!({"view": null}));
+ }
+
+ let r = run(&mut s, "explode.delete", json!({"view": "Hand"}), output_schema_for::<ExplodeDeleted>());
+ assert_eq!(r, json!({"deleted": "Hand"}));
+ let r = run(&mut s, "explode.delete", json!({"view": scaled["view"]}), output_schema_for::<ExplodeDeleted>());
+ assert_eq!(r, json!({"deleted": "Far"}));
+
+ // A misspelt key runs in Warn and says so, with a reply that still matches; strict refuses it.
+ run(&mut s, "explode.create", json!({"name": "Typo"}), output_schema_for::<ExplodeCreated>());
+ for (id, p, schema) in [
+ ("explode.create", json!({"nme": "Typo"}), output_schema_for::<ExplodeCreated>()),
+ ("explode.show", json!({"veiw": "Exploded View"}), output_schema_for::<ExplodeShown>()),
+ ("explode.list", json!({"view": 1}), output_schema_for::<ExplodeViews>()),
+ ("explode.delete", json!({"view": "Typo", "name": 1}), output_schema_for::<ExplodeDeleted>()),
+ ] {
+ s.param_check = ParamCheck::Warn;
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let schema = schema.as_value();
+ assert!(r["param_warnings"].as_array().is_some_and(|w| !w.is_empty()) && conforms(schema, schema, &r), "{id}: {r}");
+ s.param_check = ParamCheck::Strict;
+ let error = s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains("unknown key"), "{id}: {error}");
+ }
+ let before = s.doc.assembly.exploded.len();
+ s.param_check = ParamCheck::Strict;
+ assert!(s.execute("explode.create", &json!({"nme": "Typo"})).is_err());
+ assert_eq!(s.doc.assembly.exploded.len(), before, "strict ran nothing");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 51c6188e8d..cb091d6760 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -21,10 +21,6 @@ doc.recovery_discard
doc.recovery_list
document.inspect
engine.commands
-explode.create
-explode.delete
-explode.list
-explode.show
expr.evaluate
face.delete
file.export