Sheet metal rules: typed input contracts and replies (#6581) (#10921)

* claim: sheet rule contracts (#6581)

* feat(engine): add typed sheet-rule contracts (#6581)
This commit is contained in:
PapaEcho
2026-11-02 18:43:19 +00:00
committed by GitHub
parent a54d0517f7
commit ccdb470e01
5 changed files with 362 additions and 24 deletions
+1 -1
View File
@@ -97,7 +97,7 @@ mod script_tests;
mod sheet;
pub(crate) use sheet::{
FlangeType, ThenStep, flange_edge, flange_edge_list, flange_position, flange_type, fold_points, fold_position, perforation_pattern, sheet_points,
then_list,
sheet_rule_name, then_list,
};
mod silhouette;
mod sketch;
+28 -19
View File
@@ -13,7 +13,10 @@ use super::CommandSpec;
use super::features::{add_feature, check_expr, feature_sketch, profiles, sketch_id};
use crate::params::{bad, bool_, expr, expr_problem, req_expr, str_, string_list, vec3};
use crate::schema::features::FeatureResult;
use crate::schema::sheet::{ConvertParams, FlangeParams, FoldParams, HemParams, PerforateParams, UnfoldParams};
use crate::schema::sheet::{
ConvertParams, FlangeParams, FoldParams, HemParams, ListedRule, ManageRulesParams, ManageRulesResult, PerforateParams, RuleFeatureError,
RuleReply, RulesParams, RulesResult, UnfoldParams,
};
use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
@@ -24,6 +27,9 @@ const FOLD_CONTRACT: TypedContract<FoldParams> = TypedContract::new();
const UNFOLD_CONTRACT: TypedContract<UnfoldParams> = TypedContract::new();
const CONVERT_CONTRACT: TypedContract<ConvertParams> = TypedContract::new();
const RULES_CONTRACT: TypedContract<RulesParams> = TypedContract::new();
const MANAGE_RULES_CONTRACT: TypedContract<ManageRulesParams> = TypedContract::new();
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("sheet.flange", "Flange", crate::checked!("sheet.flange", flange))
.at("SHEET METAL", "CREATE")
@@ -101,7 +107,8 @@ pub static COMMANDS: &[CommandSpec] = &[
two flat faces tangent to it, either skin), makes it one bend of the rule's radius at their virtual sharp; \
the faces' holes become cut-outs and their engravings, up to half the thickness deep, pockets)",
),
CommandSpec::new("sheet.manage_rules", "Sheet Metal Rules", rules).at("SHEET METAL", "MODIFY").icon("sheet_rules").params(
CommandSpec::new("sheet.manage_rules", "Sheet Metal Rules", crate::checked!("sheet.manage_rules", rules))
.contract(&MANAGE_RULES_CONTRACT).output(output_schema_for::<ManageRulesResult>).at("SHEET METAL", "MODIFY").icon("sheet_rules").params(
"name (new or existing); thickness?, k_factor?, bend_radius?, relief_width?, relief_depth?, corner_relief?, hem_gap?, gap? (expressions; `Thickness` is the rule's; \
gap: between flanges that meet at a corner, whose ends are closed toward each other at any angle); \
corner_relief_shape?: notch|round|rectangular|tear (what is cut where two bends meet at a corner of the base: round and rectangular a relief \
@@ -110,7 +117,8 @@ pub static COMMANDS: &[CommandSpec] = &[
left between the bend's sides, 180° less it; the bend table gives both, and a flange's `angle` is always the bend angle); \
active?: bool; delete?: bool",
),
CommandSpec::new("sheet.rules", "List Sheet Metal Rules", list_rules).icon("sheet_rules").noundo().doc_only().params("→ rules with their expressions and values, and the active one"),
CommandSpec::new("sheet.rules", "List Sheet Metal Rules", crate::checked!("sheet.rules", list_rules))
.contract(&RULES_CONTRACT).output(output_schema_for::<RulesResult>).icon("sheet_rules").noundo().doc_only().params("→ rules with their expressions and values, and the active one"),
CommandSpec::new("sheet.flat_pattern", "Create Flat Pattern", flat_pattern)
.at("SHEET METAL", "CREATE")
.icon("flat")
@@ -624,9 +632,13 @@ fn convert(s: &mut Session, p: &Value) -> Result<Value> {
)
}
pub(crate) fn sheet_rule_name(v: &Value) -> std::result::Result<&str, &'static str> {
v.as_str().map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or("`name` is required")
}
fn rules(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "sheet.manage_rules";
let name = str_(p, "name").map(str::trim).filter(|n| !n.is_empty() && n.len() <= 128).ok_or_else(|| bad(cmd, "`name` is required"))?.to_string();
let name = sheet_rule_name(p.get("name").unwrap_or(&Value::Null)).map_err(|why| bad(cmd, why))?.to_string();
if bool_(p, "delete").unwrap_or(false) {
let doc = s.doc_mut();
let before = doc.sheet.rules.len();
@@ -637,7 +649,7 @@ fn rules(s: &mut Session, p: &Value) -> Result<Value> {
if doc.sheet.active.as_deref() == Some(name.as_str()) {
doc.sheet.active = None;
}
return Ok(json!({"deleted": name}));
return serde_json::to_value(ManageRulesResult::Deleted { deleted: name, param_warnings: Vec::new() }).map_err(|e| bad(cmd, e.to_string()));
}
let mut rule =
s.doc.sheet.rules.iter().find(|r| r.name == name).cloned().unwrap_or_else(|| SheetRule { name: name.clone(), ..s.doc.sheet_rule(None) });
@@ -670,18 +682,15 @@ fn rules(s: &mut Session, p: &Value) -> Result<Value> {
doc.sheet.active = Some(name.clone());
}
s.refresh();
let errors: Vec<Value> = s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| json!({"feature": r.name, "error": e}))).collect();
Ok(json!({"rule": rule_json(&rule), "values": values, "errors": errors}))
}
/// A rule as the rule commands list it: as saved, and with its `angle_display` also while it is
/// the `bend` a design leaves out.
fn rule_json(r: &SheetRule) -> Value {
let mut v = json!(r);
if let Value::Object(m) = &mut v {
m.insert("angle_display".into(), json!(r.angle_display));
}
v
let errors =
s.model.results.iter().filter_map(|r| r.error.as_ref().map(|e| RuleFeatureError { feature: r.name.clone(), error: e.clone() })).collect();
serde_json::to_value(ManageRulesResult::Changed {
rule: Box::new(RuleReply::from(&rule)),
values: values.into(),
errors,
param_warnings: Vec::new(),
})
.map_err(|e| bad(cmd, e.to_string()))
}
fn list_rules(s: &mut Session, _p: &Value) -> Result<Value> {
@@ -690,9 +699,9 @@ fn list_rules(s: &mut Session, _p: &Value) -> Result<Value> {
if all.is_empty() {
all.push(SheetRule::steel());
}
let rules: Vec<Value> = all.iter().map(|r| json!({"rule": rule_json(r), "values": s.doc.rule_values(&vals, r).ok()})).collect();
let rules = all.iter().map(|r| ListedRule { rule: r.into(), values: s.doc.rule_values(&vals, r).ok().map(Into::into) }).collect();
let active = s.doc.sheet_rule(None).name;
Ok(json!({"rules": rules, "active": active}))
serde_json::to_value(RulesResult { rules, active, param_warnings: Vec::new() }).map_err(|e| bad("sheet.rules", e.to_string()))
}
fn no_sheet_body(cmd: &str) -> EngineError {
+197 -2
View File
@@ -1,5 +1,5 @@
//! Contracts for the sheet metal feature commands in `cmd/sheet.rs`. They all return
//! [`FeatureResult`](super::features::FeatureResult).
//! Contracts for sheet metal feature and rule commands in `cmd/sheet.rs`. Feature commands
//! return [`FeatureResult`](super::features::FeatureResult); rule commands have their own replies.
//!
//! 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
@@ -557,6 +557,201 @@ pub struct ConvertParams {
pub common: FeatureCommon,
}
/// List the design's sheet metal rules (the built-in steel rule if none are saved).
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct RulesParams {}
/// Create or edit a sheet metal rule, activate it, or delete it. Expressions may use design
/// parameters; `Thickness` inside a rule's other expressions is that rule's thickness.
/// The handler evaluates dimensions and ranges against the design after checking the contract.
#[derive(Debug, Deserialize, JsonSchema)]
#[schemars(deny_unknown_fields)]
pub struct ManageRulesParams {
/// The rule's name (trimmed, nonempty, at most 128 bytes). A new rule inherits the active
/// rule's fields; an existing rule keeps fields not given here.
pub name: RuleName,
/// Thickness, more than 0 and less than 10000 mm. Ignored when deleting.
pub thickness: Option<LengthExpr>,
/// Neutral-axis fraction, from 0 to 1. Ignored when deleting.
pub k_factor: Option<super::types::NumberExpr>,
/// Inner bend radius, nonnegative. Ignored when deleting.
pub bend_radius: Option<LengthExpr>,
/// Bend relief width. Ignored when deleting.
pub relief_width: Option<LengthExpr>,
/// Bend relief depth. Ignored when deleting.
pub relief_depth: Option<LengthExpr>,
/// Corner relief size across. Ignored when deleting.
pub corner_relief: Option<LengthExpr>,
/// Corner relief shape. Ignored when deleting.
pub corner_relief_shape: Option<ReliefShapeParam>,
/// Inner radius of flat hems. Ignored when deleting.
pub hem_gap: Option<LengthExpr>,
/// Gap between meeting flanges. Ignored when deleting.
pub gap: Option<LengthExpr>,
/// How DXF bend notes show angles: bend or included, ignoring case and surrounding blanks.
/// Ignored when deleting.
pub angle_display: Option<AngleDisplayParam>,
/// Make this the active rule. Default: true if there is no saved active rule, otherwise false.
/// False leaves the active choice unchanged; ignored when deleting.
pub active: Option<bool>,
/// Delete the named saved rule instead of editing it. Default: false. Deleting the active
/// rule clears that choice; listing then uses the first remaining rule, else built-in steel.
pub delete: Option<bool>,
}
/// A rule name, checked by the handler's reader.
#[derive(Debug)]
pub struct RuleName(pub String);
impl<'de> Deserialize<'de> for RuleName {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let v = Value::deserialize(d)?;
crate::cmd::sheet_rule_name(&v).map(|n| RuleName(n.to_string())).map_err(|why| D::Error::custom(whole(why)))
}
}
impl JsonSchema for RuleName {
fn schema_name() -> Cow<'static, str> {
"SheetRuleName".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"type": "string", "description": "Trimmed, nonempty rule name, at most 128 bytes after trimming."})
}
}
/// A rule's bend-note angle display, checked by the same parser as the handler.
#[derive(Debug)]
pub struct AngleDisplayParam(pub solidcraft_doc::sheet::AngleDisplay);
impl<'de> Deserialize<'de> for AngleDisplayParam {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Value::deserialize(d)?
.as_str()
.and_then(solidcraft_doc::sheet::AngleDisplay::parse)
.map(AngleDisplayParam)
.ok_or_else(|| D::Error::custom("must be bend or included"))
}
}
impl JsonSchema for AngleDisplayParam {
fn schema_name() -> Cow<'static, str> {
"SheetAngleDisplay".into()
}
fn json_schema(_: &mut SchemaGenerator) -> Schema {
json_schema!({"type": "string", "description": "bend or included, ignoring case and surrounding blanks.",
"pattern": format!("^{blank}([Bb][Ee][Nn][Dd]|[Ii][Nn][Cc][Ll][Uu][Dd][Ee][Dd]){blank}$", blank = blanks())})
}
}
/// A saved rule's expressions, including the default bend-angle display which the saved
/// design omits. These are expressions, not evaluated values.
#[derive(Debug, serde::Serialize, JsonSchema)]
pub struct RuleReply {
pub name: String,
pub thickness: String,
pub k_factor: String,
pub bend_radius: String,
pub relief_width: String,
pub relief_depth: String,
pub corner_relief: String,
pub corner_relief_shape: String,
pub hem_gap: String,
pub gap: String,
pub angle_display: String,
}
impl From<&solidcraft_doc::sheet::SheetRule> for RuleReply {
fn from(r: &solidcraft_doc::sheet::SheetRule) -> Self {
Self {
name: r.name.clone(),
thickness: r.thickness.clone(),
k_factor: r.k_factor.clone(),
bend_radius: r.bend_radius.clone(),
relief_width: r.relief_width.clone(),
relief_depth: r.relief_depth.clone(),
corner_relief: r.corner_relief.clone(),
corner_relief_shape: r.corner_relief_shape.clone(),
hem_gap: r.hem_gap.clone(),
gap: r.gap.clone(),
angle_display: r.angle_display.clone(),
}
}
}
/// Evaluated rule values: lengths in millimetres, dimensionless K-factor and canonical choices.
#[derive(Debug, serde::Serialize, JsonSchema)]
pub struct RuleValuesReply {
pub thickness: f64,
pub k_factor: f64,
pub bend_radius: f64,
pub relief_width: f64,
pub relief_depth: f64,
pub corner_relief: f64,
pub corner_relief_shape: String,
pub hem_gap: f64,
pub gap: f64,
pub angle_display: String,
}
impl From<solidcraft_doc::sheet::RuleValues> for RuleValuesReply {
fn from(r: solidcraft_doc::sheet::RuleValues) -> Self {
Self {
thickness: r.thickness,
k_factor: r.k_factor,
bend_radius: r.bend_radius,
relief_width: r.relief_width,
relief_depth: r.relief_depth,
corner_relief: r.corner_relief,
corner_relief_shape: r.corner_relief_shape.name().into(),
hem_gap: r.hem_gap,
gap: r.gap,
angle_display: r.angle_display.name().into(),
}
}
}
/// A rule and its evaluated values, or null values if its expressions no longer evaluate.
#[derive(Debug, serde::Serialize, JsonSchema)]
pub struct ListedRule {
pub rule: RuleReply,
pub values: Option<RuleValuesReply>,
}
/// The rule list and effective active name.
#[derive(Debug, serde::Serialize, JsonSchema)]
pub struct RulesResult {
pub rules: Vec<ListedRule>,
pub active: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub param_warnings: Vec<String>,
}
/// A feature that failed to rebuild after a rule was edited.
#[derive(Debug, serde::Serialize, JsonSchema)]
pub struct RuleFeatureError {
pub feature: String,
pub error: String,
}
/// A successful rule edit or deletion, preserving the existing reply alternatives.
#[derive(Debug, serde::Serialize, JsonSchema)]
#[serde(untagged)]
pub enum ManageRulesResult {
Changed {
rule: Box<RuleReply>,
values: RuleValuesReply,
errors: Vec<RuleFeatureError>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
param_warnings: Vec<String>,
},
Deleted {
deleted: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
param_warnings: Vec<String>,
},
}
#[cfg(test)]
#[path = "sheet_tests.rs"]
mod tests;
+136
View File
@@ -355,3 +355,139 @@ fn replies_match_the_output_schema() {
assert!(r.get("param_warnings").is_some(), "{r}");
check(r);
}
#[test]
fn rule_commands_publish_contracts_and_refuse_unknown_keys() {
for id in ["sheet.rules", "sheet.manage_rules"] {
let spec = crate::command_specs().into_iter().find(|c| c.id == id).unwrap();
assert!(spec.contract.is_some() && spec.output.is_some(), "{id}: input schema missing");
let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() };
let p = if id == "sheet.rules" { json!({"unknown_key": true}) } else { json!({"name": "Test", "thikness": 1}) };
assert!(s.execute(id, &p).is_err(), "{id}: unknown key accepted");
assert!(s.doc.sheet.rules.is_empty());
}
}
#[test]
fn rule_contract_keys_and_readers_match() {
use super::{AngleDisplayParam, ManageRulesParams, RuleName, RulesParams};
assert_keys(input_schema_for::<RulesParams>(), &[]);
assert_keys(
input_schema_for::<ManageRulesParams>(),
&[
"active",
"angle_display",
"bend_radius",
"corner_relief",
"corner_relief_shape",
"delete",
"gap",
"hem_gap",
"k_factor",
"name",
"relief_depth",
"relief_width",
"thickness",
],
);
for (text, valid) in [("bend", true), (" INCLUDED ", true), ("\u{2003}BeNd\u{2003}", true), ("outside", false)] {
assert_eq!(parse::<AngleDisplayParam>(json!(text)).is_some(), valid);
}
assert!(parse::<AngleDisplayParam>(json!(false)).is_none());
for v in [json!(null), json!(false), json!(1), json!(""), json!(" \n "), json!("a".repeat(129)), json!("é".repeat(65))] {
assert!(parse::<RuleName>(v).is_none());
}
assert_eq!(parse::<RuleName>(json!(" My rule ")).unwrap().0, "My rule");
assert!(parse::<RuleName>(json!("é".repeat(64))).is_some());
let pattern = input_schema_for::<AngleDisplayParam>();
assert!(pattern.as_value()["pattern"].as_str().unwrap().contains(&super::blanks()));
assert_strict_keeps_todays_errors(&[
("sheet.manage_rules", json!({"name": null})),
("sheet.manage_rules", json!({"name": true})),
("sheet.manage_rules", json!({"name": " "})),
("sheet.manage_rules", json!({"name": "a".repeat(129)})),
("sheet.manage_rules", json!({"name": "R", "angle_display": "outer"})),
("sheet.manage_rules", json!({"name": "R", "angle_display": 5})),
("sheet.manage_rules", json!({"name": "R", "corner_relief_shape": "oval"})),
("sheet.manage_rules", json!({"name": "R", "thickness": -1})),
("sheet.manage_rules", json!({"name": "R", "k_factor": 2})),
("sheet.manage_rules", json!({"name": "Missing", "delete": true})),
]);
}
/// Run all rule forms in Warn, compare with Off, and pin the successful reply shapes.
#[test]
fn rule_replies_match_the_output_schemas_without_warnings() {
use super::{ManageRulesResult, RulesResult};
let mut off = Session::default();
let mut warn = Session { param_check: ParamCheck::Warn, ..Session::default() };
let calls = [
("sheet.rules", json!({})),
(
"sheet.manage_rules",
json!({"name": " Metric ", "thickness": 2, "k_factor": "0.4", "bend_radius": "Thickness / 2",
"relief_width": 1, "relief_depth": "Thickness", "corner_relief": 3, "corner_relief_shape": " Round ",
"hem_gap": 0.1, "gap": "Thickness / 2", "angle_display": " INCLUDED ", "active": true}),
),
(
"sheet.manage_rules",
json!({"name": "Metric", "thickness": "3 mm", "k_factor": 0.5, "bend_radius": 1,
"relief_width": "1 mm", "relief_depth": 2, "corner_relief": "3 mm", "corner_relief_shape": "tear",
"hem_gap": "0.2 mm", "gap": 2, "angle_display": "BeNd", "active": false, "delete": false}),
),
("sheet.manage_rules", json!({"name": "Other"})),
(
"sheet.manage_rules",
json!({"name": "Other", "thickness": null, "k_factor": null, "bend_radius": null,
"relief_width": null, "relief_depth": null, "corner_relief": null, "corner_relief_shape": null,
"hem_gap": null, "gap": null, "angle_display": null, "active": null, "delete": null}),
),
("sheet.rules", json!({})),
("sheet.manage_rules", json!({"name": "Other", "active": true})),
("sheet.manage_rules", json!({"name": "Metric", "delete": true})),
("sheet.manage_rules", json!({"name": "Other", "delete": true})),
("sheet.rules", json!({})),
];
for (id, p) in calls {
let a = off.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
let b = warn.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
assert_eq!(a, b, "{id} {p}");
assert!(b.get("param_warnings").is_none(), "{id} {p}: {b}");
let schema = if id == "sheet.rules" { output_schema_for::<RulesResult>() } else { output_schema_for::<ManageRulesResult>() };
assert!(conforms(schema.as_value(), schema.as_value(), &b), "{id}: {b}");
if let Some(rule) = b.get("rule") {
let saved = off.doc.sheet.rules.iter().find(|r| json!(r.name) == rule["name"]).unwrap();
let mut old = json!(saved);
old["angle_display"] = json!(saved.angle_display);
assert_eq!(*rule, old);
let (vals, _) = off.doc.param_values();
assert_eq!(b["values"], json!(off.doc.rule_values(&vals, saved).unwrap()));
assert_eq!(b["errors"], json!([]));
}
}
// Saved rules whose expressions no longer evaluate are still listed, with null values.
warn.doc_mut().sheet.rules.push(solidcraft_doc::sheet::SheetRule {
name: "Invalid".into(),
thickness: "Missing".into(),
..solidcraft_doc::sheet::SheetRule::steel()
});
let reply = warn.execute("sheet.rules", &json!({})).unwrap();
assert_eq!(reply["rules"][0]["values"], Value::Null);
let schema = output_schema_for::<RulesResult>();
assert!(conforms(schema.as_value(), schema.as_value(), &reply));
}
#[test]
fn rule_warnings_match_the_output_schema_and_strict_does_not_mutate() {
use super::{ManageRulesResult, RulesResult};
for (id, p) in [("sheet.rules", json!({"naem": "R"})), ("sheet.manage_rules", json!({"name": "R", "thikness": 1}))] {
let mut s = Session { param_check: ParamCheck::Strict, ..Session::default() };
assert!(s.execute(id, &p).is_err());
assert!(s.doc.sheet.rules.is_empty());
s.param_check = ParamCheck::Warn;
let reply = s.execute(id, &p).unwrap();
assert!(!reply["param_warnings"].as_array().unwrap().is_empty());
let schema = if id == "sheet.rules" { output_schema_for::<RulesResult>() } else { output_schema_for::<ManageRulesResult>() };
assert!(conforms(schema.as_value(), schema.as_value(), &reply));
}
}
-2
View File
@@ -210,9 +210,7 @@ selection.delete
sheet.export_bend_table
sheet.export_dxf
sheet.flat_pattern
sheet.manage_rules
sheet.path_flange
sheet.rules
sketch.arc.center_point
sketch.arc.tangent
sketch.arc.three_point