SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: the named view commands and Redefine Sketch describe their exact parameters and reply (#12499) (#12592)
PeppaWutz5eaf8c4181b1
diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rsindex cfd7e681d4..1c5bfa8509 100644--- a/crates/engine/src/cmd/browser.rs+++ b/crates/engine/src/cmd/browser.rs@@ -19,9 +19,11 @@ use crate::params::{bad, bool_, expr, str_};use crate::schema::browser::{BodyRenameParams, BodyRenamed, BrowserFoldParams, BrowserFoldResult, BrowserGroupMade, BrowserGroupParams, BrowserGroupRenamed,BrowserMoveParams, BrowserMoved, BrowserOrderParams, BrowserOrdered, BrowserRenameGroupParams, BrowserUngroupParams, BrowserUngrouped,- BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, Isolated, RepairDone, RepairFace, RepairHole,- RepairParams, RepairResult, RepairSewn, VisibilityState,+ BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, Isolated, PlaneFrame, RedefineAttachment,+ RedefineSketchParams, RedefineSketchResult, RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn, ViewApplyParams,+ ViewDeleteParams, ViewDeleted, ViewListParams, ViewListResult, ViewRenameParams, ViewRenamed, ViewSaveParams, ViewSaved, VisibilityState,};+use crate::schema::view_navigation::CameraReply;use crate::schema::{TypedContract, output_schema_for};use crate::{Result, Session};@@ -35,6 +37,12 @@ const MOVE_CONTRACT: TypedContract<BrowserMoveParams> = TypedContract::new();const ORDER_CONTRACT: TypedContract<BrowserOrderParams> = TypedContract::new();const VISIBILITY_CONTRACT: TypedContract<BrowserVisibilityParams> = TypedContract::new();const FOLD_CONTRACT: TypedContract<BrowserFoldParams> = TypedContract::new();+const REDEFINE_SKETCH_CONTRACT: TypedContract<RedefineSketchParams> = TypedContract::new();+const VIEW_SAVE_CONTRACT: TypedContract<ViewSaveParams> = TypedContract::new();+const VIEW_RENAME_CONTRACT: TypedContract<ViewRenameParams> = TypedContract::new();+const VIEW_DELETE_CONTRACT: TypedContract<ViewDeleteParams> = TypedContract::new();+const VIEW_LIST_CONTRACT: TypedContract<ViewListParams> = TypedContract::new();+const VIEW_APPLY_CONTRACT: TypedContract<ViewApplyParams> = TypedContract::new();/// A reply as JSON: the commands here build their replies from the types their output schemas/// describe, so the two can't drift apart.@@ -56,8 +64,10 @@ pub static COMMANDS: &[CommandSpec] = &[.params("body: its name (a part the modelling kernel refuses, or an open part that should be a solid); gap?: expr (default 0.2 mm, at most 1 mm: free edges that pair up within it are sewn, each sewn edge carrying its own gap as its tolerance); patch_holes?: bool (default false: loops of free edges left are patched, in the plane of the faces around them where those are that plane, else tangent to them, and sewn in; otherwise the reply offers the patches); name? → the feature, and repair: what changed face by face (rebuilt and refused faces, sewn gaps, holes with their surface.patch), faces and largest edge tolerance before and after, closed, modelling, volume. Refused with why when nothing applies",),- CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", redefine_sketch)+ CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", crate::checked!("sketch.redefine", redefine_sketch)).icon("plane")+ .contract(&REDEFINE_SKETCH_CONTRACT)+ .output(output_schema_for::<RedefineSketchResult>).params("sketch: id or name; plane: as sketch.create; frame?: as sketch.create; author_path?: exact owner occurrence ids; explicitly rebinds or freezes the plane while preserving geometry and dimension names"),CommandSpec::new("browser.group", "New Group", crate::checked!("browser.group", group)).icon("folder")@@ -84,13 +94,33 @@ pub static COMMANDS: &[CommandSpec] = &[.contract(&UNITS_CONTRACT).output(crate::schema::output_schema_for::<DocumentUnitsResult>).params("units: mm|cm|m|in|ft (display and unit-less parameters; values keep their meaning)"),- CommandSpec::new("view.save", "New Named View", view_save)+ CommandSpec::new("view.save", "New Named View", crate::checked!("view.save", view_save)).icon("camera")+ .contract(&VIEW_SAVE_CONTRACT)+ .output(output_schema_for::<ViewSaved>).params("name?; camera: {target: [x,y,z], yaw, pitch, distance, fov?} (replaces a view of the same name)"),- CommandSpec::new("view.rename", "Rename Named View", view_rename).icon("rename").params("view: name, name"),- CommandSpec::new("view.delete", "Delete Named View", view_delete).icon("delete").params("view: name"),- CommandSpec::new("view.list", "List Named Views", view_list).icon("list").noundo().doc_only(),- CommandSpec::new("view.apply", "Restore Named View", view_apply).icon("camera").noundo().params(+ CommandSpec::new("view.rename", "Rename Named View", crate::checked!("view.rename", view_rename))+ .icon("rename")+ .contract(&VIEW_RENAME_CONTRACT)+ .output(output_schema_for::<ViewRenamed>)+ .params("view: name, name"),+ CommandSpec::new("view.delete", "Delete Named View", crate::checked!("view.delete", view_delete))+ .icon("delete")+ .contract(&VIEW_DELETE_CONTRACT)+ .output(output_schema_for::<ViewDeleted>)+ .params("view: name"),+ CommandSpec::new("view.list", "List Named Views", crate::checked!("view.list", view_list))+ .icon("list")+ .noundo()+ .contract(&VIEW_LIST_CONTRACT)+ .output(output_schema_for::<ViewListResult>)+ .doc_only(),+ CommandSpec::new("view.apply", "Restore Named View", crate::checked!("view.apply", view_apply))+ .icon("camera")+ .noundo()+ .contract(&VIEW_APPLY_CONTRACT)+ .output(output_schema_for::<CameraReply>)+ .params("view?: front|back|top|bottom|left|right|iso|home (frames the model) | a named view's name; or camera?: {target: [x,y,z], yaw, pitch, distance, fov?, roll?} (radians, mm, about the up axis; yaw: heading of the line of sight, 0 along +Y (Front), π/2 along +X (Left), π (Back), −π/2 (Right); pitch: the eye's elevation, within ±π/2, π/2 = Top; roll defaults to 0, turns the picture clockwise, must be finite and is clamped to ±π; the View angles readout shows these in degrees; up is refused: the up axis comes from the design settings) → camera. The viewport (and the MCP screenshot) moves there. View state: not saved, not an undo step",),CommandSpec::new("browser.order", "Order Browser Items", crate::checked!("browser.order", order))@@ -1049,14 +1079,47 @@ fn document_units(s: &mut Session, p: &Value) -> Result<Value> {reply(kept)}+/// A camera `view.save` keeps, as the handler reads it (and `ViewCamera`, its contract type): a+/// [`solidcraft_doc::NamedView`] of finite numbers with a positive distance, or the message the+/// handler refuses it with.+pub(crate) fn saved_view_form(c: &Value) -> std::result::Result<solidcraft_doc::NamedView, String> {+ let v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| format!("bad camera: {e}"))?;+ let ok = [v.target.x, v.target.y, v.target.z, v.yaw, v.pitch, v.distance, v.fov].iter().all(|x| x.is_finite()) && v.distance > 0.0;+ if ok { Ok(v) } else { Err("the camera must be finite with a positive distance".into()) }+}++/// The camera `view.apply` turns to for a `camera` it is given, as the handler reads it (and+/// `ApplyCamera`, its contract type), or the message the handler refuses it with.+pub(crate) fn applied_camera_form(c: &Value) -> std::result::Result<crate::render::Camera, String> {+ if c.get("up").is_some() {+ return Err("camera `up` is not supported: the up axis comes from the design settings".into());+ }+ let roll = match c.get("roll") {+ Some(value) => value.as_f64().filter(|r| r.is_finite()).ok_or("camera `roll` must be a finite number in radians")?,+ None => 0.0,+ };+ let v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| format!("bad camera: {e}"))?;+ // Past a pole the same view has other angles; the orbit would snap it back (#6032).+ if !(v.pitch.abs() <= std::f64::consts::FRAC_PI_2 + 1e-9) {+ return Err("camera `pitch` must be within ±π/2 radians (±90°)".into());+ }+ let cam = crate::render::Camera { roll: roll.clamp(-std::f64::consts::PI, std::f64::consts::PI), ..camera_of(&v) };+ if !usable_camera(&cam) {+ return Err("the camera must be finite with a positive distance".into());+ }+ Ok(cam)+}++/// A camera the viewport can be put at: finite, with a positive distance and a field of view of+/// at least 0.+fn usable_camera(cam: &crate::render::Camera) -> bool {+ cam.is_valid() && cam.fov.is_finite() && cam.fov >= 0.0+}+fn view_save(s: &mut Session, p: &Value) -> Result<Value> {let cmd = "view.save";let c = p.get("camera").ok_or_else(|| bad(cmd, "`camera` is required"))?;- let mut v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| bad(cmd, format!("bad camera: {e}")))?;- let ok = [v.target.x, v.target.y, v.target.z, v.yaw, v.pitch, v.distance, v.fov].iter().all(|x| x.is_finite()) && v.distance > 0.0;- if !ok {- return Err(bad(cmd, "the camera must be finite with a positive distance"));- }+ let mut v = saved_view_form(c).map_err(|e| bad(cmd, e))?;let n = s.doc.named_views.len();v.name = match str_(p, "name").map(str::trim).filter(|n| !n.is_empty()) {Some(n) if n.len() <= 128 => n.to_string(),@@ -1070,7 +1133,7 @@ fn view_save(s: &mut Session, p: &Value) -> Result<Value> {let d = s.doc_mut();d.named_views.retain(|x| x.name != name);d.named_views.push(v);- Ok(json!({ "view": name }))+ reply(cmd, ViewSaved { view: name, param_warnings: Vec::new() })}fn view_apply(s: &mut Session, p: &Value) -> Result<Value> {@@ -1078,23 +1141,7 @@ fn view_apply(s: &mut Session, p: &Value) -> Result<Value> {let cam = match (str_(p, "view"), p.get("camera")) {(Some(_), Some(_)) => return Err(bad(cmd, "give `view` or `camera`, not both")),(None, None) => return Err(bad(cmd, "`view` (a name) or `camera` is required")),- (None, Some(c)) => {- if c.get("up").is_some() {- return Err(bad(cmd, "camera `up` is not supported: the up axis comes from the design settings"));- }- let roll = match c.get("roll") {- Some(value) => {- value.as_f64().filter(|r| r.is_finite()).ok_or_else(|| bad(cmd, "camera `roll` must be a finite number in radians"))?- }- None => 0.0,- };- let v: solidcraft_doc::NamedView = serde_json::from_value(c.clone()).map_err(|e| bad(cmd, format!("bad camera: {e}")))?;- // Past a pole the same view has other angles; the orbit would snap it back (#6032).- if !(v.pitch.abs() <= std::f64::consts::FRAC_PI_2 + 1e-9) {- return Err(bad(cmd, "camera `pitch` must be within ±π/2 radians (±90°)"));- }- crate::render::Camera { roll: roll.clamp(-std::f64::consts::PI, std::f64::consts::PI), ..camera_of(&v) }- }+ (None, Some(c)) => applied_camera_form(c).map_err(|e| bad(cmd, e))?,// Standard view names come first, as in the browser's Named Views folder.(Some(name), None) => match crate::render::StandardView::parse(name) {Some(sv) => {@@ -1106,11 +1153,11 @@ fn view_apply(s: &mut Session, p: &Value) -> Result<Value> {None => s.doc.named_views.iter().find(|v| v.name == name).map(camera_of).ok_or_else(|| bad(cmd, format!("no named view `{name}`")))?,},};- if !cam.is_valid() || !cam.fov.is_finite() || cam.fov < 0.0 {+ if !usable_camera(&cam) {return Err(bad(cmd, "the camera must be finite with a positive distance"));}s.camera = Some(cam);- Ok(json!({ "camera": cam }))+ reply(cmd, CameraReply { camera: cam, param_warnings: Vec::new() })}/// The orbit camera of a named view (Z up, no roll).@@ -1134,17 +1181,18 @@ fn view_rename(s: &mut Session, p: &Value) -> Result<Value> {if let Some(v) = s.doc_mut().named_views.get_mut(i) {v.name = name.to_string();}- Ok(json!({ "view": name }))+ reply(cmd, ViewRenamed { view: name.to_string(), param_warnings: Vec::new() })}fn view_delete(s: &mut Session, p: &Value) -> Result<Value> {- let i = view_index(s, p, "view.delete")?;+ let cmd = "view.delete";+ let i = view_index(s, p, cmd)?;let v = s.doc_mut().named_views.remove(i);- Ok(json!({ "deleted": v.name }))+ reply(cmd, ViewDeleted { deleted: v.name, param_warnings: Vec::new() })}fn view_list(s: &mut Session, _p: &Value) -> Result<Value> {- Ok(json!({ "views": s.doc.named_views }))+ reply("view.list", ViewListResult { views: s.doc.named_views.clone(), param_warnings: Vec::new() })}/// The keys whose strings name bodies, alone or in a list (`body`, `targets`…), at any depth of a@@ -1493,17 +1541,17 @@ fn redefine_sketch(s: &mut Session, p: &Value) -> Result<Value> {let attachment = s.doc.feature(id).and_then(|feature| match &feature.kind {FeatureKind::Sketch { plane, .. } => Some(if super::sketch::face::anchor(plane).is_some() {- "exact_face"+ RedefineAttachment::ExactFace} else if solidcraft_doc::sheet::plane_sheet_face(plane).is_some() {- "sheet_face"+ RedefineAttachment::SheetFace} else {- "fixed"+ RedefineAttachment::Fixed}),_ => None,});- let mut out = json!({ "sketch": id,"attachment":attachment });- super::sketch::frame_reply(&mut out, frame, &placement);- Ok(out)+ let note = frame.and_then(|f| super::sketch::frame_note(Some(f), &placement)).map(str::to_string);+ let frame = frame.and_then(PlaneFrame::from_name);+ reply(cmd, RedefineSketchResult { sketch: id, attachment, frame, note, created: None, param_warnings: Vec::new() })}#[cfg(test)]diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex ba4360daf8..efd073aec5 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -882,17 +882,23 @@ pub(super) fn plane_frame(p: &Value, cmd: &str) -> Result<Option<&'static str>>}}+/// The note a reply carries when a world plane went into a moved or turned component+/// (`placement`: that component's) for an explicit plane read in `frame`, where it differs from+/// the component's own.+pub(super) fn frame_note(frame: Option<&str>, placement: &solidcraft_doc::Mat) -> Option<&'static str> {+ (frame == Some("world") && !solidcraft_doc::is_identity(placement)).then_some(+ "the plane was read in world coordinates and the component is moved or turned, so it is stored at that world place in the component; frame: \"component\" reads it in the component's own coordinates",+ )+}+/// The reply's `frame` for an explicit plane, with a note when a world plane went into a moved/// or turned component (`placement`: that component's), where it differs from the component's own.pub(super) fn frame_reply(out: &mut Value, frame: Option<&str>, placement: &solidcraft_doc::Mat) {let Some(o) = out.as_object_mut() else { return };let Some(frame) = frame else { return };o.insert("frame".into(), json!(frame));- if frame == "world" && !solidcraft_doc::is_identity(placement) {- o.insert(- "note".into(),- json!("the plane was read in world coordinates and the component is moved or turned, so it is stored at that world place in the component; frame: \"component\" reads it in the component's own coordinates"),- );+ if let Some(note) = frame_note(Some(frame), placement) {+ o.insert("note".into(), json!(note));}}diff --git a/crates/engine/src/schema/browser.rs b/crates/engine/src/schema/browser.rsindex 0d88f670a0..abeeb901c4 100644--- a/crates/engine/src/schema/browser.rs+++ b/crates/engine/src/schema/browser.rs@@ -9,7 +9,8 @@ use serde_json::{Value, json};use solidcraft_doc::BrowserEntry;-use super::check::whole;+use super::canvas::CanvasPlane;+use super::check::{located, whole};use super::types::{FeatureCommon, LengthExpr, feature_common, present};/// Repair a part the modelling kernel refuses, or an open part that should be a solid: faces@@ -1107,6 +1108,469 @@ pub struct BodyRenamed {pub param_warnings: Vec<String>,}+// ---- Named views and Redefine Sketch (#12499) ----+//+// As above: each key reads as its handler reads it and fails with the handler's message. A key+// the handler can't do without is optional in the type and required in the schema, so the+// handler's own message is what a call that leaves it out gets. Whether a view or a sketch+// exists, and whether a plane or a face can be found, stays the handler's to check.++fn view_required(schema: &mut Schema) {+ require(schema, &["view"]);+}++fn view_and_name_required(schema: &mut Schema) {+ require(schema, &["view", "name"]);+}++fn camera_required(schema: &mut Schema) {+ require(schema, &["camera"]);+}++fn sketch_and_plane_required(schema: &mut Schema) {+ require(schema, &["sketch", "plane"]);+}++/// A named view, as `view.rename` and `view.delete` read `view`: text.+#[derive(Clone, Debug, PartialEq)]+pub struct ViewKey(pub String);++impl<'de> Deserialize<'de> for ViewKey {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(n) => Ok(ViewKey(n)),+ _ => Err(D::Error::custom(whole("`view` must be a view name"))),+ }+ }+}++impl JsonSchema for ViewKey {+ fn schema_name() -> Cow<'static, str> {+ "ViewKey".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A named view's name.", "type": "string"})+ }+}++fn some_view<'de, D: Deserializer<'de>>(d: D) -> Result<Option<ViewKey>, D::Error> {+ ViewKey::deserialize(d).map(Some)+}++/// The name `view.save` gives a view: at most 128 bytes once surrounding spaces are cut; nothing+/// left means the next free "Named View" number.+#[derive(Clone, Debug, PartialEq)]+pub struct SavedViewName(pub String);++impl<'de> Deserialize<'de> for SavedViewName {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(n) if n.trim().len() > MAX_NAME_BYTES => Err(D::Error::custom(whole("`name` is too long"))),+ Value::String(n) => Ok(SavedViewName(n)),+ _ => Err(D::Error::custom("must be text")),+ }+ }+}++impl JsonSchema for SavedViewName {+ fn schema_name() -> Cow<'static, str> {+ "SavedViewName".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A name of at most 128 bytes once surrounding spaces are cut.", "type": "string"})+ }+}++/// The point a saved camera looks at, as the schemas of the view commands give it.+fn target_schema() -> Value {+ json!({+ "description": "The point the camera looks at, in mm: [x, y, z].",+ "type": "array",+ "items": {"type": "number"},+ "minItems": 3,+ "maxItems": 3+ })+}++/// The camera `view.save` keeps, as the handler reads it: finite numbers and a positive+/// distance. A `name` inside it is replaced by the call's `name`.+#[derive(Clone, Debug, PartialEq)]+pub struct ViewCamera(pub solidcraft_doc::NamedView);++impl<'de> Deserialize<'de> for ViewCamera {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ crate::cmd::browser::saved_view_form(&Value::deserialize(d)?).map(ViewCamera).map_err(|why| D::Error::custom(whole(why)))+ }+}++impl JsonSchema for ViewCamera {+ fn schema_name() -> Cow<'static, str> {+ "ViewCamera".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "An orbit camera. Angles are in radians, about the up axis.",+ "type": "object",+ "properties": {+ "target": target_schema(),+ "yaw": {"description": "Turn about the up axis; 0 looks along +Y, from the front.", "type": "number"},+ "pitch": {"description": "Elevation of the eye above the ground plane.", "type": "number"},+ "distance": {"description": "From the target to the eye, in mm.", "type": "number", "exclusiveMinimum": 0},+ "fov": {"description": "Vertical field of view; 0 is orthographic. Default: 0.", "type": "number", "default": 0.0}+ },+ "required": ["target", "yaw", "pitch", "distance"]+ })+ }+}++/// Keep the camera as a named view of the design. One undo step. A view of the same name is+/// replaced.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = camera_required)]+pub struct ViewSaveParams {+ // Optional in the type and required in the schema (`camera_required`): left out, the handler+ // refuses it with its own message.+ /// The camera to keep: `{target: [x, y, z], yaw, pitch, distance, fov?}`, finite, with a+ /// distance above 0.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ViewCamera")]+ pub camera: Option<ViewCamera>,+ /// The view's name, at most 128 bytes once surrounding spaces are cut. Default: "Named View"+ /// and the first number no view's name has. A value that is not text is reported, though the+ /// handler would read it as left out.+ #[serde(default)]+ pub name: Option<SavedViewName>,+}++/// What `view.save` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ViewSaved {+ /// The name the view was kept under.+ pub view: 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>,+}++/// Rename a named view. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = view_and_name_required)]+pub struct ViewRenameParams {+ // Required in the schema (`view_and_name_required`), optional in the type, as `group` above.+ /// The view to rename, by name.+ #[serde(default, deserialize_with = "some_view", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ViewKey")]+ pub view: Option<ViewKey>,+ /// The new name, 1 to 128 characters once surrounding spaces are cut; no other view may+ /// have it.+ #[serde(default, deserialize_with = "some_new_name", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "NewName")]+ pub name: Option<NewName>,+}++/// What `view.rename` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ViewRenamed {+ /// The view's name now, without surrounding spaces.+ pub view: 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>,+}++/// Delete a named view. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = view_required)]+pub struct ViewDeleteParams {+ // Required in the schema (`view_required`), optional in the type.+ /// The view to delete, by name.+ #[serde(default, deserialize_with = "some_view", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ViewKey")]+ pub view: Option<ViewKey>,+}++/// What `view.delete` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ViewDeleted {+ /// The name of the view that is gone.+ 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>,+}++/// `view.list` takes no parameters.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ViewListParams {}++/// A named view, as `view.list` gives it. Only its schema is described here: the reply carries+/// the design's own [`solidcraft_doc::NamedView`] values.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ViewEntry {+ /// The view's name.+ pub name: String,+ /// The point the camera looks at, in mm.+ pub target: [f64; 3],+ /// Turn about the up axis, in radians.+ pub yaw: f64,+ /// Elevation of the eye, in radians.+ pub pitch: f64,+ /// From the target to the eye, in mm.+ pub distance: f64,+ /// Vertical field of view in radians; 0 is orthographic.+ pub fov: f64,+}++/// What `view.list` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ViewListResult {+ /// The design's named views, in the order they were made.+ #[schemars(with = "Vec<ViewEntry>")]+ pub views: Vec<solidcraft_doc::NamedView>,+ /// 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 camera `view.apply` turns to, as the handler reads it: `up` is refused, `roll` is finite,+/// the pitch within ±π/2 and the rest finite with a positive distance.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct ApplyCamera(pub solidcraft_render::Camera);++impl<'de> Deserialize<'de> for ApplyCamera {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ crate::cmd::browser::applied_camera_form(&Value::deserialize(d)?).map(ApplyCamera).map_err(|why| D::Error::custom(whole(why)))+ }+}++impl JsonSchema for ApplyCamera {+ fn schema_name() -> Cow<'static, str> {+ "ApplyCamera".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "An orbit camera. Angles are in radians, about the up axis, which comes from the design settings.",+ "type": "object",+ "properties": {+ "target": target_schema(),+ "yaw": {"description": "Turn about the up axis; 0 looks along +Y (Front), π/2 along +X (Left), π (Back), -π/2 (Right).", "type": "number"},+ "pitch": {"description": "Elevation of the eye above the ground plane, within ±π/2; π/2 is Top.", "type": "number", "minimum": -std::f64::consts::FRAC_PI_2, "maximum": std::f64::consts::FRAC_PI_2},+ "distance": {"description": "From the target to the eye, in mm.", "type": "number", "exclusiveMinimum": 0},+ "fov": {"description": "Vertical field of view; 0 is orthographic. Default: 0.", "type": "number", "minimum": 0, "default": 0.0},+ "roll": {"description": "Turn about the viewing direction, clockwise; a finite number, clamped to ±π. Default: 0.", "type": "number", "default": 0.0}+ },+ "required": ["target", "yaw", "pitch", "distance"],+ "not": {"required": ["up"]}+ })+ }+}++/// Move the viewport (and the MCP screenshot) to a standard view, a named view or a camera. View+/// state only: not saved with the design and not an undo step. Give `view` or `camera`, not both.+/// (A `view` that is not text is read as absent when a `camera` is given, as the handler does.)+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ViewApplyKeys {+ /// A standard view: front, back, top, bottom, left, right, iso or home (the model framed+ /// from there), or a named view's name. Not with `camera`.+ #[serde(default)]+ pub view: Option<String>,+ /// A camera to turn to. Not with `view`.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ApplyCamera")]+ pub camera: Option<ApplyCamera>,+}++/// `view.apply`'s parameters: [`ViewApplyKeys`] with the two forms told apart.+///+/// The handler reads `view` as text and takes anything else as absent, and reads `camera` only+/// when `view` is not text, so the same holds here: a `view` that is not text is not looked at+/// when a `camera` is given, and one of neither is left to the handler's message.+#[derive(Debug)]+pub struct ViewApplyParams(pub ViewApplyKeys);++impl<'de> Deserialize<'de> for ViewApplyParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let mut value = Value::deserialize(d)?;+ if value.get("view").is_some_and(Value::is_string) {+ if value.get("camera").is_some() {+ return Err(D::Error::custom(whole("give `view` or `camera`, not both")));+ }+ } else if let Some(keys) = value.as_object_mut() {+ keys.remove("view");+ }+ serde_path_to_error::deserialize(&value).map(ViewApplyParams).map_err(|e| D::Error::custom(located(&e)))+ }+}++impl JsonSchema for ViewApplyParams {+ fn schema_name() -> Cow<'static, str> {+ "ViewApplyParams".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ let mut schema = ViewApplyKeys::json_schema(generator);+ schema.insert("anyOf".into(), json!([{"required": ["view"]}, {"required": ["camera"]}]));+ schema.insert("not".into(), json!({"required": ["view", "camera"]}));+ schema+ }+}++/// A sketch by id or name, as `sketch.redefine` reads `sketch`.+#[derive(Clone, Debug, PartialEq)]+pub struct SketchKey(pub String);++impl<'de> Deserialize<'de> for SketchKey {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::Number(n) => Ok(SketchKey(n.to_string())),+ Value::String(s) => Ok(SketchKey(s)),+ _ => Err(D::Error::custom(whole("`sketch` must be an id or name"))),+ }+ }+}++impl JsonSchema for SketchKey {+ fn schema_name() -> Cow<'static, str> {+ "SketchKey".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "A sketch's feature id (a number) or its name.", "type": ["number", "string"]})+ }+}++fn some_sketch<'de, D: Deserializer<'de>>(d: D) -> Result<Option<SketchKey>, D::Error> {+ SketchKey::deserialize(d).map(Some)+}++/// The coordinates an explicit plane `{origin, x_dir, y_dir}` is given in: `world` or+/// `component`, the component's own. (No doc on the variants: they would make the schema a+/// `oneOf` of constants instead of a plain `enum`.)+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)]+#[serde(rename_all = "lowercase")]+pub enum PlaneFrame {+ World,+ Component,+}++impl PlaneFrame {+ /// The frame a handler names, as `world` or `component`.+ pub fn from_name(name: &str) -> Option<PlaneFrame> {+ match name {+ "world" => Some(PlaneFrame::World),+ "component" => Some(PlaneFrame::Component),+ _ => None,+ }+ }+}++impl<'de> Deserialize<'de> for PlaneFrame {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(f) if f == "world" => Ok(PlaneFrame::World),+ Value::String(f) if f == "component" => Ok(PlaneFrame::Component),+ _ => Err(D::Error::custom(whole("`frame` must be \"world\" or \"component\""))),+ }+ }+}++/// The occurrence ids of the placement a sketch is authored in, from the outermost down, as+/// `sketch.redefine` reads `author_path`: at most 64 nonzero whole numbers.+#[derive(Clone, Debug, PartialEq)]+pub struct AuthorPath(pub Vec<u64>);++impl<'de> Deserialize<'de> for AuthorPath {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::Array(path) if path.len() <= MAX_PATH => path+ .iter()+ .map(|id| id.as_u64().filter(|id| *id != 0).ok_or_else(|| D::Error::custom(whole("invalid author_path id"))))+ .collect::<Result<_, _>>()+ .map(AuthorPath),+ _ => Err(D::Error::custom(whole("author_path must contain at most64 ids"))),+ }+ }+}++impl JsonSchema for AuthorPath {+ fn schema_name() -> Cow<'static, str> {+ "AuthorPath".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "Occurrence ids, outermost first: at most 64 whole numbers above 0.",+ "type": "array",+ "items": {"type": "integer", "minimum": 1},+ "maxItems": MAX_PATH+ })+ }+}++/// Move a sketch to another plane, keeping its geometry and its dimension names: an origin or+/// construction plane, an explicit plane, or a planar face of the model. A face it follows is+/// refused where the sketch's own geometry would depend on later features. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = sketch_and_plane_required)]+pub struct RedefineSketchParams {+ // Optional in the type and required in the schema (`sketch_and_plane_required`): left out,+ // the handler refuses it with its own message.+ /// The sketch to move, by feature id or name.+ #[serde(default, deserialize_with = "some_sketch", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "SketchKey")]+ pub sketch: Option<SketchKey>,+ /// The new plane, as `sketch.create` takes it. A picked face is read as it reads one.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "CanvasPlane")]+ pub plane: Option<CanvasPlane>,+ /// Move the plane this far along its normal (mm or a length expression). Default: 0.+ #[serde(default)]+ pub offset: Option<LengthExpr>,+ /// The placement the sketch is authored in, as occurrence ids from the outermost down. Default: the+ /// sketch's saved one, else the active occurrence, else the component's only placement; a+ /// component sketch in a design with several placements needs it.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "AuthorPath")]+ pub author_path: Option<AuthorPath>,+ /// For an explicit plane `{origin, x_dir, y_dir}`: whether it is in the world's or the+ /// component's own coordinates. Default: world. A named plane or a face takes none.+ #[serde(default)]+ pub frame: Option<PlaneFrame>,+}++/// How a redefined sketch is attached to its plane: `exact_face` (to a face of a body, which it+/// follows), `sheet_face` (to a face of a sheet part) or `fixed` (where it is: an origin,+/// construction or explicit plane).+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, JsonSchema)]+#[serde(rename_all = "snake_case")]+pub enum RedefineAttachment {+ ExactFace,+ SheetFace,+ Fixed,+}++/// What `sketch.redefine` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct RedefineSketchResult {+ /// The sketch's feature id.+ pub sketch: u64,+ /// How it is attached now.+ pub attachment: Option<RedefineAttachment>,+ /// For an explicit plane: the coordinates it was read in.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub frame: Option<PlaneFrame>,+ /// For a world plane put into a component that is moved or turned: how it was stored.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub note: Option<String>,+ /// What the session reports for every sketch command: the ids of the points, curves,+ /// constraints and dimensions the sketch gained, `{points, curves, constraints, dimensions}`.+ /// The handler leaves it out; the session adds it.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub created: Option<Value>,+ /// In the warn parameter-check mode: what the call's parameters got wrong.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub param_warnings: Vec<String>,+}+#[cfg(test)]#[path = "browser_tests.rs"]mod tests;diff --git a/crates/engine/src/schema/browser_tests.rs b/crates/engine/src/schema/browser_tests.rsindex 38ccbbaebd..eb756ad77e 100644--- a/crates/engine/src/schema/browser_tests.rs+++ b/crates/engine/src/schema/browser_tests.rs@@ -3,10 +3,13 @@ use serde_json::{Value, json};use super::{BodyRenameParams, BodyRenamed, BrowserFoldParams, BrowserFoldResult, BrowserGroupMade, BrowserGroupParams, BrowserGroupRenamed,BrowserMoveParams, BrowserMoved, BrowserOrderParams, BrowserOrdered, BrowserRenameGroupParams, BrowserUngroupParams, BrowserUngrouped,- BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, RepairParams, RepairResult, VisibilityState,+ BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, RedefineSketchParams, RedefineSketchResult,+ RepairParams, RepairResult, ViewApplyParams, ViewDeleteParams, ViewDeleted, ViewListParams, ViewListResult, ViewRenameParams, ViewRenamed,+ ViewSaveParams, ViewSaved, VisibilityState,};use crate::Session;use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};+use crate::schema::view_navigation::CameraReply;use crate::schema::{ParamCheck, input_schema_for, output_schema_for};#[test]@@ -330,3 +333,413 @@ fn browser_commands_reply_with_their_schemas() {let error = s.execute("browser.visibility", &p).err().map(|e| e.to_string()).unwrap_or_default();assert!(error.contains("`itms`"), "{error}");}++// ---- Named views and Redefine Sketch (#12499) ----++const CAMERA: fn() -> Value = || json!({"target": [1, 2, 3], "yaw": 0.5, "pitch": -0.6, "distance": 150});++#[test]+fn view_schemas_and_the_key_check_agree() {+ assert_keys(input_schema_for::<ViewSaveParams>(), &["camera", "name"]);+ assert_keys(input_schema_for::<ViewRenameParams>(), &["name", "view"]);+ assert_keys(input_schema_for::<ViewDeleteParams>(), &["view"]);+ assert_keys(input_schema_for::<ViewListParams>(), &[]);+ assert_keys(input_schema_for::<ViewApplyParams>(), &["camera", "view"]);+ assert_keys(input_schema_for::<RedefineSketchParams>(), &["author_path", "frame", "offset", "plane", "sketch"]);+}++/// Each call has one problem the handler already refuses: strict gives its message. The session+/// has a sketch (`1`) and no named view, so a view that must exist is looked for in the second+/// test.+#[test]+fn view_strict_keeps_todays_errors() {+ let long = "n".repeat(129);+ let deep: Vec<u64> = (1..=65).collect();+ assert_strict_keeps_todays_errors(&[+ ("view.save", json!({})),+ ("view.save", json!({"name": "A"})),+ ("view.save", json!({"camera": null})),+ ("view.save", json!({"camera": "front"})),+ ("view.save", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0}})),+ ("view.save", json!({"camera": {"target": [0, 0], "yaw": 0, "pitch": 0, "distance": 5}})),+ ("view.save", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 0}})),+ ("view.save", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": -3}})),+ ("view.save", json!({"camera": CAMERA(), "name": long})),+ ("view.rename", json!({})),+ ("view.rename", json!({"name": "B"})),+ ("view.rename", json!({"view": 5, "name": "B"})),+ ("view.rename", json!({"view": null, "name": "B"})),+ ("view.rename", json!({"view": "Nope", "name": "B"})),+ ("view.delete", json!({})),+ ("view.delete", json!({"view": 5})),+ ("view.delete", json!({"view": null})),+ ("view.delete", json!({"view": "Nope"})),+ ("view.apply", json!({})),+ ("view.apply", json!({"view": 5})),+ ("view.apply", json!({"view": null})),+ ("view.apply", json!({"view": "Nope"})),+ ("view.apply", json!({"view": "top", "camera": CAMERA()})),+ ("view.apply", json!({"view": "top", "camera": null})),+ ("view.apply", json!({"camera": null})),+ ("view.apply", json!({"camera": "front"})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "up": "y"}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "up": null}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "roll": "x"}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "roll": null}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 1.6, "distance": 80}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": -1.6, "distance": 80}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 0}})),+ ("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": 0, "distance": 80, "fov": -0.5}})),+ ("sketch.redefine", json!({})),+ ("sketch.redefine", json!({"plane": "XZ"})),+ ("sketch.redefine", json!({"sketch": true, "plane": "XZ"})),+ ("sketch.redefine", json!({"sketch": null, "plane": "XZ"})),+ ("sketch.redefine", json!({"sketch": [1], "plane": "XZ"})),+ ("sketch.redefine", json!({"sketch": 999, "plane": "XZ"})),+ ("sketch.redefine", json!({"sketch": 1})),+ ("sketch.redefine", json!({"sketch": 1, "plane": null})),+ ("sketch.redefine", json!({"sketch": 1, "plane": true})),+ ("sketch.redefine", json!({"sketch": 1, "plane": 1.5})),+ ("sketch.redefine", json!({"sketch": 1, "plane": -1})),+ ("sketch.redefine", json!({"sketch": 1, "plane": {"x_dir": [1, 0, 0]}})),+ ("sketch.redefine", json!({"sketch": 1, "plane": {"x_dir": [1, 0, 0], "y_dir": [2, 0, 0]}})),+ ("sketch.redefine", json!({"sketch": 1, "plane": {"origin": "1 mm", "x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}})),+ ("sketch.redefine", json!({"sketch": 1, "plane": {"face": "x"}})),+ ("sketch.redefine", json!({"sketch": 1, "plane": {"face": [1, 2, 3], "body": "Box"}})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "frame": "local"})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "frame": 3})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "frame": "world"})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": "1"})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": null})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": [0]})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": ["a"]})),+ ("sketch.redefine", json!({"sketch": 1, "plane": "XZ", "author_path": deep})),+ ]);+}++/// The calls that need a named view to get as far as their message.+#[test]+fn view_strict_keeps_todays_errors_for_views() {+ let long = "n".repeat(129);+ let cases = [+ ("view.rename", json!({"view": "Front 2", "name": ""})),+ ("view.rename", json!({"view": "Front 2", "name": " "})),+ ("view.rename", json!({"view": "Front 2", "name": 5})),+ ("view.rename", json!({"view": "Front 2", "name": null})),+ ("view.rename", json!({"view": "Front 2", "name": long})),+ ("view.rename", json!({"view": "Front 2"})),+ ("view.rename", json!({"view": "Front 2", "name": "Other"})),+ ];+ for (id, p) in cases {+ let run = |level: ParamCheck| {+ let mut s = Session { param_check: level, ..Session::default() };+ for name in ["Front 2", "Other"] {+ s.execute("view.save", &json!({"camera": CAMERA(), "name": name})).unwrap_or_else(|e| panic!("{e}"));+ }+ s.execute(id, &p).err().map(|e| e.to_string())+ };+ let off = run(ParamCheck::Off);+ assert!(off.is_some(), "{id} {p} should fail today");+ assert_eq!(run(ParamCheck::Strict), off, "{id} {p}");+ }+}++/// What the handlers refuse is refused by the types with the same message, and what they take+/// is taken: the check names no problem for any call that works today, in the forms that read+/// different keys (`view` or `camera`) and in each form of `plane`.+#[test]+fn the_check_reads_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();+ let cam = |extra: Value| {+ let mut c = CAMERA();+ c["distance"] = json!(80);+ for (k, v) in extra.as_object().into_iter().flatten() {+ c[k] = v.clone();+ }+ c+ };+ // view.apply: a view, or a camera.+ assert_eq!(issues("view.apply", json!({"view": "top"})), none);+ assert_eq!(issues("view.apply", json!({"view": "Anything"})), none);+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({}))})), none);+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({"fov": 0.5, "roll": 1.0}))})), none);+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({"roll": 100}))})), none, "a roll past π is clamped");+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({"pitch": std::f64::consts::FRAC_PI_2}))})), none);+ // `view` is read as text only: where `camera` is the form, one that is not text is not looked at.+ assert_eq!(issues("view.apply", json!({"view": null, "camera": cam(json!({}))})), none);+ assert_eq!(issues("view.apply", json!({"view": 5, "camera": cam(json!({}))})), none);+ assert_eq!(issues("view.apply", json!({"view": "top", "camera": cam(json!({}))})), ["give `view` or `camera`, not both"]);+ assert_eq!(issues("view.apply", json!({"view": "top", "camera": null})), ["give `view` or `camera`, not both"]);+ assert_eq!(+ issues("view.apply", json!({"camera": cam(json!({"up": "z"}))})),+ ["camera `up` is not supported: the up axis comes from the design settings"]+ );+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({"roll": "x"}))})), ["camera `roll` must be a finite number in radians"]);+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({"pitch": 2}))})), ["camera `pitch` must be within ±π/2 radians (±90°)"]);+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({"distance": 0}))})), ["the camera must be finite with a positive distance"]);+ assert_eq!(issues("view.apply", json!({"camera": cam(json!({"fov": -1}))})), ["the camera must be finite with a positive distance"]);+ assert!(issues("view.apply", json!({"camera": {"yaw": 1}}))[0].starts_with("bad camera: missing field `target`"));+ // Neither: the handler's own message (the type leaves it to the handler).+ assert_eq!(issues("view.apply", json!({})), none);+ // view.save.+ assert_eq!(issues("view.save", json!({"camera": CAMERA()})), none);+ assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": " "})), none);+ assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": null})), none);+ // Not text: the handler reads it as left out; the check reports it.+ assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": 5})).len(), 1);+ assert_eq!(+ issues("view.save", json!({"camera": {"name": "old", "target": [1, 2, 3], "yaw": 0, "pitch": 7, "distance": 1, "fov": 0.3}, "name": "N"})),+ none+ );+ assert_eq!(issues("view.save", json!({"camera": cam(json!({"distance": -1}))})), ["the camera must be finite with a positive distance"]);+ assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": "n".repeat(129)})), ["`name` is too long"]);+ assert_eq!(issues("view.save", json!({"camera": CAMERA(), "name": format!(" {} ", "n".repeat(128))})), none);+ // view.rename and view.delete.+ assert_eq!(issues("view.rename", json!({"view": "a", "name": "b"})), none);+ assert_eq!(issues("view.rename", json!({"view": 1, "name": "b"})), ["`view` must be a view name"]);+ assert_eq!(issues("view.rename", json!({"view": "a", "name": ""})), ["`name` must be 1…128 characters"]);+ assert_eq!(issues("view.delete", json!({"view": null})), ["`view` must be a view name"]);+ assert_eq!(issues("view.list", json!({})), none);+ assert_eq!(issues("view.list", json!({"views": 1})).len(), 1);+ // sketch.redefine: each form of the plane, and `frame` and `author_path` as given.+ let plane = |p: Value| issues("sketch.redefine", json!({"sketch": "S", "plane": p}));+ for p in [+ json!("XY"),+ json!("front"),+ json!("Plane1"),+ json!(7),+ json!({"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}),+ json!({"origin": [1, 2, 3], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}),+ json!({"origin": null, "x_dir": {"x": 1, "y": 0, "z": 0}, "y_dir": [0, 1, 0]}),+ json!({"face": [1, 2, 3]}),+ json!({"face": [1, 2, 3], "body": "Box", "index": 2, "path": [1, 2], "fixed": true}),+ ] {+ assert_eq!(plane(p.clone()), none, "{p}");+ }+ assert_eq!(plane(json!(1.5)).len(), 1);+ assert_eq!(plane(json!(null)), ["`plane` must be XY, XZ, YZ, a construction plane name or id, or an object"]);+ assert_eq!(plane(json!({"x_dir": [1, 0, 0]})), ["plane needs y_dir"]);+ let with = |extra: Value| {+ let mut p = json!({"sketch": 1, "plane": "XZ"});+ for (k, v) in extra.as_object().into_iter().flatten() {+ p[k] = v.clone();+ }+ issues("sketch.redefine", p)+ };+ assert_eq!(with(json!({"offset": 5})), none);+ assert_eq!(with(json!({"offset": "w / 2"})), none);+ assert_eq!(with(json!({"frame": null})), none);+ assert_eq!(with(json!({"frame": "component", "author_path": [1, 2]})), none);+ assert_eq!(with(json!({"author_path": []})), none);+ assert_eq!(with(json!({"frame": "x"})), ["`frame` must be \"world\" or \"component\""]);+ assert_eq!(with(json!({"author_path": [0]})), ["invalid author_path id"]);+ assert_eq!(with(json!({"author_path": null})), ["author_path must contain at most64 ids"]);+ assert_eq!(issues("sketch.redefine", json!({"sketch": 2.5, "plane": "XZ"})), none);+ assert_eq!(issues("sketch.redefine", json!({"sketch": {}, "plane": "XZ"})), ["`sketch` must be an id or name"]);+}++/// The schemas say what the handlers need, and no more.+#[test]+fn the_view_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}");+ }+ };+ let cam = |extra: Value| {+ let mut c = CAMERA();+ for (k, v) in extra.as_object().into_iter().flatten() {+ c[k] = v.clone();+ }+ c+ };+ takes(+ input_schema_for::<ViewSaveParams>(),+ &[+ (json!({"camera": CAMERA()}), true),+ (json!({"camera": cam(json!({"fov": 0.4})), "name": "N"}), true),+ (json!({"name": "N"}), false),+ (json!({"camera": cam(json!({"distance": 0}))}), false),+ (json!({"camera": {"yaw": 0}}), false),+ ],+ );+ takes(+ input_schema_for::<ViewApplyParams>(),+ &[+ (json!({"view": "top"}), true),+ (json!({"camera": cam(json!({"roll": 0.3, "fov": 0.5}))}), true),+ (json!({}), false),+ (json!({"view": "top", "camera": CAMERA()}), false),+ (json!({"camera": cam(json!({"up": "z"}))}), false),+ (json!({"camera": cam(json!({"pitch": 2}))}), false),+ (json!({"camera": cam(json!({"fov": -1}))}), false),+ ],+ );+ takes(+ input_schema_for::<ViewRenameParams>(),+ &[(json!({"view": "a", "name": "b"}), true), (json!({"view": "a"}), false), (json!({"name": "b"}), false)],+ );+ takes(input_schema_for::<ViewDeleteParams>(), &[(json!({"view": "a"}), true), (json!({}), false), (json!({"view": 1}), false)]);+ takes(input_schema_for::<ViewListParams>(), &[(json!({}), true), (json!({"x": 1}), false)]);+ takes(+ input_schema_for::<RedefineSketchParams>(),+ &[+ (json!({"sketch": 3, "plane": "XZ"}), true),+ (+ json!({"sketch": "S", "plane": {"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "frame": "component", "offset": "2 mm", "author_path": [1]}),+ true,+ ),+ (json!({"sketch": "S", "plane": {"face": [1, 2, 3]}}), true),+ (json!({"plane": "XZ"}), false),+ (json!({"sketch": 3}), false),+ (json!({"sketch": 3, "plane": "XZ", "frame": "x"}), false),+ (json!({"sketch": 3, "plane": "XZ", "author_path": [0]}), false),+ ],+ );+}++/// Every form of the six commands, in Warn: each real reply matches its output schema and+/// carries no warning, and the replies are the JSON the handlers have always returned.+#[test]+fn view_and_redefine_replies_match_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |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!(r.get("param_warnings").is_none(), "{id} {p}: {r}");+ assert!(conforms(schema, schema, &r), "{id} {p}: {r} doesn't match {schema}");+ r+ };+ let saved = run("view.save", json!({"camera": CAMERA()}), output_schema_for::<ViewSaved>());+ assert_eq!(saved, json!({"view": "Named View1"}));+ let saved = run(+ "view.save",+ json!({"camera": {"target": [1, 2, 3], "yaw": 0, "pitch": 0.2, "distance": 9, "fov": 0.4}, "name": " Detail "}),+ output_schema_for::<ViewSaved>(),+ );+ assert_eq!(saved, json!({"view": "Detail"}));+ run("view.save", json!({"camera": CAMERA(), "name": null}), output_schema_for::<ViewSaved>());+ let listed = run("view.list", json!({}), output_schema_for::<ViewListResult>());+ assert_eq!(listed["views"].as_array().map(Vec::len), Some(3), "{listed}");+ assert_eq!(listed["views"][1]["name"], "Detail", "{listed}");+ let schema = output_schema_for::<ViewListResult>();+ let entry = &listed["views"][0];+ assert!(entry["target"].is_array() && entry["fov"] == 0.0 && entry["distance"] == 150.0, "{listed}");+ assert!(conforms(schema.as_value(), schema.as_value(), &listed));+ let renamed = run("view.rename", json!({"view": "Named View1", "name": " Overview "}), output_schema_for::<ViewRenamed>());+ assert_eq!(renamed, json!({"view": "Overview"}));+ let deleted = run("view.delete", json!({"view": "Overview"}), output_schema_for::<ViewDeleted>());+ assert_eq!(deleted, json!({"deleted": "Overview"}));+ let empty = run("view.list", json!({}), output_schema_for::<ViewListResult>());+ assert_eq!(empty["views"].as_array().map(Vec::len), Some(2), "{empty}");++ let camera = output_schema_for::<CameraReply>;+ for view in ["front", "back", "top", "iso", "home"] {+ run("view.apply", json!({"view": view}), camera());+ }+ let named = run("view.apply", json!({"view": "Detail"}), camera());+ assert!((named["camera"]["pitch"].as_f64().unwrap_or_default() - 0.2).abs() < 1e-12, "{named}");+ let turned =+ run("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80, "fov": 0.5, "roll": 1.0}}), camera());+ assert_eq!(turned["camera"]["roll"], 1.0, "{turned}");+ let clamped = run("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 1, "pitch": 0.2, "distance": 80, "roll": 100}}), camera());+ assert!((clamped["camera"]["roll"].as_f64().unwrap_or_default() - std::f64::consts::PI).abs() < 1e-12, "{clamped}");+ run("view.apply", json!({"camera": {"target": [0, 0, 0], "yaw": 0, "pitch": std::f64::consts::FRAC_PI_2, "distance": 80}}), camera());++ // Redefine Sketch: a sketch, moved to a named plane, offset, an explicit plane in each frame,+ // and a face of a body.+ let sketch = |s: &mut Session| s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"))["sketch"].clone();+ let sk = sketch(&mut s);+ let mut run = |id: &str, p: Value| {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let schema = output_schema_for::<RedefineSketchResult>();+ assert!(r.get("param_warnings").is_none(), "{id} {p}: {r}");+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id} {p}: {r}");+ assert!(r["created"].is_object(), "the session adds `created`: {r}");+ let mut r = r;+ r.as_object_mut().map(|o| o.remove("created"));+ r+ };+ let r = run("sketch.redefine", json!({"sketch": sk, "plane": "XZ"}));+ assert_eq!(r, json!({"sketch": sk, "attachment": "fixed"}));+ let r = run("sketch.redefine", json!({"sketch": sk.to_string(), "plane": "YZ", "offset": "5 mm", "frame": null}));+ assert_eq!(r, json!({"sketch": sk, "attachment": "fixed"}));+ let explicit = json!({"origin": [1, 2, 3], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]});+ let r = run("sketch.redefine", json!({"sketch": sk, "plane": explicit}));+ assert_eq!(r, json!({"sketch": sk, "attachment": "fixed", "frame": "world"}));+ let r = run("sketch.redefine", json!({"sketch": sk, "plane": explicit, "frame": "component"}));+ assert_eq!(r, json!({"sketch": sk, "attachment": "fixed", "frame": "component"}));+}++/// A face of a body that comes before the sketch: the sketch follows it, or stays where the face+/// is now with `fixed`.+#[test]+fn redefine_sketch_onto_a_face_matches_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})).unwrap_or_else(|e| panic!("{e}"));+ let sk = s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"))["sketch"].clone();+ let mut run = |p: Value| {+ let r = s.execute("sketch.redefine", &p).unwrap_or_else(|e| panic!("{p}: {e}"));+ let schema = output_schema_for::<RedefineSketchResult>();+ assert!(r.get("param_warnings").is_none() && conforms(schema.as_value(), schema.as_value(), &r), "{p}: {r}");+ r+ };+ let r = run(json!({"sketch": sk, "plane": {"face": [5, 5, 10]}}));+ assert_eq!(r["attachment"], "exact_face", "{r}");+ let r = run(json!({"sketch": sk, "plane": {"face": [5, 5, 10], "body": "Box", "index": 0, "fixed": true}}));+ assert_eq!(r["attachment"], "fixed", "{r}");+}++/// A moved component: a world plane put into it says so in `note`, which the schema describes.+#[test]+fn redefine_sketch_note_matches_the_output_schema() {+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ let part = run("component.create", json!({"name": "Part", "grounded": false}));+ let sk = run("sketch.create", json!({"plane": "XY"}))["sketch"].clone();+ run("occurrence.move", json!({"occurrence": part["occurrence"], "translate": [10, 0, 0]}));+ let r = run("sketch.redefine", json!({"sketch": sk, "plane": {"x_dir": [1, 0, 0], "y_dir": [0, 1, 0]}, "author_path": [part["occurrence"]]}));+ let schema = output_schema_for::<RedefineSketchResult>();+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{r}");+ assert!(r.get("param_warnings").is_none(), "{r}");+ assert_eq!(r["frame"], "world", "{r}");+ assert!(r["note"].as_str().is_some_and(|n| n.contains("world coordinates")), "{r}");+}++/// A misspelt key still runs in Warn, and says so, with a reply that matches; Strict refuses it.+#[test]+fn a_misspelt_key_is_reported_for_each_view_command() {+ let mut s = Session::default();+ s.execute("view.save", &json!({"camera": CAMERA(), "name": "V"})).unwrap_or_else(|e| panic!("{e}"));+ let sk = s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"))["sketch"].clone();+ s.param_check = ParamCheck::Warn;+ let cases: Vec<(&str, Value, &str, schemars::Schema)> = vec![+ ("view.apply", json!({"view": "top", "camra": 1}), "camra", output_schema_for::<CameraReply>()),+ ("view.list", json!({"view": "V"}), "view", output_schema_for::<ViewListResult>()),+ ("view.rename", json!({"view": "V", "name": "W", "nmae": 1}), "nmae", output_schema_for::<ViewRenamed>()),+ ("view.save", json!({"camera": CAMERA(), "name": "X", "nmae": 1}), "nmae", output_schema_for::<ViewSaved>()),+ ("sketch.redefine", json!({"sketch": sk, "plane": "XZ", "frme": "world"}), "frme", output_schema_for::<RedefineSketchResult>()),+ ("view.delete", json!({"view": "X", "vew": 1}), "vew", output_schema_for::<ViewDeleted>()),+ ];+ for (id, p, key, schema) in cases {+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ assert!(r["param_warnings"].to_string().contains(key), "{id}: {r}");+ assert!(conforms(schema.as_value(), schema.as_value(), &r), "{id}: {r}");+ }+ s.param_check = ParamCheck::Strict;+ let error = s.execute("view.apply", &json!({"view": "top", "camra": 1})).err().map(|e| e.to_string()).unwrap_or_default();+ assert!(error.contains("`camra`"), "{error}");+}++/// The commands run exactly as before with the check off, whatever the call (the types only+/// describe).+#[test]+fn the_view_commands_still_read_their_calls_as_before_with_the_check_off() {+ let mut s = Session::default();+ s.execute("view.save", &json!({"camera": CAMERA(), "name": 5})).unwrap_or_else(|e| panic!("{e}"));+ assert_eq!(s.execute("view.list", &json!({"x": 1})).unwrap_or_else(|e| panic!("{e}"))["views"][0]["name"], "Named View1");+ s.execute("view.apply", &json!({"view": 5, "camera": CAMERA()})).unwrap_or_else(|e| panic!("{e}"));+}diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 0056e2c3c2..6d8aac2193 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -122,7 +122,6 @@ sketch.rectangle.centersketch.rectangle.roundedsketch.rectangle.three_pointsketch.rectangle.two_point-sketch.redefinesketch.slot.arc_centersketch.slot.arc_three_pointsketch.slot.center_point@@ -182,8 +181,3 @@ timeline.rename_grouptimeline.reordertimeline.reorder_manytimeline.ungroup-view.apply-view.delete-view.list-view.rename-view.save