Skip to content

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

Agents and scripts: sketch Copy, Cut and Paste describe their exact parameters and reply (#10963) (#10964)

austin62jake6500c42c9f7a
diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs
index 8497a0d68d..1752c2d4dc 100644
--- a/crates/engine/src/cmd/sketch_clipboard.rs
+++ b/crates/engine/src/cmd/sketch_clipboard.rs
@@ -16,17 +16,32 @@ use super::sketch::edit;
use super::sketch_store;
use super::{CommandSpec, in_sketch};
use crate::params::{bad, string_list, vec2};
+use crate::schema::sketch_clipboard::{Copied, CopyParams, CutParams, PasteParams, Pasted};
+use crate::schema::{TypedContract, output_schema_for};
use crate::{Result, Sel, Session};
+const COPY_CONTRACT: TypedContract<CopyParams> = TypedContract::new();
+const CUT_CONTRACT: TypedContract<CutParams> = TypedContract::new();
+const PASTE_CONTRACT: TypedContract<PasteParams> = TypedContract::new();
+
pub static COMMANDS: &[CommandSpec] = &[
- CommandSpec::new("sketch.copy", "Copy Sketch Entities", copy).icon("copy")
+ CommandSpec::new("sketch.copy", "Copy Sketch Entities", crate::checked!("sketch.copy", copy)).icon("copy")
.noundo()
.enabled(in_sketch)
+ .contract(&COPY_CONTRACT)
+ .output(output_schema_for::<Copied>)
.params("entities?: [curve or point ids] (default: the selected sketch geometry); the constraints and dimensions among them come along"),
- CommandSpec::new("sketch.cut", "Cut Sketch Entities", cut).icon("cut")
+ CommandSpec::new("sketch.cut", "Cut Sketch Entities", crate::checked!("sketch.cut", cut)).icon("cut")
.enabled(in_sketch)
+ .contract(&CUT_CONTRACT)
+ .output(output_schema_for::<Copied>)
.params("entities?: [curve or point ids] (default: the selected sketch geometry): copies them as sketch.copy does, then deletes them (one undo step)"),
- CommandSpec::new("sketch.paste", "Paste Sketch Entities", paste).icon("paste").enabled(in_sketch).params(
+ CommandSpec::new("sketch.paste", "Paste Sketch Entities", crate::checked!("sketch.paste", paste))
+ .icon("paste")
+ .enabled(in_sketch)
+ .contract(&PASTE_CONTRACT)
+ .output(output_schema_for::<Pasted>)
+ .params(
"at?: [x, y] (sketch point the copy's centre goes to) | translate?: [x, y]; without either, offset from the original in its own sketch and at the same coordinates in another; sketch?: target (default: the active sketch)",
),
];
@@ -229,15 +244,20 @@ fn copy(s: &mut Session, p: &Value) -> Result<Value> {
clip.center = bounds.center();
let size = bounds.size();
clip.extent = size.x.max(size.y);
- let out = json!({
- "curves": clip.curves.len() + texts.iter().map(|t| sk.link_curves(t).len()).sum::<usize>(),
- "points": clip.lone.len(),
- "texts": texts.len(),
- "constraints": clip.constraints.len(),
- "center": [clip.center.x, clip.center.y],
- });
+ let out = Copied {
+ curves: clip.curves.len() + texts.iter().map(|t| sk.link_curves(t).len()).sum::<usize>(),
+ points: clip.lone.len(),
+ texts: texts.len(),
+ constraints: clip.constraints.len(),
+ center: [clip.center.x, clip.center.y],
+ param_warnings: Vec::new(),
+ };
s.sketch_clipboard = Some(clip);
- Ok(out)
+ reply(cmd, out)
+}
+
+fn reply(cmd: &str, reply: impl serde::Serialize) -> Result<Value> {
+ serde_json::to_value(reply).map_err(|e| bad(cmd, e.to_string()))
}
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
@@ -361,7 +381,7 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
.chain(lone.iter().map(|id| Sel::SketchPoint { id: id.clone() }))
.collect();
}
- Ok(json!({"curves": curves, "points": lone, "constraints": constraints, "translate": [t.x, t.y], "sketch": info}))
+ reply(cmd, Pasted { curves, points: lone, constraints, translate: [t.x, t.y], sketch: info, param_warnings: Vec::new() })
}
#[cfg(test)]
diff --git a/crates/engine/src/schema/mod.rs b/crates/engine/src/schema/mod.rs
index 6004f9beaa..e352ed0b35 100644
--- a/crates/engine/src/schema/mod.rs
+++ b/crates/engine/src/schema/mod.rs
@@ -87,6 +87,7 @@ pub mod render_ui;
pub mod section;
pub mod sheet;
pub mod sketch;
+pub mod sketch_clipboard;
pub mod sketch_constraints;
pub mod sketch_create;
pub mod sketch_ends;
diff --git a/crates/engine/src/schema/sketch_clipboard.rs b/crates/engine/src/schema/sketch_clipboard.rs
new file mode 100644
index 0000000000..8f481c188e
--- /dev/null
+++ b/crates/engine/src/schema/sketch_clipboard.rs
@@ -0,0 +1,119 @@
+//! Contracts and result types for the commands in `cmd/sketch_clipboard.rs`: copying, cutting
+//! and pasting sketch geometry (#10963).
+
+use std::borrow::Cow;
+
+use schemars::{JsonSchema, Schema, SchemaGenerator};
+use serde::de::Error as _;
+use serde::{Deserialize, Deserializer, Serialize};
+use serde_json::Value;
+use solidcore_record::Vec2;
+
+use super::types::{Point2, SketchRef, StringList, present};
+use crate::params;
+
+/// Where a paste goes: a [`Point2`], with the paste's message.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub struct PastePoint(pub Vec2);
+
+impl<'de> Deserialize<'de> for PastePoint {
+ fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
+ params::vec2(&Value::deserialize(d)?).map(PastePoint).ok_or_else(|| D::Error::custom("must be [x, y]"))
+ }
+}
+
+impl JsonSchema for PastePoint {
+ fn schema_name() -> Cow<'static, str> {
+ "PastePoint".into()
+ }
+ fn inline_schema() -> bool {
+ true
+ }
+ fn json_schema(generator: &mut SchemaGenerator) -> Schema {
+ generator.subschema_for::<Point2>()
+ }
+}
+
+/// Copy sketch curves and points, with the constraints and dimensions among them, to the sketch
+/// clipboard. The design is unchanged.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CopyParams {
+ /// Curve or point ids (default: the selected sketch geometry).
+ #[serde(default)]
+ pub entities: Option<StringList>,
+ /// The sketch they are in (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchRef>,
+}
+
+/// Copy sketch curves and points as `sketch.copy` does, then delete them, in one undo step.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct CutParams {
+ /// Curve or point ids (default: the selected sketch geometry).
+ #[serde(default)]
+ pub entities: Option<StringList>,
+ /// The sketch they are in (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchRef>,
+}
+
+/// Paste what was copied into a sketch, with its constraints and dimensions, in one undo step.
+/// The pasted geometry is selected. Without `at` or `translate`, it goes a step away from the
+/// original in its own sketch (further each time), and at the same coordinates in another.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(deny_unknown_fields)]
+pub struct PasteParams {
+ /// The sketch point the copy's centre goes to. Takes the place of `translate`.
+ #[serde(default, deserialize_with = "present")]
+ #[schemars(with = "PastePoint")]
+ pub at: Option<PastePoint>,
+ /// How far to move the copy from where it was (mm).
+ #[serde(default, deserialize_with = "present")]
+ #[schemars(with = "PastePoint")]
+ pub translate: Option<PastePoint>,
+ /// The sketch to paste into (default: the one being edited).
+ #[serde(default)]
+ pub sketch: Option<SketchRef>,
+}
+
+/// What `sketch.copy` and `sketch.cut` return: what is on the clipboard.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct Copied {
+ /// How many curves, those of copied text included.
+ pub curves: usize,
+ /// How many points that belong to no copied curve.
+ pub points: usize,
+ /// How many texts.
+ pub texts: usize,
+ /// How many constraints and dimensions among them came along.
+ pub constraints: usize,
+ /// The centre of what was copied, in sketch coordinates: where `at` puts it.
+ pub center: [f64; 2],
+ /// 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 `sketch.paste` returns.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct Pasted {
+ /// The new curves' ids.
+ pub curves: Vec<String>,
+ /// The new lone points' ids.
+ pub points: Vec<String>,
+ /// The new constraints' and dimensions' ids.
+ pub constraints: Vec<String>,
+ /// How far the copy was moved from where it was (mm).
+ pub translate: [f64; 2],
+ /// The sketch's solve: `{solved, dof}`.
+ pub sketch: Value,
+ /// 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 = "sketch_clipboard_tests.rs"]
+mod tests;
diff --git a/crates/engine/src/schema/sketch_clipboard_tests.rs b/crates/engine/src/schema/sketch_clipboard_tests.rs
new file mode 100644
index 0000000000..76bb1aa847
--- /dev/null
+++ b/crates/engine/src/schema/sketch_clipboard_tests.rs
@@ -0,0 +1,92 @@
+use serde_json::{Value, json};
+
+use super::{Copied, CopyParams, CutParams, PasteParams, Pasted};
+use crate::Session;
+use crate::schema::tests::{assert_keys, conforms};
+use crate::schema::{ParamCheck, input_schema_for, output_schema_for};
+
+fn run(s: &mut Session, id: &str, p: Value) -> Value {
+ s.execute(id, &p).unwrap_or_else(|e| panic!("{id} {p}: {e}"))
+}
+
+/// A sketch `A` being edited, as these commands need, with a line and a circle; the line is
+/// copied. Their ids.
+fn drawing(s: &mut Session) -> (String, String) {
+ run(s, "sketch.create", json!({"plane": "XY", "name": "A"}));
+ let line = run(s, "sketch.line", json!({"points": [[0, 0], [10, 0]]}))["curves"][0].as_str().map(str::to_string).unwrap_or_default();
+ let circle =
+ run(s, "sketch.circle.center", json!({"center": [30, 0], "radius": 4}))["curves"][0].as_str().map(str::to_string).unwrap_or_default();
+ run(s, "sketch.copy", json!({"entities": [line]}));
+ (line, circle)
+}
+
+#[test]
+fn schemas_and_the_key_check_agree() {
+ assert_keys(input_schema_for::<CopyParams>(), &["entities", "sketch"]);
+ assert_keys(input_schema_for::<CutParams>(), &["entities", "sketch"]);
+ assert_keys(input_schema_for::<PasteParams>(), &["at", "sketch", "translate"]);
+}
+
+/// A call that fails today gets the same message in strict. These commands run only while a
+/// sketch is being edited, so each call runs in one (`assert_strict_keeps_todays_errors` runs
+/// after a finished sketch).
+#[test]
+fn strict_keeps_todays_errors() {
+ for (id, p) in [
+ ("sketch.copy", json!({})),
+ ("sketch.copy", json!({"entities": null})),
+ ("sketch.copy", json!({"entities": ["nope"]})),
+ ("sketch.copy", json!({"entities": "l1", "sketch": "Nope"})),
+ ("sketch.cut", json!({"entities": ["nope"]})),
+ ("sketch.paste", json!({"at": "x"})),
+ ("sketch.paste", json!({"at": null})),
+ ("sketch.paste", json!({"at": [1e9, 0]})),
+ ("sketch.paste", json!({"at": "x", "translate": [1, 2]})),
+ ("sketch.paste", json!({"translate": [1, 2, 3]})),
+ ("sketch.paste", json!({"translate": {"x": 1}})),
+ ("sketch.paste", json!({"sketch": "Nope"})),
+ ] {
+ let error = |level: ParamCheck| {
+ let mut s = Session::default();
+ drawing(&mut s);
+ s.param_check = level;
+ s.execute(id, &p).err().map(|e| e.to_string())
+ };
+ let off = error(ParamCheck::Off);
+ assert!(off.is_some(), "{id} {p} should fail today");
+ assert_eq!(error(ParamCheck::Strict), off, "{id} {p}");
+ }
+}
+
+/// #10963: copy, cut and paste reply as their output schemas say, in Warn without warnings for
+/// good calls and with them for a misspelt key: a copy of one curve and of the selection, pastes
+/// without a position, at a point and moved, and a cut pasted back.
+#[test]
+fn clipboard_commands_reply_with_their_schemas() {
+ let (copied, pasted) = (output_schema_for::<Copied>(), output_schema_for::<Pasted>());
+ let matches = |schema: &schemars::Schema, r: &Value, warned: bool| {
+ let schema = schema.as_value();
+ assert!(conforms(schema, schema, r), "{r} doesn't match {schema}");
+ assert_eq!(r.get("param_warnings").is_some(), warned, "{r}");
+ };
+ let mut s = Session { param_check: ParamCheck::Warn, ..Session::default() };
+ let (line, circle) = drawing(&mut s);
+ let r = run(&mut s, "sketch.copy", json!({"entities": [line, circle], "sketch": "A"}));
+ matches(&copied, &r, false);
+ assert_eq!((r["curves"].as_u64(), r["center"].as_array().map(Vec::len)), (Some(2), Some(2)), "{r}");
+ let r = run(&mut s, "sketch.paste", json!({}));
+ matches(&pasted, &r, false);
+ assert_eq!(r["curves"].as_array().map(Vec::len), Some(2), "{r}");
+ // The pasted curves are selected: a copy with no `entities` takes them.
+ matches(&copied, &run(&mut s, "sketch.copy", json!({})), false);
+ matches(&pasted, &run(&mut s, "sketch.paste", json!({"at": [50, 50]})), false);
+ let r = run(&mut s, "sketch.paste", json!({"translate": {"x": 5, "y": -5}, "sketch": "A"}));
+ matches(&pasted, &r, false);
+ assert_eq!(r["translate"], json!([5.0, -5.0]), "{r}");
+ matches(&copied, &run(&mut s, "sketch.cut", json!({"entities": circle})), false);
+ matches(&pasted, &run(&mut s, "sketch.paste", json!({})), false);
+
+ matches(&copied, &run(&mut s, "sketch.copy", json!({"entities": [line], "entites": [line]})), true);
+ matches(&copied, &run(&mut s, "sketch.cut", json!({"entities": [line], "sketc": "A"})), true);
+ matches(&pasted, &run(&mut s, "sketch.paste", json!({"at": [0, 0], "tranlate": [1, 1]})), true);
+}
diff --git a/crates/engine/src/schema/unconverted.txt b/crates/engine/src/schema/unconverted.txt
index 7a6b5011d3..4372312dd1 100644
--- a/crates/engine/src/schema/unconverted.txt
+++ b/crates/engine/src/schema/unconverted.txt
@@ -201,9 +201,7 @@ sketch.constraint.polygon
sketch.constraint.symmetry
sketch.constraint.tangent
sketch.construction
-sketch.copy
sketch.create
-sketch.cut
sketch.delete
sketch.dimension
sketch.dimension_text
@@ -236,7 +234,6 @@ sketch.move_point
sketch.offset
sketch.offset.break
sketch.options
-sketch.paste
sketch.pattern.circular
sketch.pattern.rectangular
sketch.point