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 Browser folder commands and Rename Body describe their exact parameters and reply (#12276) (#12339)

PeppaWutz464da902381b
diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs
index fec2ab08bf..cbb624bd66 100644
--- a/crates/engine/src/cmd/browser.rs
+++ b/crates/engine/src/cmd/browser.rs
@@ -16,15 +16,38 @@ use solidcraft_doc::{BrowserEntry, FeatureKind, MAX_GROUP_NESTING};
use super::CommandSpec;
use super::features::{add_feature, check_expr};
use crate::params::{bad, bool_, expr, str_};
-use crate::schema::browser::{DocumentUnitsParams, DocumentUnitsResult, RepairDone, RepairFace, RepairHole, RepairParams, RepairResult, RepairSewn};
+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,
+};
use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Session};
const REPAIR_CONTRACT: TypedContract<RepairParams> = TypedContract::new();
const UNITS_CONTRACT: TypedContract<DocumentUnitsParams> = TypedContract::new();
+const RENAME_BODY_CONTRACT: TypedContract<BodyRenameParams> = TypedContract::new();
+const GROUP_CONTRACT: TypedContract<BrowserGroupParams> = TypedContract::new();
+const UNGROUP_CONTRACT: TypedContract<BrowserUngroupParams> = TypedContract::new();
+const RENAME_GROUP_CONTRACT: TypedContract<BrowserRenameGroupParams> = TypedContract::new();
+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();
+
+/// A reply as JSON: the commands here build their replies from the types their output schemas
+/// describe, so the two can't drift apart.
+fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
+}
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("body.rename", "Rename Body", rename_body).icon("rename").params("body: its name, name: the new name (features that use the body follow)"),
+ CommandSpec::new("body.rename", "Rename Body", crate::checked!("body.rename", rename_body))
+ .icon("rename")
+ .contract(&RENAME_BODY_CONTRACT)
+ .output(output_schema_for::<BodyRenamed>)
+ .params("body: its name, name: the new name (features that use the body follow)"),
// The import and failed operations offer it for a part the modelling kernel refuses.
CommandSpec::new("body.repair", "Repair Part", crate::checked!("body.repair", repair_body))
.icon("body")
@@ -36,12 +59,25 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sketch.redefine", "Redefine Sketch Plane", redefine_sketch)
.icon("plane")
.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", group)
+ CommandSpec::new("browser.group", "New Group", crate::checked!("browser.group", group))
.icon("folder")
+ .contract(&GROUP_CONTRACT)
+ .output(output_schema_for::<BrowserGroupMade>)
.params("folder?: bodies|sketches|construction; component?: id (default 0); parent?: group id (the new group nests in it, taking its component and folder; at most 8 levels); name?; items?: [keys] (they leave other groups)"),
- CommandSpec::new("browser.ungroup", "Ungroup", ungroup).icon("folder").params("group: id (its items and child groups go up to the group that holds it, or the folder)"),
- CommandSpec::new("browser.rename_group", "Rename Group", rename_group).icon("rename").params("group: id, name"),
- CommandSpec::new("browser.move", "Move Browser Items", move_items).icon("reorder")
+ CommandSpec::new("browser.ungroup", "Ungroup", crate::checked!("browser.ungroup", ungroup))
+ .icon("folder")
+ .contract(&UNGROUP_CONTRACT)
+ .output(output_schema_for::<BrowserUngrouped>)
+ .params("group: id (its items and child groups go up to the group that holds it, or the folder)"),
+ CommandSpec::new("browser.rename_group", "Rename Group", crate::checked!("browser.rename_group", rename_group))
+ .icon("rename")
+ .contract(&RENAME_GROUP_CONTRACT)
+ .output(output_schema_for::<BrowserGroupRenamed>)
+ .params("group: id, name"),
+ CommandSpec::new("browser.move", "Move Browser Items", crate::checked!("browser.move", move_items))
+ .icon("reorder")
+ .contract(&MOVE_CONTRACT)
+ .output(output_schema_for::<BrowserMoved>)
.params("folder, component?, items: [keys (strings) and group ids (numbers)]; group?: id (into it; omit for the folder's top level); before?: key or group id (position in it; default the end). A group cannot go into itself or past 8 levels"),
CommandSpec::new("document.units", "Change Design Units", crate::checked!("document.units", document_units))
.icon("settings")
@@ -57,8 +93,16 @@ pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("view.apply", "Restore Named View", view_apply).icon("camera").noundo().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", order).icon("reorder").params("folder: bodies|sketches|construction|components, component?, order: [keys (strings) and top-level group ids (numbers)] (display order; for `components`, the ids of the components placed in it)"),
- CommandSpec::new("browser.visibility", "Show/Hide", visibility).icon("eye").params(
+ CommandSpec::new("browser.order", "Order Browser Items", crate::checked!("browser.order", order))
+ .icon("reorder")
+ .contract(&ORDER_CONTRACT)
+ .output(output_schema_for::<BrowserOrdered>)
+ .params("folder: bodies|sketches|construction|components, component?, order: [keys (strings) and top-level group ids (numbers)] (display order; for `components`, the ids of the components placed in it)"),
+ CommandSpec::new("browser.visibility", "Show/Hide", crate::checked!("browser.visibility", visibility))
+ .icon("eye")
+ .contract(&VISIBILITY_CONTRACT)
+ .output(output_schema_for::<BrowserVisibilityResult>)
+ .params(
"visible: bool; items?: [sketch id or name | body name | construction name | joint name | O|X|Y|Z|XY|XZ|YZ]; \
or joints?: [joint id or name] (their glyphs; they still constrain and move parts); \
or features?: [feature id or name] (the bodies they made; path?: [occurrence ids] for only that placement's); \
@@ -66,12 +110,22 @@ pub static COMMANDS: &[CommandSpec] = &[
or tree_folders?: [browser folder or group key: c0/bodies, o:4/sketches, c0/g7, c0/joints, c0/canvases, c0/point_clouds] (the folder or group itself: its items keep their own state); \
or paths?: [[occurrence ids]] (exact placements and descendants), isolate?: bool (with paths or items of bodies, and visible:true: everything else is hidden, other placements as placements). Saved with the design and undone like any other change (the camera is not)",
),
- CommandSpec::new("browser.expand_all", "Expand All", expand_all).icon("folder").noundo().params(
+ CommandSpec::new("browser.expand_all", "Expand All", crate::checked!("browser.expand_all", expand_all))
+ .icon("folder")
+ .noundo()
+ .contract(&FOLD_CONTRACT)
+ .output(output_schema_for::<BrowserFoldResult>)
+ .params(
"path?: [occurrence ids] (that placement and its descendants); component?: id (that component's own folders); \
omit both for the whole tree, including folders that start closed (Origin, Named Views, Features). \
Display only: open/closed rows are not saved in the design and are not an undo step → open, open_by_default, closed_by_default",
),
- CommandSpec::new("browser.collapse_all", "Collapse All", collapse_all).icon("folder").noundo().params(
+ CommandSpec::new("browser.collapse_all", "Collapse All", crate::checked!("browser.collapse_all", collapse_all))
+ .icon("folder")
+ .noundo()
+ .contract(&FOLD_CONTRACT)
+ .output(output_schema_for::<BrowserFoldResult>)
+ .params(
"path?: [occurrence ids]; component?: id; omit both for the whole tree. The row it starts from (the design row for the whole tree) stays open, so its first level remains visible. \
Display only; not an undo step → open, open_by_default, closed_by_default",
),
@@ -221,7 +275,7 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
take_out(d, component, &folder, &gone);
let items = gone;
d.browser_groups.push(solidcraft_doc::BrowserGroup { id, name: name.clone(), component, folder, parent, items });
- Ok(json!({ "group": id, "name": name, "parent": parent }))
+ reply(cmd, BrowserGroupMade { group: id, name, parent, param_warnings: Vec::new() })
}
/// A group's contents go up to the group that holds it (the folder's top level for a top-level
@@ -229,7 +283,7 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {
let id = group_id(s, p, "browser.ungroup")?;
let d = s.doc_mut();
- let Some(g) = d.browser_group(id).cloned() else { return Ok(json!({ "group": id })) };
+ let Some(g) = d.browser_group(id).cloned() else { return reply("browser.ungroup", BrowserUngrouped { group: id, param_warnings: Vec::new() }) };
settle(d, g.component, &g.folder, Some(id));
settle(d, g.component, &g.folder, g.parent);
let inside = d.browser_group(id).map(|g| g.items.clone()).unwrap_or_default();
@@ -243,7 +297,7 @@ fn ungroup(s: &mut Session, p: &Value) -> Result<Value> {
}
take_out(d, g.component, &g.folder, &[BrowserEntry::Group(id)]);
d.browser_groups.retain(|x| x.id != id);
- Ok(json!({ "group": id }))
+ reply("browser.ungroup", BrowserUngrouped { group: id, param_warnings: Vec::new() })
}
fn rename_group(s: &mut Session, p: &Value) -> Result<Value> {
@@ -254,7 +308,7 @@ fn rename_group(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(g) = s.doc_mut().browser_groups.iter_mut().find(|g| g.id == id) {
g.name = name.to_string();
}
- Ok(json!({ "group": id, "name": name }))
+ reply(cmd, BrowserGroupRenamed { group: id, name: name.to_string(), param_warnings: Vec::new() })
}
fn move_items(s: &mut Session, p: &Value) -> Result<Value> {
@@ -312,7 +366,7 @@ fn move_items(s: &mut Session, p: &Value) -> Result<Value> {
let at = before.as_ref().and_then(|b| list.iter().position(|e| e == b)).unwrap_or(list.len());
list.splice(at..at, items.iter().cloned());
}
- Ok(json!({ "items": items, "group": to }))
+ reply(cmd, BrowserMoved { items, group: to, param_warnings: Vec::new() })
}
fn order(s: &mut Session, p: &Value) -> Result<Value> {
@@ -348,7 +402,7 @@ fn order(s: &mut Session, p: &Value) -> Result<Value> {
// An item that sits in a group belongs to the group's list only.
d.browser_order.insert(key, order);
}
- Ok(json!({}))
+ reply(cmd, BrowserOrdered { param_warnings: Vec::new() })
}
const ORIGIN: [&str; 7] = ["O", "X", "Y", "Z", "XY", "XZ", "YZ"];
@@ -426,7 +480,7 @@ fn shown_feature(world: &solidcraft_doc::ModelState, f: &solidcraft_doc::Feature
/// A browser folder or group key (`Visibility::hidden_folders`): `c0` or `o:<ids>`, then
/// `/bodies`, `/sketches`, `/construction`, `/joints`, `/canvases` or `/g<group id>`.
-fn tree_folder_key(k: &str) -> bool {
+pub(crate) fn tree_folder_key(k: &str) -> bool {
let Some((scope, last)) = k.rsplit_once('/') else { return false };
let scope_ok =
scope == "c0" || scope.strip_prefix("o:").is_some_and(|ids| ids.split('/').count() <= 64 && ids.split('/').all(|i| i.parse::<u64>().is_ok()));
@@ -486,7 +540,11 @@ fn isolate_bodies(s: &mut Session, p: &Value, visible: bool) -> Result<Value> {
s.visibility.hidden_occurrences = hidden;
s.visibility.hidden_bodies = hidden_bodies;
s.refresh_display();
- Ok(json!({"visible":true,"isolated":keep,"visibility":s.visibility}))
+ let visibility = VisibilityState::from(&s.visibility);
+ reply(
+ cmd,
+ BrowserVisibilityResult { visible: true, changed: None, isolated: Some(Isolated::Bodies(keep)), visibility, param_warnings: Vec::new() },
+ )
}
/// The tree keys of the Bodies folders and groups (with the groups they are in) that hold the
@@ -546,7 +604,8 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.refresh_display();
- return Ok(json!({"visible":visible,"changed":keys.len(),"visibility":s.visibility}));
+ let visibility = VisibilityState::from(&s.visibility);
+ return reply(cmd, BrowserVisibilityResult { visible, changed: Some(keys.len()), isolated: None, visibility, param_warnings: Vec::new() });
}
if let Some(value) = p.get("paths") {
if p.get("items").is_some() || p.get("folder").is_some() {
@@ -597,7 +656,17 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
s.visibility.hidden_occurrences = hidden;
s.visibility.hidden_bodies = root_bodies;
s.refresh_display();
- return Ok(json!({"visible":true,"isolated":paths,"visibility":s.visibility}));
+ let visibility = VisibilityState::from(&s.visibility);
+ return reply(
+ cmd,
+ BrowserVisibilityResult {
+ visible: true,
+ changed: None,
+ isolated: Some(Isolated::Paths(paths)),
+ visibility,
+ param_warnings: Vec::new(),
+ },
+ );
}
for path in &paths {
s.visibility.hidden_occurrences.retain(|p| p != path);
@@ -606,7 +675,8 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.refresh_display();
- return Ok(json!({"visible":visible,"changed":paths.len(),"visibility":s.visibility}));
+ let visibility = VisibilityState::from(&s.visibility);
+ return reply(cmd, BrowserVisibilityResult { visible, changed: Some(paths.len()), isolated: None, visibility, param_warnings: Vec::new() });
}
if bool_(p, "isolate").unwrap_or(false) {
return isolate_bodies(s, p, visible);
@@ -726,7 +796,8 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.refresh_display();
- Ok(json!({ "visible": visible, "changed": items.len(), "visibility": s.visibility }))
+ let visibility = VisibilityState::from(&s.visibility);
+ reply(cmd, BrowserVisibilityResult { visible, changed: Some(items.len()), isolated: None, visibility, param_warnings: Vec::new() })
}
/// Browser rows that start open (`c0`, Bodies, placements) vs closed (Origin, Features).
@@ -873,11 +944,8 @@ fn fold_tree(s: &mut Session, p: &Value, open: bool, cmd: &str) -> Result<Value>
if keys.open.len().saturating_add(keys.closed.len()) > MAX_FOLD_KEYS {
return Err(bad(cmd, "expand/collapse exceeds 10000 browser rows"));
}
- Ok(json!({
- "open": open,
- "open_by_default": keys.open.into_iter().collect::<Vec<_>>(),
- "closed_by_default": keys.closed.into_iter().collect::<Vec<_>>(),
- }))
+ let (open_by_default, closed_by_default) = (keys.open.into_iter().collect(), keys.closed.into_iter().collect());
+ reply(cmd, BrowserFoldResult { open, open_by_default, closed_by_default, param_warnings: Vec::new() })
}
fn expand_all(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1198,7 +1266,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {
let name =
str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` must be 1…128 characters"))?;
if name == old {
- return Ok(json!({"body": old, "name": name}));
+ return reply(cmd, BodyRenamed { body: old, name: name.to_string(), param_warnings: Vec::new() });
}
let previous = s.doc.clone();
let st = s.model.state();
@@ -1323,7 +1391,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {
// A sketch projecting the body in another placement of its component keeps it.
super::sketch_project::follow_placed_renames(d, &st, &placed, Some((&old, name)));
s.remember_body_rename(&previous, &old, name);
- Ok(json!({"body": old, "name": name}))
+ reply(cmd, BodyRenamed { body: old, name: name.to_string(), param_warnings: Vec::new() })
}
fn redefine_sketch(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rs
index b5085c01cb..8dd0443756 100644
--- a/crates/engine/src/cmd/mod.rs
+++ b/crates/engine/src/cmd/mod.rs
@@ -21,7 +21,7 @@ macro_rules! planned {
}
mod bom;
-mod browser;
+pub(crate) mod browser;
pub(crate) mod clearance;
mod clipboard;
mod clipboard_foreign;
diff --git a/crates/engine/src/schema/browser.rs b/crates/engine/src/schema/browser.rs
index 9b76efcffa..0d88f670a0 100644
--- a/crates/engine/src/schema/browser.rs
+++ b/crates/engine/src/schema/browser.rs
@@ -5,9 +5,12 @@ use std::borrow::Cow;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer, Serialize};
-use serde_json::Value;
+use serde_json::{Value, json};
-use super::types::{FeatureCommon, LengthExpr, feature_common};
+use solidcraft_doc::BrowserEntry;
+
+use super::check::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
/// SMLib refuses on their own are rebuilt on their own surfaces (geometry unchanged), free edges
@@ -164,6 +167,946 @@ pub struct DocumentUnitsResult {
pub param_warnings: Vec<String>,
}
+// ---- Browser folders and Rename Body (#12276) ----
+//
+// 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 group, component, placement, joint,
+// feature or body exists stays the handler's to check, and so do the keys that exclude one
+// another. A key the handler reads only as text, a number or a flag, and otherwise takes as
+// absent, is a plain optional field: the contract is the stricter of the two. A key the type
+// has optional but the handler can't do without is required in the schema (`require`), so that
+// the handler's own message, not "is required", is what a call that leaves it out gets.
+
+/// The most keys, entries or paths a browser list may name, as the handlers cap them.
+const MAX_LIST: usize = 10_000;
+/// The longest item key, in bytes.
+const MAX_KEY_BYTES: usize = 256;
+/// The deepest placement path, in occurrence ids.
+const MAX_PATH: usize = 64;
+/// The longest group or body name, in bytes.
+const MAX_NAME_BYTES: usize = 128;
+
+/// The folders the browser lists items in, which a group or a move is in.
+const FOLDERS: [&str; 3] = ["bodies", "sketches", "construction"];
+/// The folders `browser.visibility` takes whole.
+const VISIBILITY_FOLDERS: [&str; 6] = ["bodies", "sketches", "construction", "origin", "joints", "all"];
+
+/// Adds each of `keys` to the schema's `required` list.
+fn require(schema: &mut Schema, keys: &[&str]) {
+ let mut required: Vec<Value> = schema.get("required").and_then(Value::as_array).cloned().unwrap_or_default();
+ for key in keys {
+ if !required.iter().any(|k| k == key) {
+ required.push((*key).into());
+ }
+ }
+ schema.insert("required".into(), Value::Array(required));
+}
+
+fn group_required(schema: &mut Schema) {
+ require(schema, &["group"]);
+}
+
+fn group_and_name_required(schema: &mut Schema) {
+ require(schema, &["group", "name"]);
+}
+
+fn body_and_name_required(schema: &mut Schema) {
+ require(schema, &["body", "name"]);
+}
+
+fn folder_and_items_required(schema: &mut Schema) {
+ require(schema, &["folder", "items"]);
+}
+
+fn folder_required(schema: &mut Schema) {
+ require(schema, &["folder"]);
+}
+
+fn visible_required(schema: &mut Schema) {
+ require(schema, &["visible"]);
+}
+
+/// A browser group's id, as `cmd/browser.rs` reads one: a non-negative whole number.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct GroupId(pub u64);
+
+impl<'de> Deserialize<'de> for GroupId {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?.as_u64().map(GroupId).ok_or_else(|| D::Error::custom("must be a group id"))
+ }
+}
+
+impl JsonSchema for GroupId {
+ fn schema_name() -> Cow<'static, str> {
+ "GroupId".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A browser group's id (see `browser.group`).", "type": "integer", "minimum": 0})
+ }
+}
+
+/// `group` as `group_id` reads it: given, `null` included, a group id.
+fn some_group<'de, D: Deserializer<'de>>(d: D) -> Result<Option<GroupId>, D::Error> {
+ GroupId::deserialize(d).map(Some)
+}
+
+/// One of the three browser folders a group or an item list is in.
+#[derive(Clone, Debug, PartialEq)]
+pub struct BrowserFolder(pub String);
+
+impl<'de> Deserialize<'de> for BrowserFolder {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(f) if FOLDERS.contains(&f.as_str()) => Ok(BrowserFolder(f)),
+ _ => Err(D::Error::custom(whole("`folder` must be bodies, sketches or construction"))),
+ }
+ }
+}
+
+impl JsonSchema for BrowserFolder {
+ fn schema_name() -> Cow<'static, str> {
+ "BrowserFolder".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A browser folder: bodies, sketches or construction.", "type": "string", "enum": FOLDERS})
+ }
+}
+
+/// `browser.order`'s folder: one of the three, or `components`, the placed sub-components.
+#[derive(Clone, Debug, PartialEq)]
+pub struct OrderFolder(pub String);
+
+impl<'de> Deserialize<'de> for OrderFolder {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(f) if f == "components" || FOLDERS.contains(&f.as_str()) => Ok(OrderFolder(f)),
+ _ => Err(D::Error::custom(whole("`folder` must be bodies, sketches or construction"))),
+ }
+ }
+}
+
+impl JsonSchema for OrderFolder {
+ fn schema_name() -> Cow<'static, str> {
+ "OrderFolder".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "A browser folder: bodies, sketches, construction or components.",
+ "type": "string",
+ "enum": ["bodies", "sketches", "construction", "components"]
+ })
+ }
+}
+
+/// A group's name as `browser.group` reads it: surrounding spaces are cut; nothing left means
+/// the default name.
+#[derive(Clone, Debug, PartialEq)]
+pub struct GroupName(pub String);
+
+impl<'de> Deserialize<'de> for GroupName {
+ 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(GroupName(n)),
+ _ => Err(D::Error::custom("must be text")),
+ }
+ }
+}
+
+impl JsonSchema for GroupName {
+ fn schema_name() -> Cow<'static, str> {
+ "GroupName".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A name of at most 128 bytes once surrounding spaces are cut.", "type": "string"})
+ }
+}
+
+/// A name of 1 to 128 bytes once surrounding spaces are cut, as `browser.rename_group` and
+/// `body.rename` read `name`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct NewName(pub String);
+
+impl<'de> Deserialize<'de> for NewName {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(n) if !n.trim().is_empty() && n.trim().len() <= MAX_NAME_BYTES => Ok(NewName(n)),
+ _ => Err(D::Error::custom(whole("`name` must be 1…128 characters"))),
+ }
+ }
+}
+
+impl JsonSchema for NewName {
+ fn schema_name() -> Cow<'static, str> {
+ "NewName".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "Text of 1 to 128 bytes once surrounding spaces are cut.", "type": "string"})
+ }
+}
+
+/// `name` for the commands that can't do without it: given, `null` included, a [`NewName`].
+fn some_new_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<NewName>, D::Error> {
+ NewName::deserialize(d).map(Some)
+}
+
+/// The name of a body, as `body.rename` reads `body`.
+#[derive(Clone, Debug, PartialEq)]
+pub struct BodyName(pub String);
+
+impl<'de> Deserialize<'de> for BodyName {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(n) => Ok(BodyName(n)),
+ _ => Err(D::Error::custom(whole("`body` must be a body name"))),
+ }
+ }
+}
+
+impl JsonSchema for BodyName {
+ fn schema_name() -> Cow<'static, str> {
+ "BodyName".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A body's name. A placed copy's name (`KB (K:2)`) means the body it shows.", "type": "string"})
+ }
+}
+
+fn some_body<'de, D: Deserializer<'de>>(d: D) -> Result<Option<BodyName>, D::Error> {
+ BodyName::deserialize(d).map(Some)
+}
+
+/// What `entries` in `cmd/browser.rs` reads of a list of groups (numbers) and item keys
+/// (strings): at most 10000, no key empty or over 256 bytes. `key` names the parameter in the
+/// messages.
+fn browser_entries(value: Value, key: &str) -> Result<Vec<BrowserEntry>, String> {
+ let list = match value {
+ Value::Array(a) => a
+ .into_iter()
+ .map(|x| match x {
+ Value::String(s) => Some(BrowserEntry::Item(s)),
+ _ => x.as_u64().map(BrowserEntry::Group),
+ })
+ .collect::<Option<Vec<_>>>(),
+ _ => None,
+ };
+ let list = list.ok_or_else(|| whole(format!("`{key}` must be a list of item keys (strings) and group ids (numbers)")))?;
+ if list.len() > MAX_LIST || list.iter().any(|e| e.as_item().is_some_and(|k| k.is_empty() || k.len() > MAX_KEY_BYTES)) {
+ return Err(whole(format!("`{key}` has bad keys")));
+ }
+ Ok(list)
+}
+
+/// `browser.move`'s `items`: item keys and group ids, at least one.
+#[derive(Clone, Debug, PartialEq)]
+pub struct MovedEntries(pub Vec<BrowserEntry>);
+
+impl<'de> Deserialize<'de> for MovedEntries {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let list = browser_entries(Value::deserialize(d)?, "items").map_err(D::Error::custom)?;
+ if list.is_empty() { Err(D::Error::custom(whole("`items` must list item keys or group ids"))) } else { Ok(MovedEntries(list)) }
+ }
+}
+
+/// `browser.order`'s `order`: item keys and top-level group ids, in display order; none clears
+/// the folder's order.
+#[derive(Clone, Debug, PartialEq)]
+pub struct OrderEntries(pub Vec<BrowserEntry>);
+
+impl<'de> Deserialize<'de> for OrderEntries {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ browser_entries(Value::deserialize(d)?, "order").map(OrderEntries).map_err(D::Error::custom)
+ }
+}
+
+/// `browser.group`'s `items`: item keys, no group ids.
+#[derive(Clone, Debug, PartialEq)]
+pub struct GroupedItems(pub Vec<BrowserEntry>);
+
+impl<'de> Deserialize<'de> for GroupedItems {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let list = browser_entries(Value::deserialize(d)?, "items").map_err(D::Error::custom)?;
+ if list.iter().any(|e| e.as_item().is_none()) {
+ Err(D::Error::custom(whole("`items` are item keys: move groups with browser.move")))
+ } else {
+ Ok(GroupedItems(list))
+ }
+ }
+}
+
+fn entries_schema(description: &str, group_ids: bool, min_items: u32) -> Schema {
+ let item = json!({"type": "string", "minLength": 1, "maxLength": MAX_KEY_BYTES});
+ let entry = if group_ids { json!({"anyOf": [item, {"type": "integer", "minimum": 0}]}) } else { item };
+ json_schema!({"description": description, "type": "array", "items": entry, "minItems": min_items, "maxItems": MAX_LIST})
+}
+
+impl JsonSchema for MovedEntries {
+ fn schema_name() -> Cow<'static, str> {
+ "MovedEntries".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ entries_schema("Item keys (strings) and group ids (numbers); a number is always a group.", true, 1)
+ }
+}
+
+impl JsonSchema for OrderEntries {
+ fn schema_name() -> Cow<'static, str> {
+ "OrderEntries".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ entries_schema("Item keys (strings) and top-level group ids (numbers); a number is always a group.", true, 0)
+ }
+}
+
+impl JsonSchema for GroupedItems {
+ fn schema_name() -> Cow<'static, str> {
+ "GroupedItems".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ entries_schema("Item keys (strings).", false, 0)
+ }
+}
+
+/// Where `browser.move` puts items: before an item key or a group id.
+#[derive(Clone, Debug, PartialEq)]
+pub struct BeforeEntry(pub BrowserEntry);
+
+impl<'de> Deserialize<'de> for BeforeEntry {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(k) => Ok(BeforeEntry(BrowserEntry::Item(k))),
+ v => v.as_u64().map(|id| BeforeEntry(BrowserEntry::Group(id))).ok_or_else(|| D::Error::custom("must be an item key or a group id")),
+ }
+ }
+}
+
+impl JsonSchema for BeforeEntry {
+ fn schema_name() -> Cow<'static, str> {
+ "BeforeEntry".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "An item key (text) or a group id (a number).", "anyOf": [{"type": "string"}, {"type": "integer", "minimum": 0}]})
+ }
+}
+
+/// An item key or a group id in a reply.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum EntryKey {
+ /// A group, by id.
+ Group(u64),
+ /// An item, by key.
+ Item(String),
+}
+
+/// Make a group in a Browser folder, of the items given or empty. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct BrowserGroupParams {
+ /// The folder: bodies, sketches or construction. Needed unless `parent` gives it.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "BrowserFolder")]
+ pub folder: Option<BrowserFolder>,
+ /// The component whose folder it is. Default: 0, the design.
+ #[serde(default)]
+ pub component: Option<u64>,
+ /// The group the new one nests in, which gives it its component and folder (at most 8
+ /// levels).
+ #[serde(default)]
+ pub parent: Option<GroupId>,
+ /// The group's name, at most 128 bytes. Default: "Group" and the next number in the folder.
+ #[serde(default)]
+ pub name: Option<GroupName>,
+ /// The items to put in it, by key; they leave the other groups they were in.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "GroupedItems")]
+ pub items: Option<GroupedItems>,
+}
+
+/// What `browser.group` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BrowserGroupMade {
+ /// The new group's id.
+ pub group: u64,
+ pub name: String,
+ /// The group it is in, or `null` at the folder's top level.
+ pub parent: Option<u64>,
+ /// 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>,
+}
+
+/// Remove a group: its items and child groups go up to the group that holds it, or the folder,
+/// in the place the group had. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = group_required)]
+pub struct BrowserUngroupParams {
+ // Required in the schema (`group_required`), optional in the type: left out, the handler
+ // refuses it with its own message.
+ #[serde(default, deserialize_with = "some_group", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "GroupId")]
+ pub group: Option<GroupId>,
+}
+
+/// What `browser.ungroup` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BrowserUngrouped {
+ /// The group that is gone.
+ pub group: u64,
+ /// 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 Browser group. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = group_and_name_required)]
+pub struct BrowserRenameGroupParams {
+ #[serde(default, deserialize_with = "some_group", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "GroupId")]
+ pub group: Option<GroupId>,
+ /// The new name, 1 to 128 characters once surrounding spaces are cut.
+ #[serde(default, deserialize_with = "some_new_name", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "NewName")]
+ pub name: Option<NewName>,
+}
+
+/// What `browser.rename_group` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BrowserGroupRenamed {
+ pub group: u64,
+ /// The name now, without surrounding spaces.
+ pub name: 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>,
+}
+
+/// Move items and groups in a Browser folder: into a group or to the folder's top level, before
+/// an item or group or at the end. A group can't go into itself or past 8 levels. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = folder_and_items_required)]
+pub struct BrowserMoveParams {
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "BrowserFolder")]
+ pub folder: Option<BrowserFolder>,
+ /// The component whose folder it is. Default: 0, the design.
+ #[serde(default)]
+ pub component: Option<u64>,
+ /// What to move: item keys (strings) and group ids (numbers), at least one.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "MovedEntries")]
+ pub items: Option<MovedEntries>,
+ /// The group to move them into. Default: the folder's top level.
+ #[serde(default)]
+ pub group: Option<GroupId>,
+ /// Put them before this item key or group id, in the list they go into. Default: the end.
+ #[serde(default)]
+ pub before: Option<BeforeEntry>,
+}
+
+/// What `browser.move` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BrowserMoved {
+ /// What was moved, as given.
+ #[schemars(with = "Vec<EntryKey>")]
+ pub items: Vec<BrowserEntry>,
+ /// The group they went into, or `null` for the folder's top level.
+ pub group: Option<u64>,
+ /// 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>,
+}
+
+/// Set the display order of a Browser folder. An item that sits in a group belongs to the
+/// group's list only. One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = folder_required)]
+pub struct BrowserOrderParams {
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OrderFolder")]
+ pub folder: Option<OrderFolder>,
+ /// The component whose folder it is. Default: 0, the design.
+ #[serde(default)]
+ pub component: Option<u64>,
+ /// The display order: item keys (strings) and top-level group ids (numbers); for
+ /// `components`, the ids of the components placed in it. Empty or left out: the folder goes
+ /// back to its default order.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "OrderEntries")]
+ pub order: Option<OrderEntries>,
+}
+
+/// What `browser.order` returns: nothing but the warnings.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BrowserOrdered {
+ /// 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 list of item keys (strings, or numbers read as text), as `keys` in `cmd/browser.rs` reads
+/// one: at most 10000, no key empty or over 256 bytes.
+fn item_keys(value: Value, key: &str) -> Result<Vec<Value>, String> {
+ let list = match value {
+ Value::Array(a) if a.iter().all(|x| x.is_string() || x.as_u64().is_some()) => a,
+ _ => return Err(whole(format!("`{key}` must be a list of item keys"))),
+ };
+ let bad_key = |x: &Value| x.as_str().is_some_and(|k| k.is_empty() || k.len() > MAX_KEY_BYTES);
+ if list.len() > MAX_LIST || list.iter().any(bad_key) { Err(whole(format!("`{key}` has bad keys"))) } else { Ok(list) }
+}
+
+/// `browser.visibility`'s `items`: sketches, bodies, construction items, joints or origin items.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ShownItems(pub Vec<Value>);
+
+impl<'de> Deserialize<'de> for ShownItems {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ item_keys(Value::deserialize(d)?, "items").map(ShownItems).map_err(D::Error::custom)
+ }
+}
+
+/// `browser.visibility`'s `features`: feature ids or names.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ShownFeatures(pub Vec<Value>);
+
+impl<'de> Deserialize<'de> for ShownFeatures {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ item_keys(Value::deserialize(d)?, "features").map(ShownFeatures).map_err(D::Error::custom)
+ }
+}
+
+fn keys_schema(description: &str) -> Schema {
+ json_schema!({
+ "description": description,
+ "type": "array",
+ "items": {"anyOf": [{"type": "string", "minLength": 1, "maxLength": MAX_KEY_BYTES}, {"type": "integer", "minimum": 0}]},
+ "maxItems": MAX_LIST
+ })
+}
+
+impl JsonSchema for ShownItems {
+ fn schema_name() -> Cow<'static, str> {
+ "ShownItems".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ keys_schema("Sketches (id or name), bodies, construction items, joints or origin items (O, X, Y, Z, XY, XZ, YZ), by name.")
+ }
+}
+
+impl JsonSchema for ShownFeatures {
+ fn schema_name() -> Cow<'static, str> {
+ "ShownFeatures".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ keys_schema("Feature ids or names.")
+ }
+}
+
+/// `browser.visibility`'s `joints`: one to 10000 joint ids or names.
+#[derive(Clone, Debug, PartialEq)]
+pub struct ShownJoints(pub Vec<Value>);
+
+impl<'de> Deserialize<'de> for ShownJoints {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let list = match Value::deserialize(d)? {
+ Value::Array(a) if !a.is_empty() && a.len() <= MAX_LIST => a,
+ _ => return Err(D::Error::custom(whole("`joints` must list 1..10000 joint ids or names"))),
+ };
+ if list.iter().all(|j| j.is_number() || j.is_string()) {
+ Ok(ShownJoints(list))
+ } else {
+ Err(D::Error::custom(whole("`joint` must be an id or a name")))
+ }
+ }
+}
+
+impl JsonSchema for ShownJoints {
+ fn schema_name() -> Cow<'static, str> {
+ "ShownJoints".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Joint ids (numbers) or names.",
+ "type": "array",
+ "items": {"type": ["number", "string"]},
+ "minItems": 1,
+ "maxItems": MAX_LIST
+ })
+ }
+}
+
+/// A placement's path, occurrence ids from the outermost down, as the handlers read one: `min`
+/// to 64 whole numbers.
+fn occurrence_ids(value: &Value, min: usize) -> Option<Vec<u64>> {
+ value.as_array().filter(|a| a.len() >= min && a.len() <= MAX_PATH).and_then(|a| a.iter().map(Value::as_u64).collect::<Option<Vec<_>>>())
+}
+
+fn path_schema(description: &str, min_items: u32) -> Schema {
+ json_schema!({"description": description, "type": "array", "items": {"type": "integer", "minimum": 0}, "minItems": min_items, "maxItems": MAX_PATH})
+}
+
+/// The path of one placement for `browser.visibility`'s `path`: at most 64 occurrence ids.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PlacementPath(pub Vec<u64>);
+
+impl<'de> Deserialize<'de> for PlacementPath {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ occurrence_ids(&Value::deserialize(d)?, 0)
+ .map(PlacementPath)
+ .ok_or_else(|| D::Error::custom(whole("`path` must list at most 64 occurrence ids")))
+ }
+}
+
+impl JsonSchema for PlacementPath {
+ fn schema_name() -> Cow<'static, str> {
+ "PlacementPath".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ path_schema("A placement, by the occurrence ids from the design down.", 0)
+ }
+}
+
+/// `browser.expand_all` and `browser.collapse_all`'s `path`: 1 to 64 occurrence ids.
+#[derive(Clone, Debug, PartialEq)]
+pub struct FoldPath(pub Vec<u64>);
+
+impl<'de> Deserialize<'de> for FoldPath {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ occurrence_ids(&Value::deserialize(d)?, 1).map(FoldPath).ok_or_else(|| D::Error::custom(whole("`path` must list 1..64 occurrence ids")))
+ }
+}
+
+impl JsonSchema for FoldPath {
+ fn schema_name() -> Cow<'static, str> {
+ "FoldPath".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ path_schema("A placement, by the occurrence ids from the design down.", 1)
+ }
+}
+
+/// `browser.visibility`'s `paths`: one to 10000 placements, each 1 to 64 occurrence ids.
+#[derive(Clone, Debug, PartialEq)]
+pub struct PlacementPaths(pub Vec<Vec<u64>>);
+
+impl<'de> Deserialize<'de> for PlacementPaths {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let list = match Value::deserialize(d)? {
+ Value::Array(a) if !a.is_empty() && a.len() <= MAX_LIST => a,
+ _ => return Err(D::Error::custom(whole("paths must list 1..10000 occurrence paths"))),
+ };
+ list.iter()
+ .map(|p| occurrence_ids(p, 1))
+ .collect::<Option<Vec<_>>>()
+ .map(PlacementPaths)
+ .ok_or_else(|| D::Error::custom(whole("each path must list 1..64 occurrence ids")))
+ }
+}
+
+impl JsonSchema for PlacementPaths {
+ fn schema_name() -> Cow<'static, str> {
+ "PlacementPaths".into()
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Placements, each by the occurrence ids from the design down; each with its descendants.",
+ "type": "array",
+ "items": generator.subschema_for::<FoldPath>(),
+ "minItems": 1,
+ "maxItems": MAX_LIST
+ })
+ }
+}
+
+/// A browser folder or group key, as `tree_folder_key` reads one.
+#[derive(Clone, Debug, PartialEq)]
+pub struct TreeFolderKeys(pub Vec<String>);
+
+impl<'de> Deserialize<'de> for TreeFolderKeys {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ let list = match Value::deserialize(d)? {
+ Value::Array(a) if !a.is_empty() && a.len() <= MAX_LIST => a,
+ _ => return Err(D::Error::custom(whole("`tree_folders` must list 1..10000 browser folder or group keys"))),
+ };
+ list.into_iter()
+ .map(|k| match k {
+ Value::String(k) if crate::cmd::browser::tree_folder_key(&k) => Some(k),
+ _ => None,
+ })
+ .collect::<Option<Vec<_>>>()
+ .map(TreeFolderKeys)
+ .ok_or_else(|| {
+ D::Error::custom(whole("a browser folder or group key is `<c0 | o:ids>/<folder | g<group id>>`, such as `c0/bodies` or `o:4/g7`"))
+ })
+ }
+}
+
+impl JsonSchema for TreeFolderKeys {
+ fn schema_name() -> Cow<'static, str> {
+ "TreeFolderKeys".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({
+ "description": "Browser folder or group keys: `c0` (the design) or `o:` and the placement's occurrence ids joined by `/`, then `/bodies`, `/sketches`, `/construction`, `/joints`, `/canvases`, `/point_clouds` or `/g` and a group id.",
+ "type": "array",
+ "items": {"type": "string", "maxLength": 2048},
+ "minItems": 1,
+ "maxItems": MAX_LIST
+ })
+ }
+}
+
+/// A folder `browser.visibility` shows or hides whole.
+#[derive(Clone, Debug, PartialEq)]
+pub struct VisibilityFolder(pub String);
+
+impl<'de> Deserialize<'de> for VisibilityFolder {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(f) if VISIBILITY_FOLDERS.contains(&f.as_str()) => Ok(VisibilityFolder(f)),
+ Value::String(f) => Err(D::Error::custom(whole(format!("unknown folder `{f}` (bodies, sketches, construction, origin, joints, all)")))),
+ _ => Err(D::Error::custom("must be bodies, sketches, construction, origin, joints or all")),
+ }
+ }
+}
+
+impl JsonSchema for VisibilityFolder {
+ fn schema_name() -> Cow<'static, str> {
+ "VisibilityFolder".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A folder, whole: bodies, sketches, construction, origin, joints or all.", "type": "string", "enum": VISIBILITY_FOLDERS})
+ }
+}
+
+/// `visible`: true or false.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct Visible(pub bool);
+
+impl<'de> Deserialize<'de> for Visible {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ match Value::deserialize(d)? {
+ Value::Bool(b) => Ok(Visible(b)),
+ _ => Err(D::Error::custom(whole("`visible` must be true or false"))),
+ }
+ }
+}
+
+impl JsonSchema for Visible {
+ fn schema_name() -> Cow<'static, str> {
+ "Visible".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "true to show, false to hide.", "type": "boolean"})
+ }
+}
+
+fn some_visible<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Visible>, D::Error> {
+ Visible::deserialize(d).map(Some)
+}
+
+/// Show or hide what is in the Browser: name one kind of target (`items`, `joints`, `features`,
+/// `folder`, `tree_folders` or `paths`). Saved with the design and undone like any other
+/// change; the camera is not. With `isolate`, everything else is hidden.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = visible_required)]
+pub struct BrowserVisibilityParams {
+ // Required in the schema (`visible_required`), optional in the type, as `group` above.
+ #[serde(default, deserialize_with = "some_visible", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "Visible")]
+ pub visible: Option<Visible>,
+ /// Sketches, bodies, construction items, joints or origin items, by key. With `isolate` and
+ /// `visible: true`: the bodies to keep.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ShownItems")]
+ pub items: Option<ShownItems>,
+ /// Joints, by id or name: their glyphs (they still constrain and move parts).
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ShownJoints")]
+ pub joints: Option<ShownJoints>,
+ /// Features, by id or name: the bodies they made. Sketches go in `items`.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "ShownFeatures")]
+ pub features: Option<ShownFeatures>,
+ /// With `features`: only the bodies of this placement, which must be one of the features'
+ /// component.
+ #[serde(default)]
+ pub path: Option<PlacementPath>,
+ /// All of a kind: bodies, sketches, construction, origin, joints or all. Showing also shows
+ /// the browser folders and groups that hold it, and `all` takes in the occurrence hides.
+ #[serde(default)]
+ pub folder: Option<VisibilityFolder>,
+ /// The folders or groups themselves, by tree key; their items keep their own state.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "TreeFolderKeys")]
+ pub tree_folders: Option<TreeFolderKeys>,
+ /// Exact placements and their descendants, each by its occurrence ids.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "PlacementPaths")]
+ pub paths: Option<PlacementPaths>,
+ /// With `paths`, or `items` of bodies, and `visible: true`: show only those and hide
+ /// everything else, other placements as placements. Default: false.
+ #[serde(default)]
+ pub isolate: Option<bool>,
+}
+
+/// What the browser hides and shows, as the design saves it.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct VisibilityState {
+ /// Bodies hidden, by name.
+ pub hidden_bodies: Vec<String>,
+ /// Placements hidden with all their descendants, by occurrence path.
+ pub hidden_occurrences: Vec<Vec<u64>>,
+ /// Origin items and construction geometry hidden, by name.
+ pub hidden_origin: Vec<String>,
+ /// Sketches hidden, by feature id.
+ pub hidden_sketches: Vec<u64>,
+ /// Finished sketches shown although a feature uses them, by feature id.
+ pub shown_sketches: Vec<u64>,
+ /// Joints whose glyphs are hidden, by id. Present when there are any.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub hidden_joints: Vec<u64>,
+ /// Whether the Origin folder is hidden. Present when set.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub origin_hidden: Option<bool>,
+ /// Sketches whose closed profiles are not shaded, by feature id. Present when there are any.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub hidden_profiles: Vec<u64>,
+ /// Sketches whose dimensions are shown, by feature id. Present when there are any.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub shown_dimensions: Vec<u64>,
+ /// Bodies locked in the browser, by name. Present when there are any.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub locked_bodies: Vec<String>,
+ /// Browser folders and groups hidden themselves, by tree key. Present when there are any.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub hidden_folders: Vec<String>,
+}
+
+impl From<&solidcraft_doc::Visibility> for VisibilityState {
+ fn from(v: &solidcraft_doc::Visibility) -> Self {
+ VisibilityState {
+ hidden_bodies: v.hidden_bodies.clone(),
+ hidden_occurrences: v.hidden_occurrences.clone(),
+ hidden_origin: v.hidden_origin.clone(),
+ hidden_sketches: v.hidden_sketches.clone(),
+ shown_sketches: v.shown_sketches.clone(),
+ hidden_joints: v.hidden_joints.clone(),
+ origin_hidden: v.origin_hidden,
+ hidden_profiles: v.hidden_profiles.clone(),
+ shown_dimensions: v.shown_dimensions.clone(),
+ locked_bodies: v.locked_bodies.clone(),
+ hidden_folders: v.hidden_folders.clone(),
+ }
+ }
+}
+
+/// What an isolate kept.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum Isolated {
+ /// The bodies kept, by name (`items`).
+ Bodies(Vec<String>),
+ /// The placements kept, by occurrence path (`paths`).
+ Paths(Vec<Vec<u64>>),
+}
+
+/// What `browser.visibility` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BrowserVisibilityResult {
+ /// What was asked for.
+ pub visible: bool,
+ /// How many targets were changed. Not given by an isolate.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub changed: Option<usize>,
+ /// What an isolate kept. Only given by an isolate.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub isolated: Option<Isolated>,
+ /// What is hidden and shown now.
+ pub visibility: VisibilityState,
+ /// 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 component id `browser.expand_all` and `browser.collapse_all` read: a whole number.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct FoldComponent(pub u64);
+
+impl<'de> Deserialize<'de> for FoldComponent {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ Value::deserialize(d)?.as_u64().map(FoldComponent).ok_or_else(|| D::Error::custom(whole("`component` must be a component id")))
+ }
+}
+
+impl JsonSchema for FoldComponent {
+ fn schema_name() -> Cow<'static, str> {
+ "FoldComponent".into()
+ }
+ fn json_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"description": "A component's id; 0 is the design.", "type": "integer", "minimum": 0})
+ }
+}
+
+/// Open every row of the Browser below a row (`browser.expand_all`) or close them, the row
+/// itself staying open (`browser.collapse_all`). Display only: not saved with the design and not
+/// an undo step. Give `path` or `component`, not both; neither takes the whole tree.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct BrowserFoldParams {
+ /// A placement and its descendants, by occurrence ids (1 to 64).
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "FoldPath")]
+ pub path: Option<FoldPath>,
+ /// A component's own folders; 0 is the whole tree.
+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "FoldComponent")]
+ pub component: Option<FoldComponent>,
+}
+
+/// What `browser.expand_all` and `browser.collapse_all` return: which Browser rows start open
+/// and which closed.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BrowserFoldResult {
+ /// True after `browser.expand_all`, false after `browser.collapse_all`.
+ pub open: bool,
+ /// Tree keys of the rows that start open, sorted.
+ pub open_by_default: Vec<String>,
+ /// Tree keys of the rows that start closed (Origin, Named Views, Features…), sorted.
+ pub closed_by_default: 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>,
+}
+
+/// Rename a body; the features that use it follow. A placed copy's name means the body it shows.
+/// One undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = body_and_name_required)]
+pub struct BodyRenameParams {
+ // Required in the schema (`body_and_name_required`), optional in the type, as `group` above.
+ #[serde(default, deserialize_with = "some_body", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "BodyName")]
+ pub body: Option<BodyName>,
+ /// The new name, 1 to 128 characters once surrounding spaces are cut; no other body may have it.
+ #[serde(default, deserialize_with = "some_new_name", skip_serializing_if = "Option::is_none")]
+ #[schemars(with = "NewName")]
+ pub name: Option<NewName>,
+}
+
+/// What `body.rename` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct BodyRenamed {
+ /// The body's name before (the body a placed copy's name shows).
+ pub body: String,
+ /// Its name now, without surrounding spaces.
+ pub name: 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 = "browser_tests.rs"]
mod tests;
diff --git a/crates/engine/src/schema/browser_tests.rs b/crates/engine/src/schema/browser_tests.rs
index 07ba23de77..38ccbbaebd 100644
--- a/crates/engine/src/schema/browser_tests.rs
+++ b/crates/engine/src/schema/browser_tests.rs
@@ -1,6 +1,10 @@
use serde_json::{Value, json};
-use super::{DocumentUnitsParams, DocumentUnitsResult, RepairParams, RepairResult};
+use super::{
+ BodyRenameParams, BodyRenamed, BrowserFoldParams, BrowserFoldResult, BrowserGroupMade, BrowserGroupParams, BrowserGroupRenamed,
+ BrowserMoveParams, BrowserMoved, BrowserOrderParams, BrowserOrdered, BrowserRenameGroupParams, BrowserUngroupParams, BrowserUngrouped,
+ BrowserVisibilityParams, BrowserVisibilityResult, DocumentUnitsParams, DocumentUnitsResult, RepairParams, RepairResult, VisibilityState,
+};
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};
@@ -66,3 +70,263 @@ fn the_reply_names_the_parameters_kept_in_the_old_unit() {
assert!(conforms(schema.as_value(), schema.as_value(), &reply), "{reply}");
assert_eq!(reply["kept"], json!(["w"]), "{reply}");
}
+
+#[test]
+fn browser_schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<BodyRenameParams>(), &["body", "name"]);
+ assert_keys(input_schema_for::<BrowserGroupParams>(), &["component", "folder", "items", "name", "parent"]);
+ assert_keys(input_schema_for::<BrowserUngroupParams>(), &["group"]);
+ assert_keys(input_schema_for::<BrowserRenameGroupParams>(), &["group", "name"]);
+ assert_keys(input_schema_for::<BrowserMoveParams>(), &["before", "component", "folder", "group", "items"]);
+ assert_keys(input_schema_for::<BrowserOrderParams>(), &["component", "folder", "order"]);
+ assert_keys(
+ input_schema_for::<BrowserVisibilityParams>(),
+ &["features", "folder", "isolate", "items", "joints", "path", "paths", "tree_folders", "visible"],
+ );
+ assert_keys(input_schema_for::<BrowserFoldParams>(), &["component", "path"]);
+}
+
+/// Each call has one problem the handler already refuses: strict gives its message. (A missing
+/// key is left to the handler, so the message is the handler's too.)
+#[test]
+fn browser_strict_keeps_todays_errors() {
+ let long = "n".repeat(129);
+ let deep: Vec<u64> = (1..=65).collect();
+ assert_strict_keeps_todays_errors(&[
+ ("body.rename", json!({})),
+ ("body.rename", json!({"body": 5, "name": "X"})),
+ ("body.rename", json!({"body": null, "name": "X"})),
+ ("browser.group", json!({})),
+ ("browser.group", json!({"folder": "components"})),
+ ("browser.group", json!({"folder": null})),
+ ("browser.group", json!({"folder": "bodies", "parent": "x"})),
+ ("browser.group", json!({"folder": "bodies", "name": long})),
+ ("browser.group", json!({"folder": "bodies", "items": [1]})),
+ ("browser.group", json!({"folder": "bodies", "items": "A"})),
+ ("browser.group", json!({"folder": "bodies", "items": null})),
+ ("browser.group", json!({"folder": "bodies", "items": [""]})),
+ ("browser.group", json!({"folder": "bodies", "items": [true]})),
+ ("browser.move", json!({"folder": "bodies", "items": vec!["A"; 10_001]})),
+ ("browser.move", json!({"folder": "bodies", "items": ["k".repeat(257)]})),
+ ("browser.order", json!({"folder": "bodies", "order": vec!["A"; 10_001]})),
+ ("browser.ungroup", json!({})),
+ ("browser.ungroup", json!({"group": "g"})),
+ ("browser.ungroup", json!({"group": null})),
+ ("browser.ungroup", json!({"group": 99})),
+ ("browser.rename_group", json!({})),
+ ("browser.rename_group", json!({"group": -1, "name": "x"})),
+ ("browser.move", json!({})),
+ ("browser.move", json!({"folder": "bodies"})),
+ ("browser.move", json!({"folder": "bodies", "items": []})),
+ ("browser.move", json!({"folder": "bodies", "items": [true]})),
+ ("browser.move", json!({"folder": "bodies", "items": [""]})),
+ ("browser.move", json!({"folder": "bodies", "items": "A"})),
+ ("browser.move", json!({"folder": "bodies", "items": ["A"], "group": "g"})),
+ ("browser.move", json!({"folder": "bodies", "items": ["A"], "before": true})),
+ ("browser.move", json!({"folder": "origin", "items": ["A"]})),
+ ("browser.order", json!({})),
+ ("browser.order", json!({"folder": "origin"})),
+ ("browser.order", json!({"folder": "bodies", "order": null})),
+ ("browser.order", json!({"folder": "bodies", "order": [true]})),
+ ("browser.order", json!({"folder": "bodies", "order": ["A", ""]})),
+ ("browser.visibility", json!({})),
+ ("browser.visibility", json!({"visible": "yes"})),
+ ("browser.visibility", json!({"visible": true})),
+ ("browser.visibility", json!({"visible": true, "tree_folders": []})),
+ ("browser.visibility", json!({"visible": true, "tree_folders": ["bodies"]})),
+ ("browser.visibility", json!({"visible": true, "tree_folders": [3]})),
+ ("browser.visibility", json!({"visible": true, "paths": []})),
+ ("browser.visibility", json!({"visible": true, "paths": [[]]})),
+ ("browser.visibility", json!({"visible": true, "paths": [["a"]]})),
+ ("browser.visibility", json!({"visible": true, "paths": [deep]})),
+ ("browser.visibility", json!({"visible": true, "joints": []})),
+ ("browser.visibility", json!({"visible": true, "joints": [true]})),
+ ("browser.visibility", json!({"visible": true, "folder": "nowhere"})),
+ ("browser.visibility", json!({"visible": true, "items": "A"})),
+ ("browser.visibility", json!({"visible": true, "items": null})),
+ ("browser.visibility", json!({"visible": true, "items": [""]})),
+ ("browser.visibility", json!({"visible": true, "items": []})),
+ ("browser.visibility", json!({"visible": true, "features": [true]})),
+ ("browser.expand_all", json!({"path": []})),
+ ("browser.expand_all", json!({"path": null})),
+ ("browser.expand_all", json!({"path": "o:1"})),
+ ("browser.expand_all", json!({"path": [1, "a"]})),
+ ("browser.expand_all", json!({"component": "root"})),
+ ("browser.collapse_all", json!({"component": null})),
+ ("browser.collapse_all", json!({"component": -1})),
+ ("browser.collapse_all", json!({"path": deep})),
+ ]);
+}
+
+/// The same, for the keys that need a body or a group to get as far as their message.
+#[test]
+fn browser_strict_keeps_todays_errors_for_names() {
+ let long = "n".repeat(129);
+ let cases = [
+ ("body.rename", json!({"body": "Box", "name": ""})),
+ ("body.rename", json!({"body": "Box", "name": " "})),
+ ("body.rename", json!({"body": "Box", "name": 5})),
+ ("body.rename", json!({"body": "Box", "name": null})),
+ ("body.rename", json!({"body": "Box", "name": long})),
+ ("body.rename", json!({"body": "Box"})),
+ ("browser.rename_group", json!({"group": "@g", "name": ""})),
+ ("browser.rename_group", json!({"group": "@g", "name": 5})),
+ ("browser.rename_group", json!({"group": "@g", "name": long})),
+ ("browser.rename_group", json!({"group": "@g"})),
+ ("browser.group", json!({"parent": "@g", "folder": "sketches"})),
+ ("browser.group", json!({"parent": "@g", "folder": null})),
+ ("browser.group", json!({"folder": "bodies", "parent": 77})),
+ ("browser.move", json!({"folder": "bodies", "items": ["Box"], "before": 77})),
+ ];
+ for (id, p) in cases {
+ let run = |level: ParamCheck| {
+ let mut s = Session { param_check: level, ..Session::default() };
+ s.execute("solid.box", &json!({"length": 10, "width": 10, "height": 10, "body_name": "Box"})).unwrap();
+ let g = s.execute("browser.group", &json!({"folder": "bodies", "name": "G"})).unwrap()["group"].clone();
+ let p: Value = serde_json::from_str(&p.to_string().replace("\"@g\"", &g.to_string())).unwrap();
+ 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}");
+ }
+}
+
+/// The contracts say what the handlers need: the keys that can't be left out are required, an
+/// order may be left out, and a folder is one the handler takes.
+#[test]
+fn the_browser_schemas_take_what_the_handlers_read() {
+ let required = |schema: schemars::Schema| {
+ let v = schema.as_value();
+ let mut r: Vec<String> =
+ v.get("required").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(String::from).collect();
+ r.sort();
+ r
+ };
+ assert_eq!(required(input_schema_for::<BodyRenameParams>()), ["body", "name"]);
+ assert_eq!(required(input_schema_for::<BrowserGroupParams>()), Vec::<String>::new());
+ assert_eq!(required(input_schema_for::<BrowserUngroupParams>()), ["group"]);
+ assert_eq!(required(input_schema_for::<BrowserRenameGroupParams>()), ["group", "name"]);
+ assert_eq!(required(input_schema_for::<BrowserMoveParams>()), ["folder", "items"]);
+ assert_eq!(required(input_schema_for::<BrowserOrderParams>()), ["folder"]);
+ assert_eq!(required(input_schema_for::<BrowserVisibilityParams>()), ["visible"]);
+ assert_eq!(required(input_schema_for::<BrowserFoldParams>()), Vec::<String>::new());
+ let mv = input_schema_for::<BrowserMoveParams>();
+ let mv = mv.as_value();
+ for (p, takes) in [
+ (json!({"folder": "bodies", "items": ["A", 3], "group": 3, "before": "B"}), true),
+ (json!({"folder": "bodies", "items": []}), false),
+ (json!({"folder": "origin", "items": ["A"]}), false),
+ (json!({"items": ["A"]}), false),
+ ] {
+ assert_eq!(conforms(mv, mv, &p), takes, "{p}");
+ }
+ let order = input_schema_for::<BrowserOrderParams>();
+ let order = order.as_value();
+ assert!(conforms(order, order, &json!({"folder": "components", "order": []})));
+}
+
+/// The typed visibility has the keys the saved one has, with every field set.
+#[test]
+fn the_visibility_reply_type_matches_the_design_s() {
+ let v = solidcraft_doc::Visibility {
+ hidden_bodies: vec!["A".into()],
+ hidden_occurrences: vec![vec![1, 2]],
+ hidden_origin: vec!["X".into()],
+ hidden_sketches: vec![4],
+ shown_sketches: vec![5],
+ hidden_joints: vec![6],
+ origin_hidden: Some(true),
+ hidden_profiles: vec![7],
+ shown_dimensions: vec![8],
+ locked_bodies: vec!["B".into()],
+ hidden_folders: vec!["c0/bodies".into()],
+ };
+ assert_eq!(serde_json::to_value(VisibilityState::from(&v)).unwrap(), serde_json::to_value(&v).unwrap());
+ let empty = solidcraft_doc::Visibility::default();
+ assert_eq!(serde_json::to_value(VisibilityState::from(&empty)).unwrap(), serde_json::to_value(&empty).unwrap());
+}
+
+/// #12276: every command replies as its output schema says, in Warn without warnings, in each
+/// form it takes; a misspelt key's warning still matches.
+#[test]
+fn browser_commands_reply_with_their_schemas() {
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ // A placed component, for the placement forms.
+ let part = s.execute("component.create", &json!({"name": "Part", "grounded": false})).unwrap_or_else(|e| panic!("{e}"));
+ s.execute("component.activate", &json!({"component": 0})).unwrap_or_else(|e| panic!("{e}"));
+ let occ = part["occurrence"].clone();
+ 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
+ };
+ for (i, name) in ["A", "B", "C"].into_iter().enumerate() {
+ run(
+ "solid.box",
+ json!({"length": 10, "width": 10, "height": 10, "corner": [i as f64 * 20.0, 0, 0], "body_name": name}),
+ output_schema_for::<crate::schema::features::FeatureResult>(),
+ );
+ }
+ let made = run("browser.group", json!({"folder": "bodies", "items": ["A"], "name": " Parts "}), output_schema_for::<BrowserGroupMade>());
+ assert_eq!(made["parent"], Value::Null, "{made}");
+ let outer = made["group"].clone();
+ let inner = run("browser.group", json!({"parent": outer, "items": ["B"], "component": 0}), output_schema_for::<BrowserGroupMade>());
+ assert_eq!(inner["parent"], outer, "{inner}");
+ let renamed = run("browser.rename_group", json!({"group": inner["group"], "name": " Inner "}), output_schema_for::<BrowserGroupRenamed>());
+ assert_eq!(renamed["name"], "Inner", "{renamed}");
+ let moved = run(
+ "browser.move",
+ json!({"folder": "bodies", "items": ["C", inner["group"]], "group": outer, "before": "A"}),
+ output_schema_for::<BrowserMoved>(),
+ );
+ assert_eq!(moved["items"], json!(["C", inner["group"]]), "{moved}");
+ let top = run("browser.move", json!({"folder": "bodies", "items": ["C"], "group": null}), output_schema_for::<BrowserMoved>());
+ assert_eq!(top["group"], Value::Null, "{top}");
+ run("browser.order", json!({"folder": "bodies", "order": ["C", outer]}), output_schema_for::<BrowserOrdered>());
+ let cleared = run("browser.order", json!({"folder": "bodies"}), output_schema_for::<BrowserOrdered>());
+ assert_eq!(cleared, json!({}), "{cleared}");
+ run("browser.ungroup", json!({"group": inner["group"]}), output_schema_for::<BrowserUngrouped>());
+
+ let visibility = output_schema_for::<BrowserVisibilityResult>;
+ for p in [
+ json!({"visible": false, "items": ["A", "xy"]}),
+ json!({"visible": true, "items": ["A"]}),
+ json!({"visible": false, "folder": "bodies"}),
+ json!({"visible": true, "folder": "all"}),
+ json!({"visible": false, "features": ["Box1"]}),
+ json!({"visible": false, "tree_folders": ["c0/bodies", format!("c0/g{outer}")]}),
+ json!({"visible": false, "paths": [[occ]]}),
+ json!({"visible": true, "paths": [[occ]], "isolate": true}),
+ json!({"visible": true, "items": ["B"], "isolate": true}),
+ ] {
+ let r = run("browser.visibility", p.clone(), visibility());
+ assert!(r["visibility"].is_object(), "{p}: {r}");
+ assert_eq!(r.get("isolated").is_some(), p.get("isolate").is_some(), "{p}: {r}");
+ assert_eq!(r.get("changed").is_some(), p.get("isolate").is_none(), "{p}: {r}");
+ }
+ let fold = output_schema_for::<BrowserFoldResult>;
+ for (id, p, open) in [
+ ("browser.expand_all", json!({}), true),
+ ("browser.expand_all", json!({"path": [occ]}), true),
+ ("browser.collapse_all", json!({"component": 0}), false),
+ ("browser.collapse_all", json!({"path": [occ]}), false),
+ ] {
+ assert_eq!(run(id, p, fold())["open"], open);
+ }
+ let renamed = run("body.rename", json!({"body": "A", "name": " Alpha "}), output_schema_for::<BodyRenamed>());
+ assert_eq!(renamed, json!({"body": "A", "name": "Alpha"}), "{renamed}");
+ let same = run("body.rename", json!({"body": "Alpha", "name": "Alpha"}), output_schema_for::<BodyRenamed>());
+ assert_eq!(same, json!({"body": "Alpha", "name": "Alpha"}), "{same}");
+
+ // A misspelt key still runs in warn, and says so; strict refuses it.
+ let p = json!({"visible": true, "folder": "all", "itms": []});
+ let r = s.execute("browser.visibility", &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ let schema = output_schema_for::<BrowserVisibilityResult>();
+ assert!(r["param_warnings"].to_string().contains("itms") && conforms(schema.as_value(), schema.as_value(), &r), "{r}");
+ s.param_check = ParamCheck::Strict;
+ let error = s.execute("browser.visibility", &p).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains("`itms`"), "{error}");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 586c1ea937..3dbb76424f 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -2,15 +2,6 @@
# (coverage_tests.rs). This list only shrinks: when you give a command its contract and output
# type, remove its line. Never add one: a new command comes with both schemas. Sorted, one id
# per line.
-body.rename
-browser.collapse_all
-browser.expand_all
-browser.group
-browser.move
-browser.order
-browser.rename_group
-browser.ungroup
-browser.visibility
canvas.calibrate
canvas.decal
canvas.delete