SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Agents and scripts: Frame Member and the profile library commands describe their exact parameters and reply (#12500) (#12593)
PeppaWutzb464c48506ca
diff --git a/crates/engine/src/cmd/frame.rs b/crates/engine/src/cmd/frame.rsindex 4eabb3edb0..ad11f5faca 100644--- a/crates/engine/src/cmd/frame.rs+++ b/crates/engine/src/cmd/frame.rs@@ -6,7 +6,7 @@use solidcraft_geom::prelude::*;use std::collections::BTreeMap;-use serde_json::{Value, json};+use serde_json::Value;use solidcore_record::{Loop2, Seg2, Vec2};use solidcraft_doc::expr::Kind;use solidcraft_doc::frame::{self, Anchor, MemberProfile, Profile, ProfileSpec};@@ -17,12 +17,23 @@ use super::features::{add_feature, check_expr, sketch_id};use super::sketch::edit;use super::{CommandSpec, in_sketch, not_in_sketch};use crate::params::{bad, bool_, expr, num, str_, string_list, vec2};+use crate::schema::features::FeatureResult;+use crate::schema::frame::{+ CreatedIds, FrameMemberParams, ProfileInsertParams, ProfileInsertResult, ProfileKindInfo, ProfileListParams, ProfileListResult, ProfileOut,+ ProfilePropertiesParams, ProfilePropertiesResult, ProfileSection,+};+use crate::schema::{TypedContract, output_schema_for};use crate::{Result, Session};#[cfg(test)]#[path = "frame_tests.rs"]mod tests;+const MEMBER_CONTRACT: TypedContract<FrameMemberParams> = TypedContract::new();+const LIST_CONTRACT: TypedContract<ProfileListParams> = TypedContract::new();+const PROPERTIES_CONTRACT: TypedContract<ProfilePropertiesParams> = TypedContract::new();+const INSERT_CONTRACT: TypedContract<ProfileInsertParams> = TypedContract::new();+/// The profile parameter, as every frame command documents it.macro_rules! profile_doc {() => {@@ -31,20 +42,40 @@ macro_rules! profile_doc {}pub static COMMANDS: &[CommandSpec] = &[- CommandSpec::new("frame.member", "Frame Member", member).at("WELDMENTS", "CREATE").icon("frame_member").enabled(not_in_sketch).params(concat!(+ CommandSpec::new("frame.member", "Frame Member", crate::checked!("frame.member", member))+ .at("WELDMENTS", "CREATE")+ .icon("frame_member")+ .enabled(not_in_sketch)+ .contract(&MEMBER_CONTRACT)+ .output(output_schema_for::<FeatureResult>)+ .params(concat!("sketch: the frame sketch (id or name; 2D or 3D); lines?: [curve ids] (one member each; default: every straight line drawn in the sketch: not construction, not projected or otherwise linked, not of no length); ",profile_doc!()," | profile_sketch: a sketch whose profile is the section, in its own x and y around its origin, with profiles?: picks as solid.extrude takes them (default: its material, nested loops alternating, so two circles make a tube); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point that sits on each line, default origin); angle?: angle expr (the profile turned about the line; default 0: its y as near world up as the line allows, a vertical member's x along world X); mirror?: bool (the profile mirrored across its y axis); name?; body_name? (what the members are named after, then numbered: `Rail`, `Rail (2)`…; default the profile's description, `Rect Tube 40x40x3`, or the profile sketch's name); names?: {line id: name} (names to keep, as Edit Feature keeps them). One body per line, from its start to its end; each member keeps its name when other lines are added or deleted. Returns the feature and the bodies it made")),- CommandSpec::new("frame.profile.list", "Profile Library", list).icon("library")+ CommandSpec::new("frame.profile.list", "Profile Library", crate::checked!("frame.profile.list", list))+ .icon("library").noundo().doc_only()+ .contract(&LIST_CONTRACT)+ .output(output_schema_for::<ProfileListResult>).params("Returns kinds: [{kind, label, required, optional, example}]: the built-in profiles, each SolidCraft's own parametric definition"),- CommandSpec::new("frame.profile.properties", "Profile Properties", properties).icon("measure").noundo().doc_only().params(concat!(+ CommandSpec::new("frame.profile.properties", "Profile Properties", crate::checked!("frame.profile.properties", properties))+ .icon("measure")+ .noundo()+ .doc_only()+ .contract(&PROPERTIES_CONTRACT)+ .output(output_schema_for::<ProfilePropertiesResult>)+ .params(concat!(profile_doc!(),"; density?: kg/m³ (adds mass_per_m, kg/m). Returns profile (every default filled in), area (mm²), centroid [x,y] (mm, from the bounding box centre), ixx, iyy, ixy (mm⁴ about the centroid), width, height")),- CommandSpec::new("frame.profile.insert", "Insert Profile", insert).icon("import").enabled(in_sketch).params(concat!(+ CommandSpec::new("frame.profile.insert", "Insert Profile", crate::checked!("frame.profile.insert", insert))+ .icon("import")+ .enabled(in_sketch)+ .contract(&INSERT_CONTRACT)+ .output(output_schema_for::<ProfileInsertResult>)+ .params(concat!(profile_doc!(),"; at?: [x,y] (sketch mm, default the origin); anchor?: origin|center|centroid|top_left|top|top_right|left|right|bottom_left|bottom|bottom_right (the profile point placed on `at`: its origin, the default and a built-in profile's centre, its bounding box's centre, its centroid, or a corner or edge middle of its bounding box); angle?: radians, counter-clockwise; fixed?: bool (default true: the curves are locked, so solving the sketch keeps the shape); sketch?: id|name (default: the sketch being edited). Returns the section as frame.profile.properties does",created_doc!()@@ -73,29 +104,32 @@ fn profile(s: &Session, cmd: &str, p: &Value) -> Result<Profile> {resolve(s, cmd, &profile_spec(cmd, p)?)}+/// A frame command's reply, built from its schema's type so the two can't drift apart.+fn frame_reply(cmd: &str, r: impl serde::Serialize) -> Result<Value> {+ serde_json::to_value(r).map_err(|e| bad(cmd, e.to_string()))+}+fn list(_: &mut Session, _: &Value) -> Result<Value> {- Ok(json!({"kinds": frame::profile_kinds()}))+ let kinds = frame::profile_kinds().iter().map(ProfileKindInfo::from).collect();+ frame_reply("frame.profile.list", ProfileListResult { kinds, param_warnings: Vec::new() })}/// The profile's section as the commands report it.-fn section_json(cmd: &str, profile: &Profile, density: Option<f64>) -> Result<Value> {+fn section(cmd: &str, profile: &Profile, density: Option<f64>) -> Result<ProfileSection> {let region = profile.region().map_err(|e| bad(cmd, e.to_string()))?;let s = frame::section(®ion);- let mut out = json!({- "profile": profile.filled(),- "area": s.area,- "centroid": s.centroid,- "ixx": s.ixx,- "iyy": s.iyy,- "ixy": s.ixy,- "width": s.width,- "height": s.height,- });- if let (Some(rho), Some(o)) = (density, out.as_object_mut()) {+ Ok(ProfileSection {+ profile: ProfileOut(profile.filled()),+ area: s.area,+ centroid: s.centroid,+ ixx: s.ixx,+ iyy: s.iyy,+ ixy: s.ixy,+ width: s.width,+ height: s.height,// mm² × 1e-6 m²/mm² × kg/m³ = kg/m.- o.insert("mass_per_m".into(), json!(s.area * 1e-6 * rho));- }- Ok(out)+ mass_per_m: density.map(|rho| s.area * 1e-6 * rho),+ })}fn properties(s: &mut Session, p: &Value) -> Result<Value> {@@ -109,7 +143,7 @@ fn properties(s: &mut Session, p: &Value) -> Result<Value> {.ok_or_else(|| bad(cmd, "`density` must be a positive number of kg/m³ (at most 1e6)"))?,),};- section_json(cmd, &profile, density)+ frame_reply(cmd, ProfilePropertiesResult { section: section(cmd, &profile, density)?, param_warnings: Vec::new() })}fn insert(s: &mut Session, p: &Value) -> Result<Value> {@@ -135,15 +169,16 @@ fn insert(s: &mut Session, p: &Value) -> Result<Value> {};let region = profile.region().map_err(|e| bad(cmd, e.to_string()))?;let placed = frame::placed(®ion, frame::anchor_point(std::slice::from_ref(®ion), anchor), at, angle);- let section = section_json(cmd, &profile, None)?;+ let section = section(cmd, &profile, None)?;let (created, info) = edit(s, p, cmd, false, |sk, _| {let before = sk.clone();for l in std::iter::once(&placed.outer).chain(&placed.holes) {add_loop(sk, l, fixed, cmd)?;}- Ok(super::sketch_created(Some(&before), sk))+ serde_json::from_value::<CreatedIds>(super::sketch_created(Some(&before), sk)).map_err(|e| bad(cmd, e.to_string()))})?;- Ok(json!({"created": created, "section": section, "sketch": info}))+ let sketch = serde_json::from_value(info).map_err(|e| bad(cmd, e.to_string()))?;+ frame_reply(cmd, ProfileInsertResult { created, section, sketch, param_warnings: Vec::new() })}/// Draw the closed loop `l` (lines and arcs) into the sketch, each segment sharing its enddiff --git a/crates/engine/src/schema/frame.rs b/crates/engine/src/schema/frame.rsnew file mode 100644index 0000000000..cf43010b0f--- /dev/null+++ b/crates/engine/src/schema/frame.rs@@ -0,0 +1,656 @@+//! Contracts and result types for the commands in `cmd/frame.rs`: `frame.member`,+//! `frame.profile.list`, `frame.profile.properties` and `frame.profile.insert` (#12500).+//!+//! 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 sketch exists, a dimension evaluates+//! or a profile can be built stays the handler's to check. A key the handler refuses when it is+//! left out (`profile`, `sketch`) is optional in the type and required in the schema, so that the+//! handler's message, not the check's "is required", is what a caller sees. A call with several+//! problems may get a different one first in strict than with the check off (the check goes key+//! by key, the handlers in their own order).+//!+//! `frame.member` reads some keys only in some cases. With `profile` (a built-in profile) it+//! never reads `profiles` or `exact_regions`, which pick among a section sketch's profiles; with+//! `profile_sketch` it never reads `profile`. Given both, or neither, it refuses the call before+//! it reads anything about the section, so none of the three is read then either.++use std::borrow::Cow;+use std::collections::BTreeMap;++use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};+use serde::de::Error as _;+use serde::{Deserialize, Deserializer, Serialize};+use serde_json::{Map, Value, json};+use solidcore_record::Vec2;+use solidcraft_doc::Expr;+use solidcraft_doc::frame::{self, Anchor, MAX_MEMBERS, Profile, ProfileSpec};++use super::check::{keyed, located, whole};+use super::motion::require;+use super::sketch_ends::SketchTarget;+use super::types::{AngleExpr, Point2, ProfilesParam, SketchRef, StringList, not_blank_pattern, present};+use crate::params;++/// The words `Anchor` is spelled with, as the handlers' message lists them.+const ANCHORS: [&str; 11] =+ ["origin", "center", "centroid", "top_left", "top", "top_right", "left", "right", "bottom_left", "bottom", "bottom_right"];++/// The longest name a member may be given, in bytes once trimmed, as the handler requires.+const MAX_NAME: usize = 128;++/// `v` as the only key of an object, for the helpers that read `p.get(key)`.+fn wrap(key: &str, v: Value) -> Value {+ json!({ key: v })+}++// ---------------------------------------------------------------------------------------------+// Shared types+// ---------------------------------------------------------------------------------------------++/// A built-in profile as the commands take it: `{kind, …dimensions}`, each dimension a number or+/// an expression, read by `ProfileSpec`'s own deserializer. Whether a dimension evaluates, and+/// whether the profile can be built from the values (a wall thicker than the tube), is the+/// handler's to check, as it has the design.+#[derive(Clone, Debug, PartialEq)]+pub struct ProfileParam(pub ProfileSpec);++impl<'de> Deserialize<'de> for ProfileParam {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ // The handler's `` `profile`: {error} ``, with serde_json's own wording of the error.+ serde_json::from_value::<ProfileSpec>(Value::deserialize(d)?).map(ProfileParam).map_err(|e| D::Error::custom(keyed(e)))+ }+}++/// The schema of one dimension, a number or an expression.+fn dimension_schema() -> Value {+ json!({+ "anyOf": [+ {"type": "number"},+ {"type": "string", "minLength": 1, "maxLength": 4096, "pattern": not_blank_pattern()}+ ]+ })+}++/// One schema per built-in profile kind: its `kind`, its required dimensions and its optional+/// ones, each as `dimension` says, and nothing else.+fn profile_kinds_schema(dimension: &Value) -> Vec<Value> {+ frame::profile_kinds()+ .into_iter()+ .map(|k| {+ let mut properties = Map::new();+ properties.insert("kind".into(), json!({"enum": [k.kind]}));+ for name in k.required.iter().chain(k.optional) {+ properties.insert((*name).into(), dimension.clone());+ }+ let required: Vec<&str> = std::iter::once("kind").chain(k.required.iter().copied()).collect();+ json!({"type": "object", "properties": properties, "required": required, "additionalProperties": false})+ })+ .collect()+}++impl JsonSchema for ProfileParam {+ fn schema_name() -> Cow<'static, str> {+ "ProfileParam".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A built-in profile: {\"kind\": bar | round_bar | rect_tube | round_tube | angle | channel | i_beam, …its dimensions}. Each dimension is a number in the design's units or a length expression over its parameters (\"tube_wall\", \"2 in\"); `frame.profile.list` gives each kind's dimensions and an example. A dimension that is left out and isn't required takes a default worked out from the profile's size.",+ "anyOf": profile_kinds_schema(&dimension_schema())+ })+ }+}++/// A built-in profile as a command reports it, every number in mm: serialized as the profile's+/// own JSON (`{kind, …dimensions}`).+#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(transparent)]+pub struct ProfileOut(pub Profile);++impl JsonSchema for ProfileOut {+ fn schema_name() -> Cow<'static, str> {+ "ProfileOut".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A built-in profile: {\"kind\", …its dimensions}, each in mm.",+ "anyOf": profile_kinds_schema(&json!({"type": "number"}))+ })+ }+}++/// Where a profile is held to its placement point, as `Anchor` is spelled in JSON.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct AnchorParam(pub Anchor);++impl<'de> Deserialize<'de> for AnchorParam {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ serde_json::from_value::<Anchor>(Value::deserialize(d)?).map(AnchorParam).map_err(|_| {+ D::Error::custom(whole(+ "`anchor` must be origin, center, centroid, top_left, top, top_right, left, right, bottom_left, bottom or bottom_right",+ ))+ })+ }+}++impl JsonSchema for AnchorParam {+ fn schema_name() -> Cow<'static, str> {+ "AnchorParam".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "The profile point that is placed: its origin (the default; a built-in profile's centre), `center` (its bounding box's centre), `centroid`, or a corner or edge middle of its bounding box.",+ "type": "string",+ "enum": ANCHORS+ })+ }+}++// ---------------------------------------------------------------------------------------------+// frame.profile.list+// ---------------------------------------------------------------------------------------------++/// `frame.profile.list` takes no parameters.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields)]+pub struct ProfileListParams {}++/// One built-in profile kind.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfileKindInfo {+ /// The kind's id, as `profile.kind` takes it.+ pub kind: String,+ /// The kind's name for people.+ pub label: String,+ /// The dimensions it needs.+ pub required: Vec<String>,+ /// The dimensions that default when left out.+ pub optional: Vec<String>,+ /// A complete example profile.+ pub example: ProfileOut,+}++impl From<&frame::ProfileKind> for ProfileKindInfo {+ fn from(k: &frame::ProfileKind) -> Self {+ ProfileKindInfo {+ kind: k.kind.to_string(),+ label: k.label.to_string(),+ required: k.required.iter().map(|d| d.to_string()).collect(),+ optional: k.optional.iter().map(|d| d.to_string()).collect(),+ example: ProfileOut(k.example.clone()),+ }+ }+}++/// What `frame.profile.list` returns: the built-in profiles, each SolidCraft's own parametric+/// definition.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfileListResult {+ /// Every built-in profile kind.+ pub kinds: Vec<ProfileKindInfo>,+ /// 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>,+}++// ---------------------------------------------------------------------------------------------+// frame.profile.properties and the section both profile commands report+// ---------------------------------------------------------------------------------------------++/// A density in kg/m³: above 0 and at most 1e6, as `frame.profile.properties` requires.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Density(pub f64);++impl<'de> Deserialize<'de> for Density {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::num(&wrap("density", Value::deserialize(d)?), "density")+ .filter(|d| *d > 0.0 && *d <= 1e6)+ .map(Density)+ .ok_or_else(|| D::Error::custom(whole("`density` must be a positive number of kg/m³ (at most 1e6)")))+ }+}++impl JsonSchema for Density {+ fn schema_name() -> Cow<'static, str> {+ "Density".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A density in kg/m³: above 0 and at most 1e6.",+ "type": "number", "exclusiveMinimum": 0, "maximum": 1e6+ })+ }+}++fn profile_required(schema: &mut Schema) {+ require(schema, "profile");+}++/// Work out a built-in profile's section: its area, centroid and second moments, about axes+/// through the centroid, parallel to the profile's x and y.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = profile_required)]+pub struct ProfilePropertiesParams {+ // Optional in the type and required in the schema (`profile_required`).+ /// The profile, as `frame.profile.list` describes the kinds.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ProfileParam")]+ pub profile: Option<ProfileParam>,+ /// The material's density, which adds `mass_per_m`. Default: none, and no `mass_per_m`.+ #[serde(default)]+ pub density: Option<Density>,+}++/// A profile's section, as `frame.profile.properties` and `frame.profile.insert` report it.+/// Lengths are in mm, areas in mm² and second moments in mm⁴.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfileSection {+ /// The profile with every default filled in.+ pub profile: ProfileOut,+ /// The section's area, mm².+ pub area: f64,+ /// The centroid [x, y], mm, in the profile's own plane (x across, y up) from the centre of its+ /// bounding box.+ pub centroid: [f64; 2],+ /// ∫ y² dA about the centroid: bending about the x axis, mm⁴.+ pub ixx: f64,+ /// ∫ x² dA about the centroid: bending about the y axis, mm⁴.+ pub iyy: f64,+ /// ∫ x·y dA about the centroid, mm⁴.+ pub ixy: f64,+ /// The bounding box's width, mm.+ pub width: f64,+ /// The bounding box's height, mm.+ pub height: f64,+ /// With a `density`: the mass of a metre of the profile, kg/m.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub mass_per_m: Option<f64>,+}++/// What `frame.profile.properties` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfilePropertiesResult {+ #[serde(flatten)]+ pub section: ProfileSection,+ /// 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>,+}++// ---------------------------------------------------------------------------------------------+// frame.profile.insert+// ---------------------------------------------------------------------------------------------++/// A point of the sketch in mm: `[x, y]` or `{x, y}`, with `frame.profile.insert`'s message.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct InsertAt(pub Vec2);++impl<'de> Deserialize<'de> for InsertAt {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::vec2(&Value::deserialize(d)?).map(InsertAt).ok_or_else(|| D::Error::custom(whole("`at` must be [x, y] in sketch millimetres")))+ }+}++impl JsonSchema for InsertAt {+ fn schema_name() -> Cow<'static, str> {+ "InsertAt".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ generator.subschema_for::<Point2>()+ }+}++/// An angle in radians as `frame.profile.insert` reads it: a number, at most 1e6 in size.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Radians(pub f64);++impl<'de> Deserialize<'de> for Radians {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::num(&wrap("angle", Value::deserialize(d)?), "angle")+ .filter(|a| a.abs() <= 1e6)+ .map(Radians)+ .ok_or_else(|| D::Error::custom(whole("`angle` must be a number of radians")))+ }+}++impl JsonSchema for Radians {+ fn schema_name() -> Cow<'static, str> {+ "Radians".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({"description": "An angle in radians, counter-clockwise: a number of at most 1e6 in size.", "type": "number", "minimum": -1e6, "maximum": 1e6})+ }+}++/// Draw a built-in profile into a sketch as lines and arcs, placed by its anchor and turned about+/// it. A tube's inside is drawn too, so the wall is one profile. One undo step.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = profile_required)]+pub struct ProfileInsertParams {+ // Optional in the type and required in the schema (`profile_required`).+ /// The profile, as `frame.profile.list` describes the kinds.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ProfileParam")]+ pub profile: Option<ProfileParam>,+ /// Where the anchor goes, in sketch mm. Default: the origin.+ #[serde(default)]+ pub at: Option<InsertAt>,+ /// The profile point that is placed on `at`. Default: origin.+ #[serde(default)]+ pub anchor: Option<AnchorParam>,+ /// How far the profile turns about the anchor, in radians counter-clockwise (not degrees).+ /// Default: 0.+ #[serde(default)]+ pub angle: Option<Radians>,+ /// Lock the curves, so that solving the sketch keeps the shape. Default: true.+ #[serde(default)]+ pub fixed: Option<bool>,+ /// The sketch to draw in, by id or name. Default: the sketch being edited.+ #[serde(default)]+ pub sketch: Option<SketchTarget>,+}++/// The ids of what a sketch edit added, stable and never reused.+#[derive(Debug, Serialize, Deserialize, JsonSchema)]+pub struct CreatedIds {+ /// The points added.+ pub points: Vec<String>,+ /// The curves added.+ pub curves: Vec<String>,+ /// The constraints added, dimensions apart.+ pub constraints: Vec<String>,+ /// The dimensions added.+ pub dimensions: Vec<String>,+ /// The wires added. Left out when there are none.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub wires: Vec<String>,+}++/// The sketch's solve after an edit.+#[derive(Debug, Serialize, Deserialize, JsonSchema)]+pub struct SketchSolve {+ /// Whether the constraints solved, keeping the sketch's orientation.+ pub solved: bool,+ /// The degrees of freedom left.+ pub dof: usize,+}++/// What `frame.profile.insert` returns.+#[derive(Debug, Serialize, JsonSchema)]+pub struct ProfileInsertResult {+ /// What the insertion added to the sketch.+ pub created: CreatedIds,+ /// The inserted profile's section, as `frame.profile.properties` reports it.+ pub section: ProfileSection,+ /// The sketch's solve, or null when it was not solved again.+ pub sketch: Option<SketchSolve>,+ /// 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>,+}++// ---------------------------------------------------------------------------------------------+// frame.member+// ---------------------------------------------------------------------------------------------++/// `lines`: one to 1000 curve ids, none twice, as `frame.member` reads them (a single id isn't+/// taken).+#[derive(Clone, Debug, PartialEq)]+pub struct LineIds(pub Vec<String>);++impl<'de> Deserialize<'de> for LineIds {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let fail = || D::Error::custom(whole(format!("`lines` must list 1…{MAX_MEMBERS} curve ids")));+ let Value::Array(a) = Value::deserialize(d)? else { return Err(fail()) };+ if a.is_empty() || a.len() > MAX_MEMBERS {+ return Err(fail());+ }+ let lines = a.into_iter().map(|v| if let Value::String(s) = v { Some(s) } else { None }).collect::<Option<Vec<_>>>().ok_or_else(fail)?;+ let mut seen = std::collections::HashSet::new();+ match lines.iter().find(|l| !seen.insert(l.as_str())) {+ Some(twice) => Err(D::Error::custom(whole(format!("line `{twice}` is listed twice")))),+ None => Ok(LineIds(lines)),+ }+ }+}++impl JsonSchema for LineIds {+ fn schema_name() -> Cow<'static, str> {+ "LineIds".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "Curve ids of the frame sketch's lines, each once.",+ "type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": MAX_MEMBERS, "uniqueItems": true+ })+ }+}++/// The name members are named after: text of 1 to 128 bytes once trimmed, as `frame.member` reads+/// `body_name`.+#[derive(Clone, Debug, PartialEq)]+pub struct MemberName(pub String);++impl<'de> Deserialize<'de> for MemberName {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::String(s) if !s.trim().is_empty() && s.trim().len() <= MAX_NAME => Ok(MemberName(s)),+ _ => Err(D::Error::custom(whole(format!("`body_name` must be 1…{MAX_NAME} characters")))),+ }+ }+}++impl JsonSchema for MemberName {+ fn schema_name() -> Cow<'static, str> {+ "MemberName".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "A name: text that isn't blank, at most 128 bytes once trimmed of the whitespace around it.",+ "type": "string", "pattern": not_blank_pattern()+ })+ }+}++/// `names`: up to 1000 line ids, each with a name of 1 to 128 bytes once trimmed.+#[derive(Clone, Debug, PartialEq)]+pub struct MemberNames(pub BTreeMap<String, String>);++impl<'de> Deserialize<'de> for MemberNames {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match Value::deserialize(d)? {+ Value::Object(m) if m.len() <= MAX_MEMBERS => m+ .into_iter()+ .map(|(line, v)| match v.as_str().map(str::trim).filter(|n| !n.is_empty() && n.len() <= MAX_NAME) {+ Some(name) => Ok((line, name.to_string())),+ None => Err(D::Error::custom(whole(format!("`names`: the name of line `{line}` must be 1…{MAX_NAME} characters")))),+ })+ .collect::<Result<_, _>>()+ .map(MemberNames),+ _ => Err(D::Error::custom(whole(format!("`names` must map up to {MAX_MEMBERS} line ids to names")))),+ }+ }+}++impl JsonSchema for MemberNames {+ fn schema_name() -> Cow<'static, str> {+ "MemberNames".into()+ }+ fn json_schema(_: &mut SchemaGenerator) -> Schema {+ json_schema!({+ "description": "Names to keep, by line id. A name is text that isn't blank, at most 128 bytes once trimmed.",+ "type": "object",+ "additionalProperties": {"type": "string", "pattern": not_blank_pattern()},+ "maxProperties": MAX_MEMBERS+ })+ }+}++/// `angle` as `frame.member` reads it: a number of degrees or an expression, with its message. Whether+/// the expression evaluates as an angle is the handler's to check.+#[derive(Clone, Debug, PartialEq)]+pub struct MemberAngle(pub Expr);++impl<'de> Deserialize<'de> for MemberAngle {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ params::expr(&wrap("angle", Value::deserialize(d)?), "angle")+ .map(MemberAngle)+ .ok_or_else(|| D::Error::custom(whole("`angle` must be an angle expression")))+ }+}++impl JsonSchema for MemberAngle {+ fn schema_name() -> Cow<'static, str> {+ "MemberAngle".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ generator.subschema_for::<AngleExpr>()+ }+}++/// `participants`, read as `features::add_feature` reads it: a name or a list of names, with the+/// message of `params::string_list`.+#[derive(Clone, Debug, PartialEq)]+pub struct Participants(pub Vec<String>);++impl<'de> Deserialize<'de> for Participants {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ match params::string_list("", &wrap("participants", Value::deserialize(d)?), "participants") {+ Ok(names) => Ok(Participants(names)),+ Err(crate::EngineError::BadParams { msg, .. }) => Err(D::Error::custom(whole(msg))),+ Err(e) => Err(D::Error::custom(whole(e))),+ }+ }+}++impl JsonSchema for Participants {+ fn schema_name() -> Cow<'static, str> {+ "Participants".into()+ }+ fn inline_schema() -> bool {+ true+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ generator.subschema_for::<StringList>()+ }+}++/// `sketch` is required and one of `profile` and `profile_sketch`, not both, as the schema says;+/// the type leaves them to the handler's messages.+fn member_required(schema: &mut Schema) {+ require(schema, "sketch");+ let only = |key: &str, other: &str| json!({"required": [key], "not": {"required": [other]}});+ schema.insert("anyOf".into(), json!([only("profile", "profile_sketch"), only("profile_sketch", "profile")]));+}++/// Lay structural members along the lines of a frame sketch: one body per line, from its start+/// to its end, its cross-section square to the line. The section is a built-in `profile` or the+/// profiles of a `profile_sketch`, one of them. Each member keeps its name when other lines are+/// added or deleted. Returns the feature and the bodies it made.+#[derive(Debug, Deserialize, JsonSchema)]+#[schemars(deny_unknown_fields, transform = member_required)]+pub struct FrameMemberKeys {+ // Optional in the type and required in the schema (`member_required`).+ /// The frame sketch, 2D or 3D, by id or name.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "SketchRef")]+ pub sketch: Option<SketchRef>,+ /// The lines to lay members along, by curve id, one member each. Default: every straight+ /// line drawn in the sketch that isn't construction, projected or otherwise linked, or of no+ /// length.+ #[serde(default)]+ pub lines: Option<LineIds>,+ /// The section as a built-in profile. Give it or `profile_sketch`, not both.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ProfileParam")]+ pub profile: Option<ProfileParam>,+ /// The section as a sketch: its profiles, in the sketch's own x and y around its origin. It+ /// can't be the frame sketch. Give it or `profile`, not both.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "SketchRef")]+ pub profile_sketch: Option<SketchRef>,+ /// With `profile_sketch`: which of its profiles are the section, as `solid.extrude` takes+ /// them. Default: its material, nested loops alternating, so two circles make a tube. Not+ /// used with `profile`.+ #[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]+ #[schemars(with = "ProfilesParam")]+ pub profiles: Option<ProfilesParam>,+ /// With `profile_sketch`: each index or point pick in `profiles` is exactly the region it+ /// names, where it would otherwise take the whole drawn profile a face's projected outline+ /// cuts into regions. Default: false. Not used with `profile`.+ #[serde(default)]+ pub exact_regions: Option<bool>,+ /// The profile point that sits on each line. Default: origin.+ #[serde(default)]+ pub anchor: Option<AnchorParam>,+ /// How far the profile turns about the line, a number of degrees or an expression. Default:+ /// 0, which puts its y as near world up as the line allows (a vertical member's x along+ /// world X).+ #[serde(default)]+ pub angle: Option<MemberAngle>,+ /// The profile mirrored across its y axis, before it turns. Default: false.+ #[serde(default)]+ pub mirror: Option<bool>,+ /// The feature's name in the timeline.+ #[serde(default)]+ pub name: Option<String>,+ /// What the members are named after, then numbered: `Rail`, `Rail (2)`… Default: the+ /// profile's description (`Rect Tube 40x40x3`), or the profile sketch's name.+ #[serde(default)]+ pub body_name: Option<MemberName>,+ /// Names to keep, by line id, as Edit Feature keeps them. A line not listed gets a name from+ /// `body_name`.+ #[serde(default)]+ pub names: Option<MemberNames>,+ /// The bodies taking part, which every feature records; each an existing body or `*`. Members+ /// are new bodies, whatever this lists.+ #[serde(default)]+ pub participants: Option<Participants>,+}++/// `frame.member`'s parameters: [`FrameMemberKeys`], reading the section's keys only as the+/// handler does (see the module docs).+#[derive(Debug)]+pub struct FrameMemberParams(pub FrameMemberKeys);++impl<'de> Deserialize<'de> for FrameMemberParams {+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {+ let mut value = Value::deserialize(d)?;+ if let Some(keys) = value.as_object_mut() {+ // A key counts as given when it is there, `null` included, as the handler tests it.+ match (keys.contains_key("profile"), keys.contains_key("profile_sketch")) {+ // A built-in profile: the sketch's profile picks are never read.+ (true, false) => {+ keys.remove("profiles");+ keys.remove("exact_regions");+ }+ (false, true) => {}+ // Both or neither: the handler refuses before it reads any of them.+ _ => {+ for key in ["profile", "profile_sketch", "profiles", "exact_regions"] {+ keys.remove(key);+ }+ }+ }+ }+ serde_path_to_error::deserialize(&value).map(FrameMemberParams).map_err(|e| D::Error::custom(located(&e)))+ }+}++impl JsonSchema for FrameMemberParams {+ fn schema_name() -> Cow<'static, str> {+ "FrameMemberParams".into()+ }+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {+ FrameMemberKeys::json_schema(generator)+ }+}++#[cfg(test)]+#[path = "frame_tests.rs"]+mod tests;diff --git a/crates/engine/src/schema/frame_tests.rs b/crates/engine/src/schema/frame_tests.rsnew file mode 100644index 0000000000..e6fe314450--- /dev/null+++ b/crates/engine/src/schema/frame_tests.rs@@ -0,0 +1,568 @@+use serde_json::{Value, json};+use solidcraft_doc::FeatureKind;+use solidcraft_doc::frame::{self, MAX_MEMBERS};++use super::{+ FrameMemberParams, ProfileInsertParams, ProfileInsertResult, ProfileListParams, ProfileListResult, ProfilePropertiesParams,+ ProfilePropertiesResult,+};+use crate::Session;+use crate::schema::features::FeatureResult;+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms, sketch_rectangle};+use crate::schema::{ParamCheck, input_schema_for, issues, output_schema_for};++fn tube() -> Value {+ json!({"kind": "rect_tube", "width": 40, "height": 40, "wall": 3})+}++/// The id of the first sketch of `s`.+fn first_sketch(s: &Session) -> u64 {+ s.doc.features.iter().find(|f| matches!(f.kind, FeatureKind::Sketch { .. })).map(|f| f.id).unwrap_or_else(|| panic!("no sketch"))+}++/// A session with the 600 × 400 rectangle `Frame` (its four line ids returned) and the sketch+/// `Section`, two concentric circles: a tube's wall.+fn frame_session(level: ParamCheck) -> (Session, Vec<String>) {+ let mut s = Session { param_check: level, ..Session::default() };+ let mut run = |id: &str, p: Value| s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));+ run("sketch.create", json!({"plane": "XY", "name": "Frame"}));+ let rectangle = run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [600, 400]}));+ run("sketch.finish", json!({}));+ run("sketch.create", json!({"plane": "XY", "name": "Section"}));+ run("sketch.circle.center", json!({"center": [0, 0], "radius": 20}));+ run("sketch.circle.center", json!({"center": [0, 0], "radius": 17}));+ run("sketch.finish", json!({}));+ let lines =+ rectangle["created"]["curves"].as_array().map(|c| c.iter().filter_map(|c| c.as_str().map(str::to_string)).collect()).unwrap_or_default();+ (s, lines)+}++#[test]+fn schemas_and_the_key_check_agree() {+ assert_keys(+ input_schema_for::<FrameMemberParams>(),+ &[+ "anchor",+ "angle",+ "body_name",+ "exact_regions",+ "lines",+ "mirror",+ "name",+ "names",+ "participants",+ "profile",+ "profile_sketch",+ "profiles",+ "sketch",+ ],+ );+ assert_keys(input_schema_for::<ProfileListParams>(), &[]);+ assert_keys(input_schema_for::<ProfilePropertiesParams>(), &["density", "profile"]);+ assert_keys(input_schema_for::<ProfileInsertParams>(), &["anchor", "angle", "at", "fixed", "profile", "sketch"]);+}++#[test]+fn strict_keeps_todays_errors() {+ let sketch = {+ let mut s = Session::default();+ sketch_rectangle(&mut s);+ first_sketch(&s)+ };+ let member = |extra: Value| {+ let mut p = json!({"sketch": sketch, "profile": tube()});+ for (k, v) in extra.as_object().into_iter().flatten() {+ p[k] = v.clone();+ }+ ("frame.member", p)+ };+ let bar = json!({"kind": "round_bar", "diameter": 10});+ let insert = |extra: Value| {+ let mut p = json!({"profile": bar});+ for (k, v) in extra.as_object().into_iter().flatten() {+ p[k] = v.clone();+ }+ ("frame.profile.insert", p)+ };+ assert_strict_keeps_todays_errors(&[+ // frame.member+ ("frame.member", json!({})),+ ("frame.member", json!({"sketch": null, "profile": tube()})),+ ("frame.member", json!({"sketch": true, "profile": tube()})),+ ("frame.member", json!({"sketch": [1], "profile": tube()})),+ ("frame.member", json!({"sketch": sketch})),+ ("frame.member", json!({"sketch": sketch, "profile": tube(), "profile_sketch": sketch})),+ ("frame.member", json!({"sketch": sketch, "profile": tube(), "profile_sketch": null})),+ ("frame.member", json!({"sketch": sketch, "profile_sketch": true})),+ ("frame.member", json!({"sketch": sketch, "profile_sketch": null})),+ ("frame.member", json!({"sketch": sketch, "profile_sketch": sketch})),+ ("frame.member", json!({"sketch": sketch, "profile_sketch": "Nowhere"})),+ ("frame.member", json!({"sketch": sketch, "profile_sketch": 99999, "profiles": 3})),+ ("frame.member", json!({"sketch": "Nowhere", "profile": tube()})),+ member(json!({"profile": null})),+ member(json!({"profile": "tube"})),+ member(json!({"profile": {}})),+ member(json!({"profile": {"kind": "hexagon"}})),+ member(json!({"profile": {"kind": 5}})),+ member(json!({"profile": {"kind": "bar", "width": 10}})),+ member(json!({"profile": {"kind": "bar", "width": 10, "height": 5, "diameter": 3}})),+ member(json!({"profile": {"kind": "bar", "width": true, "height": 5}})),+ member(json!({"profile": {"kind": "bar", "width": " ", "height": 5}})),+ member(json!({"profile": {"kind": "rect_tube", "width": 10, "height": 10, "wall": 5}})),+ member(json!({"profile": {"kind": "bar", "width": "nonsense(", "height": 5}})),+ member(json!({"lines": []})),+ member(json!({"lines": "l1"})),+ member(json!({"lines": [1]})),+ member(json!({"lines": ["l1", "l1"]})),+ member(json!({"lines": (0..=MAX_MEMBERS).map(|i| format!("l{i}")).collect::<Vec<_>>()})),+ member(json!({"lines": ["nope"]})),+ member(json!({"body_name": ""})),+ member(json!({"body_name": " "})),+ member(json!({"body_name": 5})),+ member(json!({"body_name": "x".repeat(129)})),+ member(json!({"anchor": "middle"})),+ member(json!({"anchor": 5})),+ member(json!({"anchor": ["top"]})),+ member(json!({"angle": true})),+ member(json!({"angle": ""})),+ member(json!({"angle": "x".repeat(4097)})),+ member(json!({"angle": "a lot"})),+ member(json!({"mirror": 3})),+ member(json!({"mirror": "yes"})),+ member(json!({"names": ["Rail"]})),+ member(json!({"names": {"l1": " "}})),+ member(json!({"names": {"l1": 5}})),+ member(json!({"names": {"l1": "x".repeat(129)}})),+ member(json!({"participants": 5})),+ member(json!({"participants": [5]})),+ member(json!({"participants": ["Nobody"]})),+ // frame.profile.properties+ ("frame.profile.properties", json!({})),+ ("frame.profile.properties", json!({"profile": null})),+ ("frame.profile.properties", json!({"profile": {"kind": "hexagon"}})),+ ("frame.profile.properties", json!({"profile": {"kind": "round_bar"}})),+ ("frame.profile.properties", json!({"profile": {"kind": "round_bar", "diameter": -1}})),+ ("frame.profile.properties", json!({"profile": bar, "density": -1})),+ ("frame.profile.properties", json!({"profile": bar, "density": 0})),+ ("frame.profile.properties", json!({"profile": bar, "density": "steel"})),+ ("frame.profile.properties", json!({"profile": bar, "density": 1e7})),+ ("frame.profile.properties", json!({"profile": bar, "density": true})),+ // frame.profile.insert+ ("frame.profile.insert", json!({})),+ ("frame.profile.insert", json!({"profile": {"kind": "bar", "width": 5}})),+ insert(json!({"at": "here"})),+ insert(json!({"at": [1]})),+ insert(json!({"at": [1e300, 0]})),+ insert(json!({"at": {"x": 1}})),+ insert(json!({"anchor": "middle"})),+ insert(json!({"anchor": 3})),+ insert(json!({"angle": "a lot"})),+ insert(json!({"angle": 1e7})),+ insert(json!({"fixed": 3})),+ insert(json!({"fixed": "false"})),+ insert(json!({"sketch": true})),+ insert(json!({"sketch": -1})),+ insert(json!({"sketch": 1.5})),+ insert(json!({"sketch": "Nowhere"})),+ // No sketch is being edited, and none is named.+ insert(json!({})),+ ]);+}++/// Each key is read as its handler reads it: a call the handler takes has no issue, and a call+/// it refuses over a key has one. (A call with a key the handler ignores is told apart below.)+#[test]+fn the_types_read_each_key_as_the_handlers_do() {+ let (_, lines) = frame_session(ParamCheck::Off);+ let line = lines.first().cloned().unwrap_or_default();+ let member = |extra: Value| {+ let mut p = json!({"sketch": "Frame", "profile": tube()});+ for (k, v) in extra.as_object().into_iter().flatten() {+ p[k] = v.clone();+ }+ p+ };+ let section = |extra: Value| {+ let mut p = json!({"sketch": "Frame", "profile_sketch": "Section"});+ for (k, v) in extra.as_object().into_iter().flatten() {+ p[k] = v.clone();+ }+ p+ };+ // (call, whether the handler takes it)+ let cases = [+ (member(json!({})), true),+ (member(json!({"lines": [line]})), true),+ (member(json!({"lines": null})), true),+ (member(json!({"lines": []})), false),+ (member(json!({"lines": [line, line]})), false),+ (member(json!({"body_name": "Rail"})), true),+ (member(json!({"body_name": " Rail "})), true),+ (member(json!({"body_name": null})), true),+ (member(json!({"body_name": "x".repeat(128)})), true),+ (member(json!({"body_name": "x".repeat(129)})), false),+ (member(json!({"body_name": " "})), false),+ (member(json!({"anchor": "bottom_left"})), true),+ (member(json!({"anchor": null})), true),+ (member(json!({"anchor": "Top"})), false),+ (member(json!({"angle": "90 deg"})), true),+ (member(json!({"angle": 45})), true),+ (member(json!({"angle": " 30 deg "})), true),+ (member(json!({"angle": null})), true),+ (member(json!({"angle": ""})), false),+ (member(json!({"angle": 1e9})), false),+ (member(json!({"mirror": true})), true),+ (member(json!({"mirror": null})), true),+ (member(json!({"mirror": 1})), false),+ (member(json!({"names": {line.clone(): " Mine "}})), true),+ (member(json!({"names": {}})), true),+ (member(json!({"names": null})), true),+ (member(json!({"names": {line.clone(): ""}})), false),+ (member(json!({"names": [line]})), false),+ (member(json!({"name": "Frame members"})), true),+ (member(json!({"participants": "*"})), true),+ (member(json!({"participants": ["*"]})), true),+ (member(json!({"participants": null})), true),+ (member(json!({"participants": [3]})), false),+ (member(json!({"participants": {"a": 1}})), false),+ (member(json!({"profile": {"kind": "bar", "width": "40 mm", "height": 10, "corner_radius": 0}})), true),+ (member(json!({"profile": {"kind": "bar", "width": 40}})), false),+ (member(json!({"profile": {"kind": "i_beam", "height": 100, "width": 50, "web": 4.5, "flange": 7, "root_radius": null}})), false),+ (section(json!({})), true),+ (section(json!({"profiles": "all"})), true),+ (section(json!({"profiles": [{"point": [0, 0]}], "exact_regions": true})), true),+ (section(json!({"profiles": [0]})), true),+ (section(json!({"profiles": "none"})), false),+ (section(json!({"profiles": null})), false),+ (section(json!({"profiles": []})), false),+ // Keys the handler never reads in this form: no issue, and the call is as good as without.+ (member(json!({"profiles": "none", "exact_regions": "yes"})), true),+ (member(json!({"profiles": null})), true),+ ];+ for (p, takes) in cases {+ let (mut s, _) = frame_session(ParamCheck::Off);+ let outcome = s.execute("frame.member", &p);+ assert_eq!(outcome.is_ok(), takes, "{p}: {outcome:?}");+ assert_eq!(issues("frame.member", &p).is_empty(), takes, "{p}: {:?}", issues("frame.member", &p));+ }++ // One of `profile` and `profile_sketch`: with both or neither the handler refuses before it+ // reads the section's keys, and the check, which can't see the design, leaves it that.+ for p in [+ json!({"sketch": "Frame", "profile": tube(), "profile_sketch": "Section"}),+ json!({"sketch": "Frame", "profile": tube(), "profile_sketch": "Section", "profiles": "none", "exact_regions": 1}),+ json!({"sketch": "Frame", "profile": null, "profile_sketch": null}),+ json!({"sketch": "Frame"}),+ json!({"sketch": "Frame", "profiles": "none"}),+ ] {+ let (mut s, _) = frame_session(ParamCheck::Off);+ let error = s.execute("frame.member", &p).unwrap_err().to_string();+ assert!(error.contains("`profile`") && error.contains("one of them"), "{p}: {error}");+ assert!(issues("frame.member", &p).is_empty(), "{p}: {:?}", issues("frame.member", &p));+ }++ // The properties and insert commands.+ let (mut s, _) = frame_session(ParamCheck::Off);+ let bar = json!({"kind": "round_bar", "diameter": 10});+ for (p, takes) in [+ (json!({"profile": bar}), true),+ (json!({"profile": bar, "density": 7850}), true),+ (json!({"profile": bar, "density": null}), true),+ (json!({"profile": bar, "density": 1e6}), true),+ (json!({"profile": bar, "density": 1e6 + 1.0}), false),+ (json!({"profile": bar, "density": 0}), false),+ (json!({"profile": bar, "density": "7850"}), false),+ ] {+ let outcome = s.execute("frame.profile.properties", &p);+ assert_eq!(outcome.is_ok(), takes, "{p}: {outcome:?}");+ assert_eq!(issues("frame.profile.properties", &p).is_empty(), takes, "{p}");+ }+ s.execute("sketch.create", &json!({"plane": "XY"})).unwrap_or_else(|e| panic!("{e}"));+ for (p, takes) in [+ (json!({"profile": bar}), true),+ (json!({"profile": bar, "at": [3, 4], "anchor": "centroid", "angle": 0.5, "fixed": false}), true),+ (json!({"profile": bar, "at": {"x": 3, "y": 4}}), true),+ (json!({"profile": bar, "at": null, "anchor": null, "angle": null, "fixed": null, "sketch": null}), true),+ (json!({"profile": bar, "angle": -1e6}), true),+ (json!({"profile": bar, "angle": 1e6 + 1.0}), false),+ (json!({"profile": bar, "at": [1, 2, 3]}), false),+ (json!({"profile": bar, "fixed": 0}), false),+ (json!({"profile": bar, "anchor": "CENTER"}), false),+ (json!({"profile": bar, "sketch": 1.5}), false),+ ] {+ let outcome = s.execute("frame.profile.insert", &p);+ assert_eq!(outcome.is_ok(), takes, "{p}: {outcome:?}");+ assert_eq!(issues("frame.profile.insert", &p).is_empty(), takes, "{p}");+ }+}++/// With a built-in profile, a `profiles` or `exact_regions` that couldn't be read is no warning;+/// with a profile sketch it is, and says what the handler says.+#[test]+fn a_section_sketchs_keys_count_only_with_a_section_sketch() {+ let messages = |p: Value| issues("frame.member", &p).into_iter().map(|i| i.message).collect::<Vec<_>>();+ assert_eq!(messages(json!({"sketch": 1, "profile": tube(), "profiles": 7, "exact_regions": []})), Vec::<String>::new());+ assert_eq!(messages(json!({"sketch": 1, "profile_sketch": 2, "profiles": "none"})), ["`profiles` must be \"all\" or a list"]);+ assert_eq!(messages(json!({"sketch": 1, "profile_sketch": 2, "exact_regions": "yes"})), ["`exact_regions` must be true or false"]);+}++/// The schemas say what the handlers need: `sketch` and a profile are required, `profile` and+/// `profile_sketch` are alternatives, and values have the shape the handlers read.+#[test]+fn the_schemas_take_what_the_handlers_read() {+ let takes = |schema: schemars::Schema, cases: &[(Value, bool)]| {+ let schema = schema.as_value();+ for (p, takes) in cases {+ assert_eq!(conforms(schema, schema, p), *takes, "{p}");+ }+ };+ let bar = json!({"kind": "round_bar", "diameter": 10});+ takes(+ input_schema_for::<FrameMemberParams>(),+ &[+ (json!({"sketch": "Frame", "profile": tube()}), true),+ (json!({"sketch": 3, "profile_sketch": "Section"}), true),+ (json!({"sketch": 3, "profile_sketch": 4, "profiles": [{"point": [0, 0]}], "exact_regions": true}), true),+ (+ json!({+ "sketch": "Frame", "lines": ["l1", "l2"], "profile": {"kind": "bar", "width": "w", "height": 5, "corner_radius": 1},+ "anchor": "top_left", "angle": "90 deg", "mirror": true, "name": "N", "body_name": "Rail",+ "names": {"l1": "A"}, "participants": ["*"]+ }),+ true,+ ),+ (json!({"profile": tube()}), false),+ (json!({"sketch": "Frame"}), false),+ (json!({"sketch": "Frame", "profile": tube(), "profile_sketch": "Section"}), false),+ (json!({"sketch": "Frame", "profile": {"kind": "hexagon"}}), false),+ (json!({"sketch": "Frame", "profile": {"kind": "bar", "width": 5}}), false),+ (json!({"sketch": "Frame", "profile": {"kind": "bar", "width": 5, "height": 5, "wall": 1}}), false),+ (json!({"sketch": true, "profile": tube()}), false),+ (json!({"sketch": "Frame", "profile": tube(), "lines": []}), false),+ (json!({"sketch": "Frame", "profile": tube(), "lines": ["a", "a"]}), false),+ (json!({"sketch": "Frame", "profile": tube(), "anchor": "middle"}), false),+ (json!({"sketch": "Frame", "profile": tube(), "angle": true}), false),+ (json!({"sketch": "Frame", "profile": tube(), "body_names": ["a"]}), false),+ ],+ );+ takes(input_schema_for::<ProfileListParams>(), &[(json!({}), true), (json!({"kind": "bar"}), false)]);+ takes(+ input_schema_for::<ProfilePropertiesParams>(),+ &[+ (json!({"profile": bar}), true),+ (json!({"profile": bar, "density": 7850}), true),+ (json!({"profile": bar, "density": null}), true),+ (json!({"profile": bar, "density": 0}), false),+ (json!({"profile": bar, "density": 1e6 + 1.0}), false),+ (json!({"density": 7850}), false),+ (json!({"profile": {"kind": "round_bar"}}), false),+ ],+ );+ takes(+ input_schema_for::<ProfileInsertParams>(),+ &[+ (json!({"profile": bar}), true),+ (json!({"profile": bar, "at": [1, 2], "anchor": "bottom", "angle": 2.5, "fixed": false, "sketch": "S"}), true),+ (json!({"profile": bar, "at": {"x": 1, "y": 2}, "sketch": 4}), true),+ (json!({}), false),+ (json!({"profile": bar, "at": [1, 2, 3]}), false),+ (json!({"profile": bar, "angle": 2e6}), false),+ (json!({"profile": bar, "fixed": "yes"}), false),+ (json!({"profile": bar, "sketch": 1.5}), false),+ ],+ );+}++/// The "not blank" patterns are the shared one, which `conforms` doesn't read: pin where they are.+#[test]+fn the_name_patterns_are_the_blank_pattern() {+ let blank = crate::schema::types::not_blank_pattern();+ let member = input_schema_for::<FrameMemberParams>();+ let member = member.as_value();+ assert_eq!(member["properties"]["body_name"]["anyOf"][0]["$ref"], json!("#/$defs/MemberName"));+ assert_eq!(member["$defs"]["MemberName"]["pattern"], json!(blank));+ assert_eq!(member["$defs"]["MemberNames"]["additionalProperties"]["pattern"], json!(blank));+ let properties = input_schema_for::<ProfilePropertiesParams>();+ let properties = properties.as_value();+ let kinds = properties["$defs"]["ProfileParam"]["anyOf"].as_array().cloned().unwrap_or_default();+ assert_eq!(kinds.len(), frame::profile_kinds().len());+ assert_eq!(kinds[0]["properties"]["width"]["anyOf"][1]["pattern"], json!(blank));+}++/// The warning for what a key gets wrong, and the check that every built-in kind is described.+#[test]+fn the_check_names_what_is_wrong_with_a_key() {+ let issues = |id: &str, p: Value| crate::schema::issues(id, &p).into_iter().map(|i| i.message).collect::<Vec<_>>();+ assert_eq!(issues("frame.profile.properties", json!({"profile": {"kind": "hexagon"}})).len(), 1);+ assert_eq!(+ issues("frame.profile.properties", json!({"profile": {"kind": "bar", "width": 1, "height": 1, "wall": 1}})),+ ["`profile`: a bar profile has no dimension `wall`"]+ );+ assert_eq!(issues("frame.profile.properties", json!({"profile": {"kind": "bar"}})), ["`profile`: a bar profile needs `width`"]);+ assert_eq!(+ issues("frame.profile.properties", json!({"profile": {"kind": "round_bar", "diameter": 1}, "density": -3})),+ ["`density` must be a positive number of kg/m³ (at most 1e6)"]+ );+ assert_eq!(+ issues("frame.profile.insert", json!({"profile": {"kind": "round_bar", "diameter": 1}, "at": 3})),+ ["`at` must be [x, y] in sketch millimetres"]+ );+ assert_eq!(+ issues("frame.profile.insert", json!({"profile": {"kind": "round_bar", "diameter": 1}, "fixed": "no"})),+ ["`fixed` must be true or false"]+ );+ assert_eq!(issues("frame.member", json!({"sketch": 1, "profile": tube(), "mirror": "no"})), ["`mirror` must be true or false"]);+ assert_eq!(issues("frame.member", json!({"sketch": 1, "profile": tube(), "lines": ["a", "a"]})), ["line `a` is listed twice"]);+ assert_eq!(+ issues("frame.member", json!({"sketch": 1, "profile": tube(), "body_names": ["a"]})),+ ["unknown key `body_names`; did you mean `body_name`?"]+ );+ // The schemas describe every built-in kind with its dimensions, and its example is one.+ let schema = input_schema_for::<ProfilePropertiesParams>();+ let schema = schema.as_value();+ for kind in frame::profile_kinds() {+ let example = serde_json::to_value(&kind.example).unwrap_or_default();+ let profile = json!({"profile": example});+ assert!(conforms(schema, schema, &profile), "{profile}");+ assert!(crate::schema::issues("frame.profile.properties", &profile).is_empty(), "{profile}");+ }+}++fn matches(schema: schemars::Schema, id: &str, reply: &Value) {+ let schema = schema.as_value();+ assert!(conforms(schema, schema, reply), "{id}: {reply} doesn't match {schema}");+ assert!(reply.get("param_warnings").is_none(), "{id}: {reply}");+}++/// The library's list and properties replies match the output schemas and are what the handlers+/// built before the typed replies: the same JSON.+#[test]+fn profile_library_replies_match_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 listed = run("frame.profile.list", json!({}));+ matches(output_schema_for::<ProfileListResult>(), "frame.profile.list", &listed);+ assert_eq!(listed, json!({"kinds": frame::profile_kinds()}));+ let kinds = listed["kinds"].as_array().cloned().unwrap_or_default();+ assert_eq!(kinds.len(), 7);+ for kind in &kinds {+ let r = run("frame.profile.properties", json!({"profile": kind["example"]}));+ matches(output_schema_for::<ProfilePropertiesResult>(), "frame.profile.properties", &r);+ let profile: frame::Profile = serde_json::from_value(kind["example"].clone()).unwrap_or_else(|e| panic!("{e}"));+ let region = profile.region().unwrap_or_else(|e| panic!("{e}"));+ let sec = frame::section(®ion);+ assert_eq!(+ r,+ json!({+ "profile": profile.filled(), "area": sec.area, "centroid": sec.centroid, "ixx": sec.ixx, "iyy": sec.iyy, "ixy": sec.ixy,+ "width": sec.width, "height": sec.height+ })+ );+ }+ let heavy = run("frame.profile.properties", json!({"profile": tube(), "density": 7850}));+ matches(output_schema_for::<ProfilePropertiesResult>(), "frame.profile.properties", &heavy);+ let area = heavy["area"].as_f64().unwrap_or_default();+ assert_eq!(heavy["mass_per_m"], json!(area * 1e-6 * 7850.0), "{heavy}");+ assert_eq!(heavy["profile"]["outer_radius"], json!(6.0), "{heavy}");+ // Dimensions as expressions, in a design with parameters.+ run("parameters.add", json!({"name": "wall", "expression": "3 mm"}));+ let by_parameter =+ run("frame.profile.properties", json!({"profile": {"kind": "rect_tube", "width": "40 mm", "height": 40, "wall": "wall"}, "density": null}));+ matches(output_schema_for::<ProfilePropertiesResult>(), "frame.profile.properties", &by_parameter);+ assert_eq!(by_parameter["area"], run("frame.profile.properties", json!({"profile": tube()}))["area"]);++ // A misspelt key still runs in Warn and says so, with a reply that matches.+ for (id, p) in [("frame.profile.list", json!({"kinds": true})), ("frame.profile.properties", json!({"profile": tube(), "densty": 7850}))] {+ let warned = run(id, p);+ assert!(warned["param_warnings"].as_array().is_some_and(|w| w.len() == 1), "{warned}");+ let schema =+ if id == "frame.profile.list" { output_schema_for::<ProfileListResult>() } else { output_schema_for::<ProfilePropertiesResult>() };+ assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");+ }+}++/// Insert a profile in every form, in Warn: each reply matches its output schema, carries no+/// warning and is what the handler built before.+#[test]+fn insert_replies_match_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 made = run("sketch.create", json!({"plane": "XY", "name": "Drawing"}));+ let id = made["sketch"].clone();+ let plain = run("frame.profile.insert", json!({"profile": tube()}));+ matches(output_schema_for::<ProfileInsertResult>(), "frame.profile.insert", &plain);+ assert_eq!(plain["created"]["curves"].as_array().map(Vec::len), Some(16), "{plain}");+ assert!(plain["sketch"]["solved"].is_boolean() && plain["sketch"]["dof"].is_u64(), "{plain}");+ let mut keys: Vec<&String> = plain.as_object().map(|o| o.keys().collect()).unwrap_or_default();+ keys.sort();+ assert_eq!(keys, ["created", "section", "sketch"]);+ let mut created: Vec<&String> = plain["created"].as_object().map(|o| o.keys().collect()).unwrap_or_default();+ created.sort();+ assert_eq!(created, ["constraints", "curves", "dimensions", "points"]);+ let section = run("frame.profile.properties", json!({"profile": tube()}));+ // The section is what the library computes for the profile, not just what the other command says.+ let profile: frame::Profile = serde_json::from_value(tube()).unwrap_or_else(|e| panic!("{e}"));+ let sec = frame::section(&profile.region().unwrap_or_else(|e| panic!("{e}")));+ assert_eq!(plain["section"]["area"], json!(sec.area), "{plain}");+ assert_eq!(plain["section"]["centroid"], json!(sec.centroid), "{plain}");+ assert_eq!(plain["section"]["profile"], serde_json::to_value(profile.filled()).unwrap_or_default(), "{plain}");+ assert_eq!(plain["section"], section);+ let placed = run(+ "frame.profile.insert",+ json!({+ "profile": {"kind": "channel", "height": "60 mm", "width": 45, "web": 5, "flange": 6},+ "at": [100, 50], "anchor": "bottom_left", "angle": 0.5, "fixed": false, "sketch": "Drawing"+ }),+ );+ matches(output_schema_for::<ProfileInsertResult>(), "frame.profile.insert", &placed);+ let by_id = run(+ "frame.profile.insert",+ json!({"profile": {"kind": "round_bar", "diameter": 20}, "sketch": id, "at": {"x": -50, "y": 5}, "anchor": null}),+ );+ matches(output_schema_for::<ProfileInsertResult>(), "frame.profile.insert", &by_id);+ assert_eq!(by_id["created"]["curves"].as_array().map(Vec::len), Some(1), "{by_id}");+ // A misspelt key still runs in Warn, and says so, with a reply that matches.+ let warned = run("frame.profile.insert", json!({"profile": {"kind": "round_bar", "diameter": 5}, "sketch": "Drawing", "ancor": "center"}));+ assert_eq!(warned["param_warnings"], json!(["unknown key `ancor`; did you mean `anchor`?"]), "{warned}");+ let schema = output_schema_for::<ProfileInsertResult>();+ assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");+}++/// Members in every form, in Warn: each reply matches `FeatureResult` and carries no warning.+#[test]+fn member_replies_match_the_output_schema() {+ let (mut s, lines) = frame_session(ParamCheck::Warn);+ let mut run = |p: Value| s.execute("frame.member", &p).unwrap_or_else(|e| panic!("{p}: {e}"));+ let first = lines.first().cloned().unwrap_or_default();+ let second = lines.get(1).cloned().unwrap_or_default();+ let calls = [+ json!({"sketch": "Frame", "profile": tube()}),+ json!({"sketch": "Frame", "profile": {"kind": "angle", "width": 60, "height": 40, "thickness": "5 mm"}, "lines": [first], "anchor": "bottom_left"}),+ json!({"sketch": "Frame", "profile": tube(), "lines": [first, second], "angle": "90 deg", "mirror": true, "name": "Rails", "body_name": "Rail"}),+ json!({"sketch": "Frame", "profile": tube(), "lines": [first], "angle": 45, "names": {first.clone(): "Chosen"}, "participants": "*"}),+ json!({"sketch": "Frame", "profile": tube(), "lines": null}),+ json!({"sketch": "Frame", "profile_sketch": "Section"}),+ json!({"sketch": "Frame", "profile_sketch": "Section", "profiles": [{"point": [0, 0]}], "exact_regions": true, "lines": [first], "anchor": "center"}),+ json!({"sketch": "Frame", "profile_sketch": "Section", "profiles": "all", "mirror": false, "angle": null, "names": null}),+ ];+ for p in calls {+ let reply = run(p.clone());+ matches(output_schema_for::<FeatureResult>(), "frame.member", &reply);+ assert!(reply["created_bodies"].as_array().is_some_and(|b| !b.is_empty()), "{p}: {reply}");+ }+ // By the id of the sketch.+ let by_id = s_first_sketch_call(&mut s, &first);+ matches(output_schema_for::<FeatureResult>(), "frame.member", &by_id);++ // A misspelt key still runs in Warn, and says so, with a reply that matches.+ let warned =+ s.execute("frame.member", &json!({"sketch": "Frame", "profile": tube(), "lines": [first], "profil": 1})).unwrap_or_else(|e| panic!("{e}"));+ assert_eq!(warned["param_warnings"], json!(["unknown key `profil`; did you mean `profile`?"]), "{warned}");+ let schema = output_schema_for::<FeatureResult>();+ assert!(conforms(schema.as_value(), schema.as_value(), &warned), "{warned}");+}++fn s_first_sketch_call(s: &mut Session, line: &str) -> Value {+ let id = first_sketch(s);+ s.execute("frame.member", &json!({"sketch": id, "profile": tube(), "lines": [line]})).unwrap_or_else(|e| panic!("{e}"))+}diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rsindex 0f4f743eff..8d5418f5f5 100644--- a/crates/engine/src/schema/mod.rs+++ b/crates/engine/src/schema/mod.rs@@ -70,6 +70,7 @@ pub mod edit;pub mod features;pub mod features_more;pub mod file;+pub mod frame;pub mod inspect;pub mod interference;pub mod joints;diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txtindex 6e405d3b64..0056e2c3c2 100644--- a/crates/engine/src/schema/unconverted.txt+++ b/crates/engine/src/schema/unconverted.txt@@ -23,10 +23,6 @@ file.savefile.save_asfile.save_meshfile.slicers-frame.member-frame.profile.insert-frame.profile.list-frame.profile.propertiesinspect.measurejoint.camjoint.gear