Skip to content

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

Sketch: paste copied sketch geometry into another design (#9258) (#9675)

PaddleStrokec2f66107cfc5
diff --git a/crates/engine/src/cmd/sketch_clipboard.rs b/crates/engine/src/cmd/sketch_clipboard.rs
index b9eddfa49d..fbe6b3c4bb 100644
--- a/crates/engine/src/cmd/sketch_clipboard.rs
+++ b/crates/engine/src/cmd/sketch_clipboard.rs
@@ -71,6 +71,38 @@ pub struct SketchClip {
pub pastes: u32,
}
+impl SketchClip {
+ /// This clipboard as another design pastes it (#9258): at the same sketch coordinates (its
+ /// sketch ids mean nothing there), and with nothing that names the copied design's
+ /// parameters. A dimension whose expression names a parameter keeps its value, in its unit
+ /// (another design's parameter of the same name would be another thing); a text keeps its
+ /// words, height and angle as numbers.
+ pub fn for_another_design(&self) -> SketchClip {
+ let mut clip = self.clone();
+ clip.sketch = u64::MAX;
+ clip.pastes = 0;
+ for c in &mut clip.constraints {
+ let Some((expr, unit)) = c.param.as_mut() else { continue };
+ if solidcraft_doc::expr::references(expr).is_empty() {
+ continue;
+ }
+ let v = c.kind.value().unwrap_or_default();
+ if solidcraft_doc::expr::unit_info(unit).is_none() {
+ *unit = if c.kind.is_angle() { "rad" } else { "mm" }.into();
+ }
+ let value = if c.kind.is_angle() { solidcraft_doc::expr::Value::angle(v) } else { solidcraft_doc::expr::Value::length(v) };
+ let shown = solidcraft_doc::expr::value_in_unit(value, unit);
+ *expr = format!("{}", if shown.is_finite() { shown } else { 0.0 });
+ }
+ for (src, _) in &mut clip.texts {
+ if let LinkSource::Text { exprs, .. } = src {
+ *exprs = Default::default();
+ }
+ }
+ clip
+ }
+}
+
/// Curve and point ids named by `entities`, or the selected sketch geometry.
fn chosen(s: &Session, p: &Value, cmd: &str) -> Result<Vec<String>> {
if p.get("entities").is_some() {
diff --git a/crates/engine/src/cmd/sketch_clipboard_tests.rs b/crates/engine/src/cmd/sketch_clipboard_tests.rs
index 7d1e919e96..72371c6c8c 100644
--- a/crates/engine/src/cmd/sketch_clipboard_tests.rs
+++ b/crates/engine/src/cmd/sketch_clipboard_tests.rs
@@ -251,3 +251,45 @@ fn clipboard_commands_refuse_parameters_that_are_not_an_object() {
// Nothing was cut or pasted by the refused calls.
assert!(s.execute("sketch.paste", &json!({})).is_ok(), "the clipboard still holds the copy");
}
+
+/// Sketch geometry copied in one design pastes into a sketch of another (#9258): at the same
+/// coordinates, with its constraints and dimensions. A dimension that named the first design's
+/// parameter keeps its value as a number in its unit (the other design's `w` is another thing);
+/// one typed as a number keeps it.
+#[test]
+fn sketch_geometry_pastes_into_another_design_with_values_not_foreign_parameters() {
+ let mut a = Session::default();
+ run(&mut a, "parameters.change", json!({"name": "w", "expression": "1 in"}));
+ run(&mut a, "sketch.create", json!({"plane": "XY"}));
+ let rect = strs(&run(&mut a, "sketch.rectangle.two_point", json!({"p0": [5, 5], "p1": [30, 15]}))["curves"]);
+ run(&mut a, "sketch.dimension", json!({"entities": [rect[0]], "value": "w"}));
+ run(&mut a, "sketch.dimension", json!({"entities": [rect[1]], "value": 10}));
+ let sa = a.active_sketch.unwrap();
+ let corner = pos(sketch(&a, sa), &rect[0]);
+ run(&mut a, "sketch.copy", json!({"entities": rect}));
+ let clip = a.sketch_clipboard.clone().unwrap();
+
+ let mut b = Session::default();
+ // Another design with its own `w`, and a sketch with the copied one's id.
+ run(&mut b, "parameters.change", json!({"name": "w", "expression": "3 mm"}));
+ run(&mut b, "sketch.create", json!({"plane": "XZ"}));
+ let sb = b.active_sketch.unwrap();
+ assert_eq!(sb, sa, "same id: the copy must still not be offset as if pasted back into its own sketch");
+ b.sketch_clipboard = Some(clip.for_another_design());
+ let pasted = strs(&run(&mut b, "sketch.paste", json!({}))["curves"]);
+ assert_eq!(pasted.len(), 4);
+ let sk = sketch(&b, sb);
+ let at = pos(sk, &pasted[0]);
+ assert!(at.iter().zip(&corner).all(|(p, q)| p.dist(*q) < 1e-6), "{at:?} vs {corner:?}");
+ let exprs: Vec<String> = sk.constraints.iter().filter_map(|c| c.param.as_ref()).filter_map(|n| b.doc.param(n)).map(|p| p.expr.clone()).collect();
+ assert_eq!(exprs.len(), 2, "{exprs:?}");
+ assert!(exprs.iter().all(|e| solidcraft_doc::expr::references(e).is_empty()), "{exprs:?}");
+ assert!(exprs.iter().any(|e| e == "10"), "{exprs:?}");
+ let width = sk.constraints.iter().filter_map(|c| c.kind.value()).fold(0.0_f64, f64::max);
+ assert!((width - 25.4).abs() < 1e-6, "the width stays 1 in, not the other design's w: {width}");
+ assert!(b.doc.params.iter().filter(|p| p.name == "w").all(|p| p.expr == "3 mm"), "its own w is untouched");
+ // Each paste without a position lands at the copied coordinates.
+ let again = strs(&run(&mut b, "sketch.paste", json!({}))["curves"]);
+ let at = pos(sketch(&b, sb), &again[0]);
+ assert!(at.iter().zip(&corner).all(|(p, q)| p.dist(*q) < 1e-6), "{at:?}");
+}
diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs
index 643f061eb0..c60f7863c0 100644
--- a/crates/ui-egui/src/context_menu.rs
+++ b/crates/ui-egui/src/context_menu.rs
@@ -1155,7 +1155,7 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
v.push(cmd(app, "sketch.circle.center", "Circle"));
v.push(cmd(app, "sketch.dimension", "Sketch Dimension"));
v.push(Item::sep());
- v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(app.session.sketch_clipboard.is_some()));
+ v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste_sketch(app)));
return v;
}
let ents: Vec<String> = curves.iter().chain(points.iter()).cloned().collect();
@@ -1220,7 +1220,7 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
// The clipboard beside Delete, as in every menu.
v.push(act("ui.cut", "Cut", "cut").key("Ctrl+X"));
v.push(act("ui.copy", "Copy", "copy").key("Ctrl+C"));
- v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(app.session.sketch_clipboard.is_some()));
+ v.push(act("ui.paste", "Paste", "paste").key("Ctrl+V").on(crate::edit_clipboard::can_paste_sketch(app)));
v.push(act("ui.delete", "Delete", "delete").key("Del"));
v.push(cmd(app, "sketch.dimension", "Sketch Dimension").with(json!({ "entities": ents })).on(ents.len() <= 2));
// One arc alone: Sketch Dimension gives its radius, this its length along the curve (#6039).
diff --git a/crates/ui-egui/src/edit_clipboard.rs b/crates/ui-egui/src/edit_clipboard.rs
index 70033ce997..9efbfabf3c 100644
--- a/crates/ui-egui/src/edit_clipboard.rs
+++ b/crates/ui-egui/src/edit_clipboard.rs
@@ -17,7 +17,10 @@
//! and copied components as independent copies with their history (Paste and Paste New alike),
//! where they were in the world (`component.paste_from_design`); completed sketches paste as
//! independent features with their parameters (`timeline.paste`); cut ones paste there as copies,
-//! the originals staying. The last copy or cut in any design is what pastes: a design's own
+//! the originals staying. Sketch geometry copied or cut in a sketch pastes into a sketch of
+//! another design (`sketch.paste`), at the cursor or at the copied coordinates, with the
+//! constraints and dimensions among it; a dimension that named the copied design's parameters
+//! keeps its value instead (#9258). The last copy or cut in any design is what pastes: a design's own
//! clipboard empties when another design copied after it.
//!
//! The window system turns Ctrl+C / Ctrl+V into clipboard events, not key presses, and only sends
@@ -106,6 +109,17 @@ fn foreign(app: &SolveApp) -> Option<&std::sync::Arc<solidcraft_engine::ForeignC
app.foreign_copy.as_ref().filter(|_| app.own_clipboard_stamp != app.clipboard_stamp)
}
+/// Sketch geometry another design copied or cut last, when that is what pastes here.
+fn foreign_sketch(app: &SolveApp) -> Option<&solidcraft_engine::cmd::sketch_clipboard::SketchClip> {
+ app.foreign_sketch_clip.as_ref().filter(|_| app.own_clipboard_stamp != app.clipboard_stamp)
+}
+
+/// Is there sketch geometry to paste into the active sketch: this design's, or another's copied
+/// last?
+pub fn can_paste_sketch(app: &SolveApp) -> bool {
+ app.session.sketch_clipboard.is_some() || foreign_sketch(app).is_some()
+}
+
/// Bodies another design copied or cut last: they paste here as imported bodies.
fn foreign_bodies(app: &SolveApp) -> bool {
foreign(app).is_some_and(|c| !c.bodies.is_empty())
@@ -126,7 +140,7 @@ pub(crate) fn drop_stale(app: &mut SolveApp) {
/// Is there something Paste would paste here?
pub fn can_paste(app: &SolveApp) -> bool {
if app.session.active_sketch.is_some() {
- app.session.sketch_clipboard.is_some()
+ can_paste_sketch(app)
} else if app.linked_design_clipboard.is_some() {
// A copied design is what pastes, and never into itself.
!design_copied_here(app)
@@ -241,6 +255,7 @@ fn replace_clipboard(app: &mut SolveApp) {
app.clipboard_stamp += 1;
app.own_clipboard_stamp = app.clipboard_stamp;
app.foreign_copy = None;
+ app.foreign_sketch_clip = None;
app.copied_bodies.clear();
app.copied_placements.clear();
app.cut = CutSet::default();
@@ -290,6 +305,7 @@ pub fn copy(app: &mut SolveApp) -> bool {
// The command says why when it fails.
let Ok(out) = app.run("sketch.copy", json!({ "entities": entities })) else { return copy_failed(app, None) };
replace_clipboard(app);
+ app.foreign_sketch_clip = app.session.sketch_clipboard.clone();
let n = out.get("curves").and_then(Value::as_u64).unwrap_or(0) + out.get("points").and_then(Value::as_u64).unwrap_or(0);
let k = out.get("constraints").and_then(Value::as_u64).unwrap_or(0);
let text = format!("SolidCraft sketch geometry: {n} entities, {k} constraints and dimensions");
@@ -460,6 +476,7 @@ pub fn cut(app: &mut SolveApp) -> bool {
}
let Ok(out) = app.run("sketch.cut", json!({ "entities": entities })) else { return copy_failed(app, None) };
replace_clipboard(app);
+ app.foreign_sketch_clip = app.session.sketch_clipboard.clone();
let n = out.get("curves").and_then(Value::as_u64).unwrap_or(0) + out.get("points").and_then(Value::as_u64).unwrap_or(0);
app.set_status(format!("Cut {n} sketch entities"), false);
leave_text(app, format!("SolidCraft sketch geometry: {n} entities"));
@@ -500,6 +517,11 @@ pub fn paste_into(app: &mut SolveApp, at: Option<Pos2>, new_copy: bool, into: Op
(active, app.session.active_occurrence_path.clone().unwrap_or_else(|| app.session.doc.first_path(active)))
});
if app.session.active_sketch.is_some() {
+ // Another design copied sketch geometry last: it pastes here at the same sketch
+ // coordinates, its dimensions keeping their values rather than that design's parameters.
+ if let Some(clip) = foreign_sketch(app).map(|c| c.for_another_design()) {
+ app.session.sketch_clipboard = Some(clip);
+ }
if app.session.sketch_clipboard.is_none() {
app.set_status("Nothing to paste: copy sketch geometry first", true);
return false;
diff --git a/crates/ui-egui/src/edit_clipboard_tests.rs b/crates/ui-egui/src/edit_clipboard_tests.rs
index e37e8d7d92..e7bee3e620 100644
--- a/crates/ui-egui/src/edit_clipboard_tests.rs
+++ b/crates/ui-egui/src/edit_clipboard_tests.rs
@@ -222,6 +222,41 @@ fn completed_sketch_copies_and_pastes_into_a_new_design() {
assert!(h.app.session.model.result(copied.id).unwrap().error.is_none());
}
+/// Sketch geometry copied in a sketch pastes into a sketch of another design (tab) with Ctrl+V,
+/// at the cursor, with its constraints and dimensions, in one undo step; the context menu offers
+/// it there too. A copy made since in that design is what pastes back in the first (#9258).
+#[test]
+fn sketch_geometry_copies_into_a_sketch_of_another_design() {
+ let (mut h, _) = rectangle();
+ clipboard_event(&mut h, egui::Event::Copy, Some([10.0, 5.0]));
+ crate::documents::new_tab(&mut h.app);
+ assert!(!super::can_paste(&h.app), "outside a sketch, sketch geometry has nowhere to go");
+ h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();
+ h.call("ui.view", json!({"view": "top"}));
+ h.call("ui.camera", json!({"target": [20, 10, 0], "distance": 150}));
+ h.frames(4);
+ assert!(super::can_paste(&h.app));
+ let menu = crate::context_menu::items(&h.app, &crate::context_menu::Target::Viewport);
+ assert!(menu.iter().any(|i| i.id == "ui.paste" && i.enabled), "the sketch menu's Paste is on");
+ let undo = h.app.session.undo.len();
+ clipboard_event(&mut h, egui::Event::Paste("SolidCraft sketch geometry".into()), Some([60.0, 40.0]));
+ let pasted = curves(&h);
+ assert_eq!(pasted.len(), 4, "{:?}", h.app.status);
+ let corner = start(&h, &pasted[0]);
+ assert!(corner.dist(Vec2::new(50.0, 35.0)) < 1.0, "{corner:?}");
+ let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap();
+ assert_eq!(sk.constraints.iter().filter(|c| c.param.is_some()).count(), 2, "both dimensions came along");
+ assert_eq!(h.app.session.undo.len(), undo + 1);
+ // A copy in this design is now the last: the first design pastes it.
+ let items: Vec<Value> = pasted.iter().take(1).map(|id| json!({"type": "sketch_curve", "id": id})).collect();
+ h.app.run("select.set", json!({ "items": items })).unwrap();
+ assert!(super::copy(&mut h.app));
+ crate::documents::switch(&mut h.app, 0);
+ let before = curves(&h).len();
+ assert!(super::paste(&mut h.app, None), "{:?}", h.app.status);
+ assert_eq!(curves(&h).len(), before + 1, "the one line copied last, not the rectangle copied here before");
+}
+
#[test]
fn copied_sketch_survives_source_close_and_pastes_from_a_sketch_group_menu() {
use crate::context_menu::{Target, items, run_item};
diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs
index 51615b6039..1358cd0151 100644
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@ -609,6 +609,9 @@ pub struct SolveApp {
/// The bodies (or components) the last copy or cut took, with the design they were in, to
/// paste into another design (`component.paste_from_design`).
pub foreign_copy: Option<std::sync::Arc<solidcraft_engine::ForeignCopy>>,
+ /// The sketch geometry the last copy or cut took, when it was sketch geometry: a sketch of
+ /// another design pastes it (#9258).
+ pub foreign_sketch_clip: Option<solidcraft_engine::cmd::sketch_clipboard::SketchClip>,
/// Esc was already acted on this frame (by the shortcuts), so later handlers skip it.
pub esc_handled: bool,
pub(crate) escape_owner: Option<EscapeOwner>,
@@ -813,6 +816,7 @@ impl SolveApp {
clipboard_stamp: 0,
own_clipboard_stamp: 0,
foreign_copy: None,
+ foreign_sketch_clip: None,
esc_handled: false,
escape_owner: None,
last_escape: None,