Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Agents and scripts: Manage, Assign and List Plastic Rules describe their exact parameters and reply (#12313) (#12314)

austin62jake4eb0c6f5ec1d
diff --git a/crates/engine/src/cmd/plastic.rs b/crates/engine/src/cmd/plastic.rs
index 58085095e6..41571943e6 100644
--- a/crates/engine/src/cmd/plastic.rs
+++ b/crates/engine/src/cmd/plastic.rs
@@ -1,6 +1,6 @@
//! Plastic (enclosure) features: Boss, Lip / Groove, Snap Fit and Rest, and plastic rules.
-use serde_json::{Value, json};
+use serde_json::Value;
use solidcore_record::Vec3;
use solidcraft_doc::BodyName;
use solidcraft_doc::FeatureKind;
@@ -12,8 +12,16 @@ use solidcraft_geom::prelude::*;
use super::CommandSpec;
use super::features::{add_feature, check_expr};
use crate::params::{bad, bool_, expr, req_expr, str_, string_list, vec3};
+use crate::schema::plastic::{
+ AssignRuleParams, AssignRuleResult, ManageRulesParams, ManageRulesResult, RuleExpressions, RuleInfo, RuleValuesOrError, RulesParams, RulesResult,
+};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{EngineError, Result, Session};
+const MANAGE_RULES_CONTRACT: TypedContract<ManageRulesParams> = TypedContract::new();
+const ASSIGN_RULE_CONTRACT: TypedContract<AssignRuleParams> = TypedContract::new();
+const RULES_CONTRACT: TypedContract<RulesParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
CommandSpec::new("plastic.boss", "Boss", boss).at("PLASTIC", "CREATE").icon("boss").params(
"position: [x,y,z] on a face; direction? (default: out of the face); diameter, height; hole_diameter?, hole_depth? (default: to the face); \
@@ -30,30 +38,48 @@ pub static COMMANDS: &[CommandSpec] = &[
"position: [x,y,z] on a face (the rest's centre); direction? (default: out of the face); width (round: the diameter); length? (a rectangle, along `along`); along?: [x,y,z]; \
height; draft? (angle; default: the body's plastic rule); thickness? (wall of a hollow rest); body?",
),
- CommandSpec::new("plastic.manage_rules", "Manage Plastic Rules", manage_rules).at("PLASTIC", "SETUP").icon("plastic_rule").params(
+ CommandSpec::new("plastic.manage_rules", "Manage Plastic Rules", crate::checked!("plastic.manage_rules", manage_rules))
+ .at("PLASTIC", "SETUP")
+ .icon("plastic_rule")
+ .contract(&MANAGE_RULES_CONTRACT)
+ .output(output_schema_for::<ManageRulesResult>)
+ .params(
"name (library or new rule; a new one starts from `from`, default ABS (1.5mm)); from?; material?; thickness?, nominal_radius?, clearance?, knife_edge?, \
reveal_height?, thickness_variation?, draft?, max_thickness?, min_thickness?, min_draft? (expressions; `Thickness` is the rule's); active?: bool (rule for bodies without one); \
delete?: bool (a design rule; a library rule goes back to the library values)",
),
- CommandSpec::new("plastic.assign_rule", "Assign Plastic Rule", assign_rule).at("PLASTIC", "SETUP").icon("plastic_assign").params(
+ CommandSpec::new("plastic.assign_rule", "Assign Plastic Rule", crate::checked!("plastic.assign_rule", assign_rule))
+ .at("PLASTIC", "SETUP")
+ .icon("plastic_assign")
+ .contract(&ASSIGN_RULE_CONTRACT)
+ .output(output_schema_for::<AssignRuleResult>)
+ .params(
"bodies: [names]; rule: name (empty: no rule) — plastic features on these bodies take its draft and clearance as defaults",
),
- CommandSpec::new("plastic.rules", "List Plastic Rules", list_rules).icon("plastic_rule").noundo().params("→ rules with their expressions and values, the active rule and the rules assigned to bodies"),
+ CommandSpec::new("plastic.rules", "List Plastic Rules", crate::checked!("plastic.rules", list_rules))
+ .icon("plastic_rule")
+ .noundo()
+ .contract(&RULES_CONTRACT)
+ .output(output_schema_for::<RulesResult>)
+ .params("→ rules with their expressions and values, the active rule and the rules assigned to bodies"),
];
-fn rule_json(s: &Session, r: &PlasticRule) -> Value {
+/// A rule as the rule commands give it back: its expressions, and its values evaluated against
+/// the design's parameters (or why they don't evaluate).
+fn rule_info(s: &Session, r: &PlasticRule) -> RuleInfo {
let (vals, _) = s.doc.param_values();
- let values = s.doc.plastic_values(&vals, r).map(|v| {
- json!({"thickness": v.thickness, "nominal_radius": v.nominal_radius, "clearance": v.clearance, "knife_edge": v.knife_edge,
- "reveal_height": v.reveal_height, "thickness_variation": v.thickness_variation, "draft_deg": v.draft.to_degrees(),
- "max_thickness": v.max_thickness, "min_thickness": v.min_thickness, "min_draft_deg": v.min_draft.to_degrees()})
- });
+ let values = match s.doc.plastic_values(&vals, r) {
+ Ok(v) => RuleValuesOrError::Values(v.into()),
+ Err(e) => RuleValuesOrError::Error { error: e.to_string() },
+ };
let library = PlasticRule::library().iter().any(|l| l.name == r.name);
- json!({
- "name": r.name, "material": r.material, "library": library,
- "expressions": r.fields().iter().map(|(k, e, _)| (k.to_string(), json!(e))).collect::<serde_json::Map<_, _>>(),
- "values": values.unwrap_or_else(|e| json!({"error": e.to_string()})),
- })
+ RuleInfo { name: r.name.clone(), material: r.material.clone(), library, expressions: RuleExpressions::from(r), values }
+}
+
+/// A reply built from its output schema's type (`schema::plastic`), so the two can't drift
+/// apart.
+fn typed_reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}
fn manage_rules(s: &mut Session, p: &Value) -> Result<Value> {
@@ -72,7 +98,7 @@ fn manage_rules(s: &mut Session, p: &Value) -> Result<Value> {
}
doc.plastic.assigned.retain(|_, r| *r != name);
}
- return Ok(json!({"deleted": name}));
+ return typed_reply(cmd, ManageRulesResult::Deleted { deleted: name, param_warnings: Vec::new() });
}
let mut rule = match s.doc.plastic_rule(&name) {
Some(r) => r,
@@ -116,7 +142,8 @@ fn manage_rules(s: &mut Session, p: &Value) -> Result<Value> {
_ => {}
}
s.refresh();
- Ok(json!({"rule": rule_json(s, &rule), "active": s.doc.plastic.active}))
+ let reply = ManageRulesResult::Changed { rule: Box::new(rule_info(s, &rule)), active: s.doc.plastic.active.clone(), param_warnings: Vec::new() };
+ typed_reply(cmd, reply)
}
fn assign_rule(s: &mut Session, p: &Value) -> Result<Value> {
@@ -142,12 +169,13 @@ fn assign_rule(s: &mut Session, p: &Value) -> Result<Value> {
}
}
s.refresh();
- Ok(json!({"bodies": bodies, "rule": if rule.is_empty() { Value::Null } else { json!(rule) }}))
+ typed_reply(cmd, AssignRuleResult { bodies, rule: (!rule.is_empty()).then_some(rule), param_warnings: Vec::new() })
}
fn list_rules(s: &mut Session, _p: &Value) -> Result<Value> {
- let rules: Vec<Value> = s.doc.plastic_rules().iter().map(|r| rule_json(s, r)).collect();
- Ok(json!({"rules": rules, "active": s.doc.plastic.active, "assigned": s.doc.plastic.assigned}))
+ let rules = s.doc.plastic_rules().iter().map(|r| rule_info(s, r)).collect();
+ let reply = RulesResult { rules, active: s.doc.plastic.active.clone(), assigned: s.doc.plastic.assigned.clone(), param_warnings: Vec::new() };
+ typed_reply("plastic.rules", reply)
}
fn rest(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 4d1cfa1566..4624f9fcb1 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -79,6 +79,7 @@ pub mod panels;
pub mod parameter_sweep;
pub mod parameters;
pub mod parts;
+pub mod plastic;
pub mod print_face;
pub mod render;
pub mod render_hdr;
diff --git a/crates/engine/src/schema/plastic.rs b/crates/engine/src/schema/plastic.rs
new file mode 100644
index 0000000000..24d16a2f47
--- /dev/null
+++ b/crates/engine/src/schema/plastic.rs
@@ -0,0 +1,268 @@
+//! Contracts and reply types for the plastic rule commands in `cmd/plastic.rs` (#12313): Manage,
+//! Assign and List Plastic Rules. A plastic rule holds a plastic part's design values, which
+//! Boss, Lip, Snap Fit and Rest take as defaults.
+//!
+//! 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 rule or a body exists, and whether
+//! an expression evaluates, stay the handlers' to check. Where a handler ignores a key of the
+//! wrong type (a `delete` that isn't true or false, a rule value that is neither a number nor
+//! text), the contract refuses it.
+
+use std::collections::BTreeMap;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::Value;
+use solidcraft_doc::plastic::{PlasticRule, PlasticValues};
+
+use super::check::whole;
+use super::config::NameList;
+use super::types::{AngleExpr, LengthExpr, not_blank_pattern};
+
+/// The longest rule name, in bytes once trimmed, as `plastic.manage_rules` reads it.
+const MAX_RULE_NAME_BYTES: usize = 128;
+
+/// `serde(default)` makes schemars publish `"default": null` on a key; drop it from a key the
+/// schema requires.
+fn drop_default(schema: &mut Schema) {
+ schema.remove("default");
+}
+
+/// Adds `key` to the schema's `required` list: for a key the type has optional so that the
+/// handler, not the check, refuses it with its own message when it's left out.
+/// (`#[schemars(required)]` doesn't do this for a key with `serde(default)`.)
+fn require(schema: &mut Schema, key: &str) {
+ match schema.get_mut("required") {
+ Some(Value::Array(required)) => {
+ if !required.iter().any(|k| k == key) {
+ required.push(key.into());
+ }
+ }
+ _ => {
+ schema.insert("required".into(), Value::Array(vec![key.into()]));
+ }
+ }
+}
+
+fn name_required(schema: &mut Schema) {
+ require(schema, "name");
+}
+
+fn bodies_required(schema: &mut Schema) {
+ require(schema, "bodies");
+}
+
+/// Make or edit a plastic rule, make it the active rule (the one for bodies without a rule of
+/// their own), or delete it. A new rule starts from `from`; an existing one keeps the values not
+/// given. Each value is a number or an expression, and may use the design's parameters; in a
+/// rule's other values, `Thickness` is that rule's thickness.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = name_required)]
+pub struct ManageRulesParams {
+ /// The rule, by name: a library rule (to edit it in this design) or a new one. Trimmed,
+ /// 1 to 128 bytes.
+ // Optional in the type, required in the schema: left out, the handler refuses the call
+ // with its own message.
+ #[serde(default, deserialize_with = "rule_name")]
+ #[schemars(schema_with = "rule_name_schema", transform = drop_default)]
+ pub name: Option<String>,
+ /// For a new rule: the rule it starts from. Default: "ABS (1.5mm)".
+ pub from: Option<String>,
+ /// The material the rule is for, as a note (at most 128 characters are kept).
+ pub material: Option<String>,
+ /// The nominal wall thickness.
+ pub thickness: Option<LengthExpr>,
+ /// The nominal radius of rounds.
+ pub nominal_radius: Option<LengthExpr>,
+ /// The clearance between mating parts: a groove's gap when it gives none.
+ pub clearance: Option<LengthExpr>,
+ pub knife_edge: Option<LengthExpr>,
+ pub reveal_height: Option<LengthExpr>,
+ /// How much a wall's thickness may vary.
+ pub thickness_variation: Option<LengthExpr>,
+ /// The draft of plastic features when they give none.
+ pub draft: Option<AngleExpr>,
+ /// The thickest wall allowed.
+ pub max_thickness: Option<LengthExpr>,
+ /// The thinnest wall allowed.
+ pub min_thickness: Option<LengthExpr>,
+ /// The least draft allowed.
+ pub min_draft: Option<AngleExpr>,
+ /// True makes this the active rule; false stops it being the active rule.
+ pub active: Option<bool>,
+ /// True deletes the rule from the design (a library rule goes back to the library's
+ /// values). Default: false.
+ pub delete: Option<bool>,
+}
+
+/// A rule's name as `plastic.manage_rules` reads it: text that isn't blank, at most 128 bytes
+/// once trimmed, and the handler's message for anything else.
+fn rule_name<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
+ match Value::deserialize(d)? {
+ Value::String(name) if !name.trim().is_empty() && name.trim().len() <= MAX_RULE_NAME_BYTES => Ok(Some(name.trim().to_string())),
+ _ => Err(D::Error::custom(whole("`name` is required"))),
+ }
+}
+
+/// The pattern says "not blank"; at most 128 bytes once trimmed, which JSON Schema can't count,
+/// is in the field's description and checked by [`rule_name`].
+fn rule_name_schema(_: &mut SchemaGenerator) -> Schema {
+ json_schema!({"type": "string", "minLength": 1, "pattern": not_blank_pattern()})
+}
+
+/// Assign a plastic rule to bodies, or take theirs away. Plastic features on those bodies take
+/// the rule's draft and clearance as defaults.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields, transform = bodies_required)]
+pub struct AssignRuleParams {
+ /// The bodies, by name: 1 to 10 000.
+ // Optional in the type, required in the schema: left out or empty, the handler refuses the
+ // call with its own message.
+ #[serde(default)]
+ pub bodies: Option<NameList>,
+ /// The rule, by name, as `plastic.rules` lists it. Empty or left out: the bodies have no
+ /// rule of their own, so the active rule applies.
+ pub rule: Option<String>,
+}
+
+/// List the plastic rules (the library's and the design's), the active rule and the rules
+/// assigned to bodies. No parameters.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct RulesParams {}
+
+/// A rule's values as written: numbers or expressions, as text.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct RuleExpressions {
+ pub thickness: String,
+ pub nominal_radius: String,
+ pub clearance: String,
+ pub knife_edge: String,
+ pub reveal_height: String,
+ pub thickness_variation: String,
+ pub draft: String,
+ pub max_thickness: String,
+ pub min_thickness: String,
+ pub min_draft: String,
+}
+
+impl From<&PlasticRule> for RuleExpressions {
+ fn from(r: &PlasticRule) -> Self {
+ Self {
+ thickness: r.thickness.clone(),
+ nominal_radius: r.nominal_radius.clone(),
+ clearance: r.clearance.clone(),
+ knife_edge: r.knife_edge.clone(),
+ reveal_height: r.reveal_height.clone(),
+ thickness_variation: r.thickness_variation.clone(),
+ draft: r.draft.clone(),
+ max_thickness: r.max_thickness.clone(),
+ min_thickness: r.min_thickness.clone(),
+ min_draft: r.min_draft.clone(),
+ }
+ }
+}
+
+/// A rule's values, evaluated: lengths in mm, angles in degrees.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct RuleValues {
+ pub thickness: f64,
+ pub nominal_radius: f64,
+ pub clearance: f64,
+ pub knife_edge: f64,
+ pub reveal_height: f64,
+ pub thickness_variation: f64,
+ pub draft_deg: f64,
+ pub max_thickness: f64,
+ pub min_thickness: f64,
+ pub min_draft_deg: f64,
+}
+
+impl From<PlasticValues> for RuleValues {
+ fn from(v: PlasticValues) -> Self {
+ Self {
+ thickness: v.thickness,
+ nominal_radius: v.nominal_radius,
+ clearance: v.clearance,
+ knife_edge: v.knife_edge,
+ reveal_height: v.reveal_height,
+ thickness_variation: v.thickness_variation,
+ draft_deg: v.draft.to_degrees(),
+ max_thickness: v.max_thickness,
+ min_thickness: v.min_thickness,
+ min_draft_deg: v.min_draft.to_degrees(),
+ }
+ }
+}
+
+/// A rule's evaluated values, or why they don't evaluate (an expression naming a parameter the
+/// design no longer has, say).
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum RuleValuesOrError {
+ Values(RuleValues),
+ Error { error: String },
+}
+
+/// A plastic rule, as the rule commands give it back.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct RuleInfo {
+ pub name: String,
+ /// The material the rule is for, as a note; may be empty.
+ pub material: String,
+ /// Whether the rule is one of the library's (edited in this design, or not).
+ pub library: bool,
+ pub expressions: RuleExpressions,
+ pub values: RuleValuesOrError,
+}
+
+/// What `plastic.manage_rules` returns: the rule made or edited, with the active rule, or the
+/// rule deleted.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(untagged)]
+pub enum ManageRulesResult {
+ Changed {
+ rule: Box<RuleInfo>,
+ /// The active rule, if any.
+ active: Option<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ param_warnings: Vec<String>,
+ },
+ Deleted {
+ deleted: String,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ param_warnings: Vec<String>,
+ },
+}
+
+/// What `plastic.assign_rule` returns: the bodies and the rule they now have, or `null` for
+/// none.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct AssignRuleResult {
+ pub bodies: Vec<String>,
+ pub rule: Option<String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+/// What `plastic.rules` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct RulesResult {
+ /// The library's rules, as this design has edited them, then the design's own.
+ pub rules: Vec<RuleInfo>,
+ /// The active rule, if any.
+ pub active: Option<String>,
+ /// Each body with a rule of its own: body name to rule name.
+ pub assigned: BTreeMap<String, String>,
+ /// In the warn parameter-check mode: what the call's parameters got wrong.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub param_warnings: Vec<String>,
+}
+
+#[cfg(test)]
+#[path = "plastic_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/plastic_tests.rs b/crates/engine/src/schema/plastic_tests.rs
new file mode 100644
index 0000000000..9ba62e2227
--- /dev/null
+++ b/crates/engine/src/schema/plastic_tests.rs
@@ -0,0 +1,173 @@
+use serde_json::{Value, json};
+
+use super::{AssignRuleParams, AssignRuleResult, ManageRulesParams, ManageRulesResult, RulesParams, RulesResult};
+use crate::Session;
+use crate::schema::tests::{assert_keys, assert_strict_keeps_todays_errors, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+/// A design with one box, `Body1`.
+fn boxed(level: ParamCheck) -> Session {
+ let mut s = Session { param_check: level, ..Session::default() };
+ s.execute("solid.box", &json!({"length": 20, "width": 15, "height": 10})).unwrap_or_else(|e| panic!("{e}"));
+ s
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(
+ input_schema_for::<ManageRulesParams>(),
+ &[
+ "active",
+ "clearance",
+ "delete",
+ "draft",
+ "from",
+ "knife_edge",
+ "material",
+ "max_thickness",
+ "min_draft",
+ "min_thickness",
+ "name",
+ "nominal_radius",
+ "reveal_height",
+ "thickness",
+ "thickness_variation",
+ ],
+ );
+ assert_keys(input_schema_for::<AssignRuleParams>(), &["bodies", "rule"]);
+ assert_keys(input_schema_for::<RulesParams>(), &[]);
+}
+
+/// #12313: calls that fail today get the same message in strict. (List Plastic Rules takes any
+/// parameters today; strict refuses an unknown key in the check's own words, as for every
+/// converted command.)
+#[test]
+fn strict_keeps_todays_errors() {
+ let many: Vec<String> = (0..10_001).map(|i| format!("B{i}")).collect();
+ assert_strict_keeps_todays_errors(&[
+ ("plastic.manage_rules", json!({})),
+ ("plastic.manage_rules", json!({"name": null})),
+ ("plastic.manage_rules", json!({"name": 5})),
+ ("plastic.manage_rules", json!({"name": " "})),
+ ("plastic.manage_rules", json!({"name": "x".repeat(129)})),
+ ("plastic.manage_rules", json!({"name": "New", "from": "Nope"})),
+ ("plastic.manage_rules", json!({"name": "Nope", "delete": true})),
+ ("plastic.manage_rules", json!({"name": "ABS (1.5mm)", "thickness": "nope + 1"})),
+ ("plastic.manage_rules", json!({"name": "ABS (1.5mm)", "thickness": "0 mm"})),
+ ("plastic.manage_rules", json!({"name": "ABS (1.5mm)", "draft": "2 mm"})),
+ ("plastic.assign_rule", json!({})),
+ ("plastic.assign_rule", json!({"bodies": null})),
+ ("plastic.assign_rule", json!({"bodies": []})),
+ ("plastic.assign_rule", json!({"bodies": 5})),
+ ("plastic.assign_rule", json!({"bodies": ["Body1", 5]})),
+ ("plastic.assign_rule", json!({"bodies": many})),
+ ("plastic.assign_rule", json!({"bodies": ["Nope"]})),
+ ]);
+ // A rule that doesn't exist, for a body that does.
+ let p = json!({"bodies": ["Body1"], "rule": "Nope"});
+ let error = |level: ParamCheck| boxed(level).execute("plastic.assign_rule", &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}");
+}
+
+/// #12313: keys of the wrong type that the handlers ignore today (the call then works, without
+/// them) are refused by the contracts: in Warn the call still works, with a warning.
+#[test]
+fn the_contracts_refuse_what_the_handlers_ignore() {
+ for (id, p, key) in [
+ ("plastic.manage_rules", json!({"name": "Mine", "active": "yes"}), "active"),
+ ("plastic.manage_rules", json!({"name": "Mine", "delete": 1}), "delete"),
+ ("plastic.manage_rules", json!({"name": "Mine", "thickness": true}), "thickness"),
+ ("plastic.manage_rules", json!({"name": "Mine", "from": 5}), "from"),
+ ("plastic.manage_rules", json!({"name": "Mine", "material": ["ABS"]}), "material"),
+ ("plastic.assign_rule", json!({"bodies": ["Body1"], "rule": 5}), "rule"),
+ ] {
+ assert!(boxed(ParamCheck::Off).execute(id, &p).is_ok(), "{p} works today");
+ let warned = boxed(ParamCheck::Warn).execute(id, &p).unwrap_or_else(|e| panic!("{p}: {e}"));
+ assert!(warned["param_warnings"].to_string().contains(key), "{warned}");
+ let error = boxed(ParamCheck::Strict).execute(id, &p).err().map(|e| e.to_string()).unwrap_or_default();
+ assert!(error.contains(&format!("`{key}`")), "{p}: {error}");
+ }
+}
+
+/// #12313: the schemas take what the handlers read: a rule's name as text, its values as
+/// numbers or expressions, `active` and `delete` as true or false; bodies as a name or a list of
+/// names, and the rule as text or `null`.
+#[test]
+fn the_schemas_take_what_the_handlers_read() {
+ let manage = input_schema_for::<ManageRulesParams>();
+ let manage = manage.as_value();
+ for (p, takes) in [
+ (json!({"name": "ABS (1.5mm)"}), true),
+ (json!({"name": "Mine", "from": "ABS (1.5mm)", "material": "ABS", "thickness": "2 mm", "draft": 3, "active": true}), true),
+ (json!({"name": "Mine", "delete": true}), true),
+ (json!({}), false),
+ (json!({"name": 5}), false),
+ (json!({"name": ""}), false),
+ (json!({"name": "Mine", "thickness": true}), false),
+ (json!({"name": "Mine", "delete": "yes"}), false),
+ (json!({"name": "Mine", "angle": 3}), false),
+ ] {
+ assert_eq!(conforms(manage, manage, &p), takes, "{p}");
+ }
+ let assign = input_schema_for::<AssignRuleParams>();
+ let assign = assign.as_value();
+ for (p, takes) in [
+ (json!({"bodies": ["Body1"], "rule": "ABS (1.5mm)"}), true),
+ (json!({"bodies": "Body1"}), true),
+ (json!({"bodies": ["Body1"], "rule": null}), true),
+ (json!({}), false),
+ (json!({"bodies": [5]}), false),
+ (json!({"bodies": ["Body1"], "rule": 5}), false),
+ ] {
+ assert_eq!(conforms(assign, assign, &p), takes, "{p}");
+ }
+}
+
+/// #12313: making, editing, listing, assigning and deleting plastic rules reply as the output
+/// schemas say, in Warn without warnings: a new active rule from a library one, its thickness
+/// from a design parameter, the list (with that rule's values not evaluating once the parameter
+/// is out of range), the rule assigned to the box and taken away again, and the rule deleted.
+#[test]
+fn plastic_rules_reply_with_their_schemas() {
+ let mut s = boxed(ParamCheck::Warn);
+ let run = |s: &mut Session, id: &str, p: Value, schema: schemars::Schema| {
+ let r = s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"));
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, &r), "{r} doesn't match {schema}");
+ assert!(r.get("param_warnings").is_none(), "{r}");
+ r
+ };
+ let r = run(
+ &mut s,
+ "plastic.manage_rules",
+ json!({"name": "Mine", "from": "ABS (1.5mm)", "material": "ABS", "active": true}),
+ output_schema_for::<ManageRulesResult>(),
+ );
+ assert_eq!((&r["rule"]["name"], &r["active"]), (&json!("Mine"), &json!("Mine")), "{r}");
+ s.execute("parameters.add", &json!({"name": "wall", "expression": "2 mm"})).unwrap_or_else(|e| panic!("{e}"));
+ let r = run(
+ &mut s,
+ "plastic.manage_rules",
+ json!({"name": "Mine", "thickness": "wall", "draft": "1.5 deg"}),
+ output_schema_for::<ManageRulesResult>(),
+ );
+ assert_eq!(r["rule"]["values"]["thickness"], 2.0, "{r}");
+ assert_eq!(r["rule"]["expressions"]["thickness"], "wall", "{r}");
+ let r = run(&mut s, "plastic.rules", json!({}), output_schema_for::<RulesResult>());
+ assert!(r["rules"].as_array().is_some_and(|rules| rules.iter().any(|x| x["name"] == "Mine" && x["library"] == false)), "{r}");
+ // A thickness of 0 doesn't evaluate as a rule's: the list says why, in place of the values.
+ s.execute("parameters.change", &json!({"name": "wall", "expression": "0 mm"})).unwrap_or_else(|e| panic!("{e}"));
+ let r = run(&mut s, "plastic.rules", json!({}), output_schema_for::<RulesResult>());
+ let mine = r["rules"].as_array().and_then(|rules| rules.iter().find(|x| x["name"] == "Mine")).cloned().unwrap_or_default();
+ assert!(mine["values"]["error"].is_string(), "{mine}");
+ let r = run(&mut s, "plastic.assign_rule", json!({"bodies": ["Body1"], "rule": "ABS (1.5mm)"}), output_schema_for::<AssignRuleResult>());
+ assert_eq!((&r["bodies"], &r["rule"]), (&json!(["Body1"]), &json!("ABS (1.5mm)")), "{r}");
+ let r = run(&mut s, "plastic.rules", json!({}), output_schema_for::<RulesResult>());
+ assert_eq!(r["assigned"], json!({"Body1": "ABS (1.5mm)"}), "{r}");
+ let r = run(&mut s, "plastic.assign_rule", json!({"bodies": "Body1", "rule": ""}), output_schema_for::<AssignRuleResult>());
+ assert_eq!(r["rule"], json!(null), "{r}");
+ let r = run(&mut s, "plastic.manage_rules", json!({"name": "Mine", "delete": true}), output_schema_for::<ManageRulesResult>());
+ assert_eq!(r["deleted"], "Mine", "{r}");
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index e7adf1804f..2756b7866e 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -90,12 +90,9 @@ parameters.graph
parameters.import
parameters.list
parameters.users
-plastic.assign_rule
plastic.boss
plastic.lip
-plastic.manage_rules
plastic.rest
-plastic.rules
plastic.snap_fit
render.aging.describe
render.backends