Sheet metal feature commands: typed parameter contracts (#6581) (#6582)

* claim: sheet.* typed parameter schemas

* Sheet metal feature commands: typed parameter contracts

sheet.flange, sheet.perforate, sheet.hem, sheet.fold, sheet.unfold, sheet.refold and
sheet.convert read their parameters by hand, so a misspelt key or a value of the wrong
shape was ignored or failed late, and describe_command had only prose for them.

Each now has a contract in schema/sheet.rs, checked in front of the unchanged handler,
and returns FeatureResult. The values no shared type fits (sheet-edge points, an edge
flange's edges, a fold's line and fixed point, the flange type, the positions, the
relief shape and the perforation pattern) get types that call the handlers' own
readers, split out of cmd/sheet.rs, and give their messages. The rule's values
(thickness, K-factor, bend radius, reliefs) stay out of the contracts: the handlers
refuse them, and strict refuses them as unknown keys.

A test passed a nested `base` object whose `sketch` the flange never reads; it now
names the sketch at the top level.

Part of #2829 (#6581).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Sheet metal contracts: a further bend's angle stays as lenient as before

The flange handler reads a `then` bend's `angle` that is no expression
(`true`, a list) as left out and bends it 90 degrees. The rebased
contract had moved that check into the shared reader, so the handler
refused such a call even with the check off.

The reader is back to the handler's behaviour, and `ThenSteps` is the
stricter one, as the schema guide asks: warn reports such an angle and
strict refuses it. Tests cover the reader's leniency, the type's
refusal and the three check levels on one flange.

Part of #2829 (#6581).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NOWN-DEV
2026-10-28 22:01:35 +00:00
committed by GitHub
parent f1ab19422b
commit eb29c4b2d8
7 changed files with 1087 additions and 77 deletions
+1
View File
@@ -58,6 +58,7 @@ pub mod component;
pub mod edit;
pub mod features;
pub mod inspect;
pub mod sheet;
pub mod sketch_constraints;
pub mod sketch_create;
pub mod view_navigation;
+550
View File
@@ -0,0 +1,550 @@
//! Contracts for the sheet metal feature commands in `cmd/sheet.rs`. They all return
//! [`FeatureResult`](super::features::FeatureResult).
//!
//! A sheet metal rule sets the sheet's thickness, K-factor, bend radius and reliefs: the
//! commands refuse those keys with a pointer to `sheet.manage_rules`, so they are no keys of
//! these contracts (strict refuses them as unknown keys). The same goes for the nested `base`
//! object an old base flange call may carry, which the handler reads only to refuse rule keys
//! in it.
//!
//! The value types below are used by these commands only. Like the shared ones in
//! [`types`](super::types), each calls the handler's own reader (split out of `cmd/sheet.rs`)
//! and gives its message.
use std::borrow::Cow;
use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::de::Error as _;
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use solidcraft_doc::FlangeEdge;
use solidcraft_geom::Vec3;
use super::check::whole;
use super::types::{AngleExpr, FaceRef, FeatureCommon, IdOrName, LengthExpr, Point3, ProfilesParam, SketchRef, StringList, feature_common, present};
/// Points on sheet edges, as the `edges` of a hem and the `bends` of a conversion: 1 to 1000
/// points `[x, y, z]`, `{x, y, z}` or `{point}` (read by `sheet::sheet_points`).
#[derive(Clone, Debug, PartialEq)]
pub struct SheetPoints(pub Vec<Vec3>);
impl<'de> Deserialize<'de> for SheetPoints {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
crate::cmd::sheet_points(Some(&Value::deserialize(d)?)).map(SheetPoints).map_err(D::Error::custom)
}
}
impl JsonSchema for SheetPoints {
fn schema_name() -> Cow<'static, str> {
"SheetPoints".into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let point = generator.subschema_for::<Point3>();
json_schema!({
"description": "Points in mm on sheet edges, 1 to 1000: each [x, y, z], {\"x\", \"y\", \"z\"} or {\"point\": [x, y, z]}.",
"type": "array",
"items": {"anyOf": [point, {"type": "object", "properties": {"point": point}, "required": ["point"]}]},
"minItems": 1,
"maxItems": 1000
})
}
}
/// The `edges` of an edge flange: 1 to 1000 points on sheet edges, each `[x, y, z]` (or
/// `{x, y, z}`) or `{point, angle?, height?}` for an edge with its own angle and height (read by
/// `sheet::flange_edge`). Whether the expressions suit the design is checked by the handler.
#[derive(Clone, Debug, PartialEq)]
pub struct FlangeEdges(pub Vec<FlangeEdge>);
impl<'de> Deserialize<'de> for FlangeEdges {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = Value::deserialize(d)?;
let items = crate::cmd::flange_edge_list(Some(&v)).map_err(|why| D::Error::custom(whole(why)))?;
items
.iter()
.enumerate()
.map(|(i, item)| crate::cmd::flange_edge(i, item).map_err(|why| D::Error::custom(whole(why))))
.collect::<Result<_, _>>()
.map(FlangeEdges)
}
}
impl JsonSchema for FlangeEdges {
fn schema_name() -> Cow<'static, str> {
"FlangeEdges".into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let point = generator.subschema_for::<Point3>();
let angle = generator.subschema_for::<AngleExpr>();
let height = generator.subschema_for::<LengthExpr>();
json_schema!({
"description": "Points in mm on the sheet's top or bottom edges, 1 to 1000: each [x, y, z] or {\"x\", \"y\", \"z\"}, or {\"point\": [x, y, z], \"angle\"?, \"height\"?} for an edge with its own angle and height (null: the feature's).",
"type": "array",
"items": {
"anyOf": [
// An object with any of the edge's keys is an edge, never a bare point.
{"anyOf": [point], "not": {"type": "object", "anyOf": [{"required": ["point"]}, {"required": ["angle"]}, {"required": ["height"]}]}},
{
"type": "object",
"properties": {"point": point, "angle": {"anyOf": [angle, {"type": "null"}]}, "height": {"anyOf": [height, {"type": "null"}]}},
"required": ["point"],
"additionalProperties": false
}
]
},
"minItems": 1,
"maxItems": 1000
})
}
}
/// A fold line's two ends, `[[x, y, z], [x, y, z]]` (read by `sheet::fold_points`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FoldPoints(pub Vec3, pub Vec3);
impl<'de> Deserialize<'de> for FoldPoints {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
crate::cmd::fold_points(&Value::deserialize(d)?).map(|(a, b)| FoldPoints(a, b)).map_err(D::Error::custom)
}
}
impl JsonSchema for FoldPoints {
fn schema_name() -> Cow<'static, str> {
"FoldPoints".into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let point = generator.subschema_for::<Point3>();
json_schema!({"description": "The fold line's two ends, in mm.", "type": "array", "items": point, "minItems": 2, "maxItems": 2})
}
}
/// A point in mm, `[x, y, z]` or `{x, y, z}`, with a fold's message for `fixed` (`Point3` says
/// "of numbers" after it).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FixedPoint(pub Vec3);
impl<'de> Deserialize<'de> for FixedPoint {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
crate::params::vec3(&Value::deserialize(d)?).map(FixedPoint).ok_or_else(|| D::Error::custom("must be a point [x, y, z]"))
}
}
impl JsonSchema for FixedPoint {
fn schema_name() -> Cow<'static, str> {
"FixedPoint".into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
Point3::json_schema(generator)
}
}
/// A flange's `type`, in any case (read by `sheet::flange_type`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FlangeTypeParam(pub(crate) crate::cmd::FlangeType);
impl<'de> Deserialize<'de> for FlangeTypeParam {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = Value::deserialize(d)?;
let t = v.as_str().ok_or_else(|| D::Error::custom("must be base, edge or contour"))?;
crate::cmd::flange_type(t).map(FlangeTypeParam).map_err(|why| D::Error::custom(whole(why)))
}
}
impl JsonSchema for FlangeTypeParam {
fn schema_name() -> Cow<'static, str> {
"FlangeType".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "base, edge or contour, in any case.",
"type": "string",
"pattern": "^([Bb][Aa][Ss][Ee]|[Ee][Dd][Gg][Ee]|[Cc][Oo][Nn][Tt][Oo][Uu][Rr])$"
})
}
}
/// A word from a short list, in any case, read by a handler's reader that returns `None` for
/// any other text; `$message` is the handler's.
macro_rules! word {
($(#[$doc:meta])* $name:ident, $reader:path, $message:literal, $description:literal, [$($word:literal),+]) => {
$(#[$doc])*
#[derive(Clone, Debug, PartialEq)]
pub struct $name(pub String);
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Value::deserialize(d)?.as_str().and_then($reader).map($name).ok_or_else(|| D::Error::custom($message))
}
}
impl JsonSchema for $name {
fn schema_name() -> Cow<'static, str> {
stringify!($name).into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
let any_case = |w: &str| w.chars().map(|c| format!("[{}{}]", c.to_ascii_uppercase(), c)).collect::<String>();
let words: Vec<String> = [$($word),+].iter().map(|w| any_case(w)).collect();
json_schema!({"description": $description, "type": "string", "pattern": format!("^({})$", words.join("|"))})
}
}
};
}
word!(
/// An edge flange's `position` (read by `sheet::flange_position`).
FlangePosition,
crate::cmd::flange_position,
"must be inside, outside, middle, material_outside or tangent",
"inside, outside (bend_outside is the same), middle, material_outside or tangent, in any case.",
["inside", "outside", "bend_outside", "middle", "material_outside", "tangent"]
);
word!(
/// A fold's `position` (read by `sheet::fold_position`).
FoldPosition,
crate::cmd::fold_position,
"must be centerline, start, end or mould",
"centerline, start, end or mould (or mold), in any case.",
["centerline", "start", "end", "mould", "mold"]
);
/// A corner relief's shape: notch, round, rectangular or tear, in any case and with blanks
/// around it (read by `ReliefShape::parse`).
#[derive(Clone, Debug, PartialEq)]
pub struct ReliefShapeParam(pub solidcraft_doc::sheet::ReliefShape);
impl<'de> Deserialize<'de> for ReliefShapeParam {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Value::deserialize(d)?
.as_str()
.and_then(solidcraft_doc::sheet::ReliefShape::parse)
.map(ReliefShapeParam)
.ok_or_else(|| D::Error::custom("must be notch, round, rectangular or tear"))
}
}
impl JsonSchema for ReliefShapeParam {
fn schema_name() -> Cow<'static, str> {
"ReliefShape".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "notch, round, rectangular or tear, in any case (blanks around it are ignored).",
"type": "string",
"pattern": format!("^{blank}({words}){blank}$", blank = blanks(), words = "[Nn][Oo][Tt][Cc][Hh]|[Rr][Oo][Uu][Nn][Dd]|[Rr][Ee][Cc][Tt][Aa][Nn][Gg][Uu][Ll][Aa][Rr]|[Tt][Ee][Aa][Rr]")
})
}
}
/// Where an edge flange's height is measured from: outer, inner or tangent, in any case and with
/// blanks around it (read by `HeightFrom::parse`).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HeightFromParam(pub solidcraft_doc::sheet::HeightFrom);
impl<'de> Deserialize<'de> for HeightFromParam {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Value::deserialize(d)?
.as_str()
.and_then(solidcraft_doc::sheet::HeightFrom::parse)
.map(HeightFromParam)
.ok_or_else(|| D::Error::custom("must be outer, inner or tangent"))
}
}
impl JsonSchema for HeightFromParam {
fn schema_name() -> Cow<'static, str> {
"HeightFrom".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({
"description": "outer, inner or tangent, in any case (blanks around it are ignored).",
"type": "string",
"pattern": format!("^{blank}({words}){blank}$", blank = blanks(), words = "[Oo][Uu][Tt][Ee][Rr]|[Ii][Nn][Nn][Ee][Rr]|[Tt][Aa][Nn][Gg][Ee][Nn][Tt]")
})
}
}
/// An edge flange's further bends (`then`): up to 16, each `{angle?, height, flip?}`, made on the
/// far edge of the flange before it (read by `sheet::then_list`). Whether the expressions suit
/// the design is checked by the handler. The handler reads an `angle` that is no expression as
/// left out (90°); this type refuses it.
#[derive(Clone, Debug, PartialEq)]
pub struct ThenSteps(pub Vec<crate::cmd::ThenStep>);
impl<'de> Deserialize<'de> for ThenSteps {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = Value::deserialize(d)?;
let steps = crate::cmd::then_list(Some(&v)).map_err(|why| D::Error::custom(whole(why)))?;
let bends = v.as_array().map(Vec::as_slice).unwrap_or_default();
let wrong = bends
.iter()
.enumerate()
.find_map(|(i, b)| b.get("angle").filter(|a| !a.is_null() && crate::params::expr(b, "angle").is_none()).map(|a| (i, a)));
match wrong {
Some((i, a)) => Err(D::Error::custom(whole(format!("then[{i}]: `angle` {}", crate::params::expr_problem(Some(a)))))),
None => Ok(ThenSteps(steps)),
}
}
}
impl JsonSchema for ThenSteps {
fn schema_name() -> Cow<'static, str> {
"ThenSteps".into()
}
fn json_schema(generator: &mut SchemaGenerator) -> Schema {
let angle = generator.subschema_for::<AngleExpr>();
let height = generator.subschema_for::<LengthExpr>();
json_schema!({
"description": "Further bends, at most 16, each a flange on the far edge of the one before: its height, its angle (default 90 deg) and flip (true turns that bend the other way; default: the flange's).",
"type": "array",
"items": {
"type": "object",
"properties": {"angle": {"anyOf": [angle, {"type": "null"}]}, "height": height, "flip": {"type": ["boolean", "null"]}},
"required": ["height"],
"additionalProperties": false
},
"maxItems": 16
})
}
}
/// Any run of the characters Rust's `trim` removes, as a regex.
fn blanks() -> String {
let u = |c: char| format!("\\u{:04x}", c as u32);
let class: String = super::types::WHITESPACE.iter().map(|&(a, b)| if a == b { u(a) } else { format!("{}-{}", u(a), u(b)) }).collect();
format!("[{class}]*")
}
/// A perforation's `pattern` (read by `sheet::perforation_pattern`).
#[derive(Clone, Debug, PartialEq)]
pub struct PerforationPattern(pub String);
impl<'de> Deserialize<'de> for PerforationPattern {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = Value::deserialize(d)?;
let t = v.as_str().unwrap_or_default();
crate::cmd::perforation_pattern(t).map(|t| PerforationPattern(t.to_string())).map_err(|why| D::Error::custom(whole(why)))
}
}
impl JsonSchema for PerforationPattern {
fn schema_name() -> Cow<'static, str> {
"PerforationPattern".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"description": "staggered (rows offset for a 60° pattern) or square, lower case.", "enum": ["staggered", "square"]})
}
}
/// Add a sheet metal flange: a base flange from sketch profiles, a contour flange along an open
/// chain of sketch lines, or edge flanges on a sheet's edges. Thickness, K-factor, bend radius
/// and reliefs come from the sheet metal rule (`sheet.manage_rules`), so those keys are refused;
/// an edge flange may set its own `radius` and corner relief. `participants` changes nothing.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct FlangeParams {
/// Which flange: base, edge or contour, in any case. Default: edge when `edges` is given,
/// else contour when `curves` is given, else base.
#[serde(default)]
pub r#type: Option<FlangeTypeParam>,
/// Base and contour: the sketch, by id or name. A base flange's default is the active sketch,
/// else the last one; a contour flange needs it.
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
#[schemars(with = "IdOrName")]
pub sketch: Option<IdOrName>,
/// Base: which of the sketch's profiles become the sheet. Default: all of them.
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
#[schemars(with = "ProfilesParam")]
pub profiles: Option<ProfilesParam>,
/// Base and contour: the sheet metal rule, by name. Default: the active rule. Ignored by an
/// edge flange, which takes its sheet's.
#[serde(default)]
pub rule: Option<String>,
/// Base: the thickness goes to the other side of the sketch plane. Contour: the material goes
/// to the other side of the chain. Edge: the flanges bend the other way. Default: false.
#[serde(default)]
pub flip: Option<bool>,
/// Contour: the open chain's lines (curve ids; arcs aren't supported yet), 1 to 1000.
#[serde(default)]
pub curves: Option<StringList>,
/// Contour: how far the flange runs from the sketch plane, positive.
#[serde(default)]
pub distance: Option<LengthExpr>,
/// Contour: the flange runs from the sketch plane the other way. Default: false.
#[serde(default)]
pub reverse: Option<bool>,
/// Edge: the edges that get a flange.
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
#[schemars(with = "FlangeEdges")]
pub edges: Option<FlangeEdges>,
/// Edge: each flange's height, along the flange to its far edge, from where `height_from` says
/// (an edge's own `height` replaces it). Required for an edge flange.
#[serde(default)]
pub height: Option<LengthExpr>,
/// Edge: where the height is measured from: the outer virtual sharp (outer), the inner virtual
/// sharp (inner), or past 90° the line square to the flange touching the bend's outside
/// (tangent; up to 90° the outer sharp). Default: outer.
#[serde(default)]
pub height_from: Option<HeightFromParam>,
/// Edge: the bend angle, more than 0 and at most 180° (an edge's own `angle` replaces it).
/// Default: 90 deg.
#[serde(default)]
pub angle: Option<AngleExpr>,
/// Edge: the inner bend radius. Default: the sheet's rule's.
#[serde(default)]
pub radius: Option<LengthExpr>,
/// Edge: where the bend starts: inside (the outer virtual sharp on the edge), outside or
/// bend_outside (the bend starting at the edge), middle (half-way), material_outside (the
/// inner virtual sharp on the edge) or tangent (the bend's outer face tangent to the edge's
/// face; below 90° the bend's end on that face). Default: inside.
#[serde(default)]
pub position: Option<FlangePosition>,
/// Edge: the sheet metal body. Default: the sheet with an edge nearest the first point.
#[serde(default)]
pub body: Option<String>,
/// Edge: the shape of the relief cut where these flanges meet at a corner, in place of the
/// rule's. Refused on a base or contour flange.
#[serde(default)]
pub corner_relief_shape: Option<ReliefShapeParam>,
/// Edge: the size across of a round or rectangular corner relief, in place of the rule's.
/// Refused on a base or contour flange.
#[serde(default)]
pub corner_relief: Option<LengthExpr>,
/// Edge: further bends, each a flange on the far edge of the one before (at most 16). Refused
/// on a base or contour flange.
#[serde(default)]
pub then: Option<ThenSteps>,
#[serde(flatten, deserialize_with = "feature_common")]
pub common: FeatureCommon,
}
/// Add a field of round perforations over a whole flat sheet: holes in the flat pattern, the DXF
/// (layer PERFORATION) and the measured volume, not cut into the solid. `participants` changes
/// nothing.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct PerforateParams {
/// The holes' diameter, more than 0.
pub diameter: LengthExpr,
/// The distance between hole centres, more than the diameter.
pub pitch: LengthExpr,
/// How far the holes stay clear of the sheet's edges, cut-outs and bends, at least 0.
/// Default: the diameter.
#[serde(default)]
pub margin: Option<LengthExpr>,
/// How the holes are laid out. Default: staggered.
#[serde(default)]
pub pattern: Option<PerforationPattern>,
/// The sheet metal body. Default: the newest sheet.
#[serde(default)]
pub body: Option<String>,
#[serde(flatten, deserialize_with = "feature_common")]
pub common: FeatureCommon,
}
/// Add hems: the sheet folded back on itself along edges. `participants` changes nothing.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct HemParams {
/// The edges to hem.
pub edges: SheetPoints,
/// The hem's length, to its outer face.
pub length: LengthExpr,
/// The gap inside the hem (its inner radius). Default: the sheet's rule's hem gap.
#[serde(default)]
pub gap: Option<LengthExpr>,
/// Hem to the other side. Default: false.
#[serde(default)]
pub flip: Option<bool>,
/// The sheet metal body. Default: the sheet with an edge nearest the first point.
#[serde(default)]
pub body: Option<String>,
#[serde(flatten, deserialize_with = "feature_common")]
pub common: FeatureCommon,
}
/// Fold a sheet along a line on its top or bottom face: a sketch line (followed when the sketch
/// changes) or two points. The bend zone comes out of the sheet, so the flat pattern keeps its
/// size. `participants` changes nothing.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct FoldParams {
/// The fold line's two ends, instead of `sketch` and `curve`.
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
#[schemars(with = "FoldPoints")]
pub points: Option<FoldPoints>,
/// The sketch holding the fold line, by id or name. Required unless `points` is given;
/// ignored then.
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
#[schemars(with = "SketchRef")]
pub sketch: Option<SketchRef>,
/// The fold line: a line of `sketch`, by id. Required unless `points` is given; ignored then.
#[serde(default)]
pub curve: Option<String>,
/// The bend angle. Default: 90 deg.
#[serde(default)]
pub angle: Option<AngleExpr>,
/// The inner bend radius. Default: the sheet's rule's.
#[serde(default)]
pub radius: Option<LengthExpr>,
/// Where the line sits in the bend zone: its centre (centerline), its start or end, from the
/// side that stays, or the mould line (mould: where the outer faces meet). Default:
/// centerline.
#[serde(default)]
pub position: Option<FoldPosition>,
/// A point on the side that stays, on the sheet. Default: the larger side (on a flange, the
/// side toward its own bend).
#[serde(default, deserialize_with = "present", skip_serializing_if = "Option::is_none")]
#[schemars(with = "FixedPoint")]
pub fixed: Option<FixedPoint>,
/// Fold the other way. Default: false.
#[serde(default)]
pub flip: Option<bool>,
/// The sheet metal body. Default: the sheet with an edge nearest the line's middle.
#[serde(default)]
pub body: Option<String>,
#[serde(flatten, deserialize_with = "feature_common")]
pub common: FeatureCommon,
}
/// Unfold every bend of a sheet (`sheet.unfold`), or fold an unfolded sheet back
/// (`sheet.refold`). `participants` changes nothing.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct UnfoldParams {
/// The sheet metal body. Default: the last folded sheet (unfold) or the last unfolded one
/// (refold).
#[serde(default)]
pub body: Option<String>,
#[serde(flatten, deserialize_with = "feature_common")]
pub common: FeatureCommon,
}
/// Turn a body into sheet metal. Without `bends`, a plate of even thickness: its large flat face
/// becomes the sheet, holes become cut-outs and recesses in one face up to half the thickness
/// deep (an engraved label) become pockets. With `bends`, a solid or shelled body: `face` stays
/// put and the flat faces reached from it across those edges become the sheet; a shell keeps its
/// thickness, a solid takes the rule's inward, and edges between two of those faces that are no
/// bends are cut open with the rule's gap. `participants` changes nothing.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ConvertParams {
/// The body to convert.
pub body: String,
/// Its large flat face (a plate), or the face that stays put (with `bends`).
pub face: FaceRef,
/// The sharp edges that become bends of the rule's radius at their virtual sharp. A point in
/// the middle of a chamfer between two faces, or on a bend modelled with its radius (a
/// cylinder tangent to two flat faces, either skin), makes it one bend. Default: none (a
/// plate).
#[serde(default)]
pub bends: Option<SheetPoints>,
/// The sheet metal rule, by name. Default: the active rule. A plate keeps its own thickness.
#[serde(default)]
pub rule: Option<String>,
#[serde(flatten, deserialize_with = "feature_common")]
pub common: FeatureCommon,
}
#[cfg(test)]
#[path = "sheet_tests.rs"]
mod tests;
+357
View File
@@ -0,0 +1,357 @@
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use super::{
ConvertParams, FixedPoint, FlangeEdges, FlangeParams, FlangePosition, FlangeTypeParam, FoldParams, FoldPoints, FoldPosition, HeightFromParam,
HemParams, PerforateParams, PerforationPattern, ReliefShapeParam, SheetPoints, ThenSteps, UnfoldParams,
};
use crate::Session;
use crate::schema::features::FeatureResult;
use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
/// The built-in rule's name, which a design without rules uses.
const STEEL: &str = "Steel (mm)";
/// A command's own keys and `FeatureCommon`'s, sorted.
fn keys(own: &[&'static str]) -> Vec<&'static str> {
let mut k = own.to_vec();
k.extend(["body_name", "body_names", "name", "participants"]);
k.sort_unstable();
k
}
/// A 100 × 60 sheet of the default rule (2.5 thick) from sketch `Base`, and a 100 × 60 × 2.5
/// box `Plate` beside it.
fn sheet() -> Session {
let mut s = Session::default();
for (id, p) in [
("sketch.create", json!({"plane": "XY", "name": "Base"})),
("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [100, 60]})),
("sketch.finish", json!({})),
("sheet.flange", json!({"sketch": "Base"})),
("solid.box", json!({"length": 100, "width": 60, "height": 2.5, "corner": [0, 100, 0], "body_name": "Plate"})),
] {
if let Err(e) = s.execute(id, &p) {
panic!("{id}: {e}");
}
}
s
}
#[test]
fn schemas_and_the_key_check_agree() {
assert_keys(
input_schema_for::<FlangeParams>(),
&keys(&[
"angle",
"body",
"corner_relief",
"corner_relief_shape",
"curves",
"distance",
"edges",
"flip",
"height",
"height_from",
"position",
"profiles",
"radius",
"reverse",
"rule",
"sketch",
"then",
"type",
]),
);
assert_keys(input_schema_for::<PerforateParams>(), &keys(&["body", "diameter", "margin", "pattern", "pitch"]));
assert_keys(input_schema_for::<HemParams>(), &keys(&["body", "edges", "flip", "gap", "length"]));
assert_keys(input_schema_for::<FoldParams>(), &keys(&["angle", "body", "curve", "fixed", "flip", "points", "position", "radius", "sketch"]));
assert_keys(input_schema_for::<UnfoldParams>(), &keys(&["body"]));
assert_keys(input_schema_for::<ConvertParams>(), &keys(&["bends", "body", "face", "rule"]));
}
fn parse<T: DeserializeOwned>(v: Value) -> Option<T> {
serde_json::from_value(v).ok()
}
/// Whether `T` accepts `v` and its schema agrees.
fn takes<T: DeserializeOwned + schemars::JsonSchema>(v: &Value) -> bool {
let schema = input_schema_for::<T>();
let schema = schema.as_value();
let accepted = parse::<T>(v.clone()).is_some();
assert_eq!(conforms(schema, schema, v), accepted, "{v}: the schema and the reader disagree");
accepted
}
/// The value types accept what the handlers' readers accept, and their schemas agree (apart
/// from the word types' patterns, which the test validator doesn't read: those are checked on
/// the readers alone).
#[test]
fn the_value_types_match_the_readers() {
let many = |n: usize| Value::Array(vec![json!([1, 2, 3]); n]);
for (v, ok) in [
(json!([[1, 2, 3]]), true),
(json!([{"x": 1, "y": 2, "z": 3}, {"point": [1, 2, 3]}, {"point": {"x": 1, "y": 2, "z": 3}, "body": "B"}]), true),
(many(1000), true),
(many(1001), false),
(json!([]), false),
(json!([[1, 2]]), false),
(json!([{"point": [1, 2]}]), false),
(json!([[1e10, 0, 0]]), false),
(json!(5), false),
(json!(null), false),
] {
assert_eq!(takes::<SheetPoints>(&v), ok, "{v}");
assert_eq!(parse::<SheetPoints>(v.clone()).map(|p| p.0), crate::cmd::sheet_points(Some(&v)).ok(), "{v}");
}
for (v, ok) in [
(json!([[1, 2, 3], {"x": 1, "y": 2, "z": 3}]), true),
(json!([{"point": [1, 2, 3]}, {"point": [1, 2, 3], "angle": "30 deg", "height": 5}, {"point": [1, 2, 3], "angle": null}]), true),
(many(1000), true),
(many(1001), false),
(json!([{"x": 1, "y": 2, "z": 3, "point": [1, 2, 3]}]), false),
(json!([{"x": 1, "y": 2, "z": 3, "angle": 30}]), false),
(json!([{"angle": 30}]), false),
(json!([{"point": [1, 2, 3], "depth": 1}]), false),
(json!([{"point": [1, 2, 3], "angle": true}]), false),
(json!([{"point": [1, 2]}]), false),
(json!([[1, 2]]), false),
(json!([]), false),
(json!(null), false),
] {
assert_eq!(takes::<FlangeEdges>(&v), ok, "{v}");
}
let bends = |n: usize| Value::Array(vec![json!({"height": 10}); n]);
for (v, ok) in [
(json!([{"height": 10}]), true),
(json!([{"height": 10, "angle": "45 deg", "flip": true}, {"height": "5 mm", "angle": null, "flip": null}]), true),
(json!([]), true),
(bends(16), true),
(bends(17), false),
(json!([{"angle": 30}]), false),
(json!([{"height": 10, "depth": 1}]), false),
(json!([{"height": 10, "flip": "yes"}]), false),
(json!([5]), false),
(json!(5), false),
] {
assert_eq!(takes::<ThenSteps>(&v), ok, "{v}");
assert_eq!(parse::<ThenSteps>(v.clone()).map(|t| t.0), crate::cmd::then_list(Some(&v)).ok(), "{v}");
}
// The handler reads a bend's `angle` that is no expression as left out (90°); the type
// refuses it, which is what warn and strict report.
for angle in [json!(true), json!([45])] {
let v = json!([{"height": 10, "angle": angle}]);
assert!(!takes::<ThenSteps>(&v), "{v}");
assert_eq!(crate::cmd::then_list(Some(&v)), crate::cmd::then_list(Some(&json!([{"height": 10}]))), "{v}");
}
for (v, ok) in [
(json!([[0, 0, 0], [1, 1, 1]]), true),
(json!([{"x": 0, "y": 0, "z": 0}, [1, 1, 1]]), true),
(json!([[0, 0, 0]]), false),
(json!([[0, 0, 0], [1, 1]]), false),
(json!([[0, 0, 0], [1, 1, 1], [2, 2, 2]]), false),
(json!(null), false),
] {
assert_eq!(takes::<FoldPoints>(&v), ok, "{v}");
}
for (v, ok) in [(json!([1, 2, 3]), true), (json!({"x": 1, "y": 2, "z": 3}), true), (json!([1, 2]), false), (json!(null), false)] {
assert_eq!(takes::<FixedPoint>(&v), ok, "{v}");
}
for (v, ok) in [
(json!("staggered"), true),
(json!("square"), true),
(json!("Square"), false),
(json!("hex"), false),
(json!(5), false),
(json!(null), false),
] {
assert_eq!(takes::<PerforationPattern>(&v), ok, "{v}");
}
let words = |accepted: &[&str], refused: &[Value], read: &dyn Fn(Value) -> bool| {
for w in accepted {
assert!(read(json!(w)), "{w}");
}
for v in refused {
assert!(!read(v.clone()), "{v}");
}
};
words(&["base", "Edge", "CONTOUR"], &[json!("sideways"), json!(""), json!(5)], &|v| parse::<FlangeTypeParam>(v).is_some());
words(
&["inside", "Outside", "MIDDLE", "bend_outside", "Material_Outside", "TANGENT"],
&[json!("mid"), json!(" inside"), json!("material outside"), json!(""), json!(3)],
&|v| parse::<FlangePosition>(v).is_some(),
);
words(&["outer", " Inner ", "TANGENT"], &[json!("sharp"), json!(""), json!(5)], &|v| parse::<HeightFromParam>(v).is_some());
words(&["centerline", "Start", "END", "mould", "Mold"], &[json!("center"), json!("side"), json!(null)], &|v| parse::<FoldPosition>(v).is_some());
words(&["notch", " Round ", "rectangular", "TEAR"], &[json!("oval"), json!(""), json!(5)], &|v| parse::<ReliefShapeParam>(v).is_some());
}
#[test]
fn strict_keeps_todays_errors() {
assert_strict_keeps_todays_errors(&[
("sheet.flange", json!({"type": "sideways"})),
("sheet.flange", json!({"type": "EDGEWAYS", "edges": [[0, 0, 0]], "height": 10})),
("sheet.flange", json!({"edges": [], "height": 10})),
("sheet.flange", json!({"edges": 5, "height": 10})),
("sheet.flange", json!({"edges": [[0, 0]], "height": 10})),
("sheet.flange", json!({"edges": [[0, 0, 0], {"point": [0, 0, 0], "depth": 3}], "height": 10})),
("sheet.flange", json!({"edges": [{"point": [0, 0]}], "height": 10})),
("sheet.flange", json!({"edges": [{"point": [0, 0, 0], "angle": true}], "height": 10})),
("sheet.flange", json!({"edges": [{"point": [0, 0, 0], "height": " "}], "height": 10})),
("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "position": "nowhere"})),
("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "height_from": "sharp"})),
("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "then": 5})),
("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "then": [{"angle": 30}]})),
("sheet.flange", json!({"edges": [[0, 0, 0]], "height": 10, "then": [{"height": 5, "turn": 1}]})),
("sheet.perforate", json!({"diameter": 2, "pitch": 5, "pattern": "hex"})),
("sheet.perforate", json!({"diameter": 2, "pitch": 5, "pattern": "Square"})),
("sheet.hem", json!({"edges": [], "length": 5})),
("sheet.hem", json!({"edges": 5, "length": 5})),
("sheet.hem", json!({"edges": null, "length": 5})),
("sheet.hem", json!({"edges": [[1, 2]], "length": 5})),
("sheet.fold", json!({"points": [[0, 0, 0]]})),
("sheet.fold", json!({"points": [[0, 0, 0], [1, 2]]})),
("sheet.fold", json!({"points": null})),
("sheet.fold", json!({"points": [[0, 0, 0], [10, 0, 0]], "position": "side"})),
("sheet.fold", json!({"points": [[0, 0, 0], [10, 0, 0]], "fixed": [1, 2]})),
("sheet.fold", json!({"points": [[0, 0, 0], [10, 0, 0]], "fixed": null})),
("sheet.fold", json!({"sketch": true, "curve": "l1"})),
("sheet.convert", json!({"body": "Nothing", "face": [0, 0, 0]})),
]);
// Calls that get past the handler's first checks only on a sheet.
for (id, p) in [
("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20, "corner_relief_shape": "oval"})),
("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20, "corner_relief_shape": 5})),
("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": []})),
("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": [[1, 2]]})),
("sheet.convert", json!({"body": "Plate", "face": ""})),
("sheet.convert", json!({"body": "Plate", "face": true})),
] {
let error = |level: ParamCheck| {
let mut s = sheet();
s.param_check = level;
s.execute(id, &p).err().map(|e| e.to_string())
};
let off = error(ParamCheck::Off);
assert!(off.is_some(), "{p} should fail today");
assert_eq!(error(ParamCheck::Strict), off, "{p}");
}
}
/// A rule's value given to a flange or a bent conversion is refused either way: by the handler,
/// which points to `sheet.manage_rules`, and in strict as a key the command doesn't take.
#[test]
fn rule_values_are_refused_with_the_check_off_and_in_strict() {
for (id, p, key) in [
("sheet.flange", json!({"sketch": "Base", "thickness": 2}), "thickness"),
("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20, "k_factor": 0.4}), "k_factor"),
("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": [[50, 100, 1.25]], "bend_radius": 2}), "bend_radius"),
] {
let error = |level: ParamCheck| {
let mut s = sheet();
s.param_check = level;
s.execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default()
};
let off = error(ParamCheck::Off);
assert!(off.contains(&format!("`{key}` is not a {id} parameter: the sheet metal rule sets it")), "{p}: {off}");
assert!(error(ParamCheck::Strict).contains(&format!("unknown key `{key}`")), "{p}");
}
}
/// A further bend's `angle` that is no expression: with the check off the flange bends it 90°,
/// as before; warn reports it and strict refuses it.
#[test]
fn a_bend_angle_that_is_no_expression_is_reported() {
let p = json!({"edges": [[0, 30, 2.5]], "height": 12, "then": [{"height": 8, "angle": true}]});
let want = "then[0]: `angle` must be a number or an expression";
let run = |level: ParamCheck| {
let mut s = sheet();
s.param_check = level;
s.execute("sheet.flange", &p)
};
let off = run(ParamCheck::Off).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(off.get("param_warnings"), None, "{off}");
let warn = run(ParamCheck::Warn).unwrap_or_else(|e| panic!("{e}"));
assert_eq!(warn["param_warnings"], json!([want]), "{warn}");
let strict = run(ParamCheck::Strict).err().map(|e| e.to_string()).unwrap_or_default();
assert!(strict.ends_with(want), "{strict}");
}
#[test]
fn replies_match_the_output_schema() {
let schema = output_schema_for::<FeatureResult>();
let schema = schema.as_value();
let check = |r: Value| assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
let warn = || {
let mut s = sheet();
s.param_check = ParamCheck::Warn;
s
};
let ok = |s: &mut Session, id: &str, p: Value| {
let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
assert_eq!(r.get("param_warnings"), None, "{id} {p}: {r}");
r
};
// Each form each command takes, in Warn, without warnings.
let mut s = warn();
for (id, p) in [
("sheet.flange", json!({"edges": [[50, 0, 2.5]], "height": 20})),
("sheet.hem", json!({"edges": [[50, 0, 20]], "length": 8, "gap": 1, "flip": false})),
(
"sheet.flange",
json!({"type": "Edge", "edges": [{"point": [100, 30, 2.5], "angle": "60 deg", "height": null}], "height": 15, "angle": 90,
"radius": 2, "position": "OUTSIDE", "flip": true, "corner_relief_shape": " round ", "corner_relief": 3, "name": "Side"}),
),
("sheet.perforate", json!({"diameter": 2, "pitch": 5, "margin": 3, "pattern": "square"})),
(
"sheet.flange",
json!({"edges": [[0, 30, 2.5]], "height": 12, "position": "material_outside", "height_from": "inner",
"then": [{"height": 8}, {"height": 6, "angle": "45 deg", "flip": true}], "name": "Chain"}),
),
("sheet.unfold", json!({})),
("sheet.refold", json!({"name": "Back"})),
("sheet.flange", json!({"type": "BASE", "sketch": "Base", "profiles": "all", "rule": STEEL, "flip": true, "body_names": ["Second"]})),
("sheet.unfold", json!({"body": "Second"})),
("sheet.refold", json!({"body": "Second"})),
("sheet.convert", json!({"body": "Plate", "face": [50, 130, 2.5], "bends": null, "rule": STEEL, "body_name": "Plated"})),
] {
check(ok(&mut s, id, p));
}
let mut s = warn();
for (id, p) in [
("sheet.fold", json!({"points": [[60, 0, 2.5], [60, 60, 2.5]], "angle": "45 deg", "radius": 1, "position": "Mould", "fixed": [10, 30, 2.5]})),
("sheet.perforate", json!({"diameter": 2, "pitch": 6})),
] {
check(ok(&mut s, id, p));
}
let mut s = warn();
for (id, p) in [
("sketch.create", json!({"plane": "XY", "offset": 2.5, "name": "FoldLine"})),
("sketch.line", json!({"points": [[40, 0], [40, 60]], "ids": ["fl"]})),
("sketch.finish", json!({})),
] {
ok(&mut s, id, p);
}
let body = s.model.state().sheets.first().map(|sh| sh.body.clone()).unwrap_or_default();
check(ok(&mut s, "sheet.fold", json!({"sketch": "FoldLine", "curve": "fl", "position": "start", "flip": true, "body": body})));
let mut s = warn();
for (id, p) in [
("sketch.create", json!({"plane": {"origin": [0, 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, -1]}, "name": "Contour"})),
("sketch.line", json!({"points": [[0, 0], [40, 0], [40, -30], [70, -30]], "ids": ["l1", "l2", "l3"]})),
("sketch.finish", json!({})),
] {
ok(&mut s, id, p);
}
check(ok(
&mut s,
"sheet.flange",
json!({"sketch": "Contour", "curves": ["l1", "l2", "l3"], "distance": 50, "reverse": true, "flip": true, "rule": STEEL}),
));
check(ok(&mut s, "sheet.flange", json!({"type": "contour", "sketch": "Contour", "curves": "l1", "distance": "20 mm", "body_name": "Strip"})));
// A misspelt key: the call runs, and the reply carrying its warning still matches.
let mut s = warn();
let r = s.execute("sheet.unfold", &json!({"bodies": "x"})).unwrap_or_else(|e| panic!("{e}"));
assert!(r.get("param_warnings").is_some(), "{r}");
check(r);
}
-7
View File
@@ -249,19 +249,12 @@ render.status
select.clear
select.set
selection.delete
sheet.convert
sheet.export_bend_table
sheet.export_dxf
sheet.flange
sheet.flat_pattern
sheet.fold
sheet.hem
sheet.manage_rules
sheet.path_flange
sheet.perforate
sheet.refold
sheet.rules
sheet.unfold
sketch.arc.center_point
sketch.arc.tangent
sketch.arc.three_point