Copy, cut and paste sketch geometry (Ctrl+C/X/V, context menu) (#1500)

* Copy, cut and paste sketch geometry (Ctrl+C/X/V, context menu)

Sketch geometry had no copy or paste: Ctrl+C / Ctrl+X / Ctrl+V arrive as
clipboard events that nothing handled, and the sketch context menu had no
Copy, Cut or Paste.

- sketch.copy / sketch.cut / sketch.paste: lines, arcs, circles, ellipses,
  splines, conics, points and text. Constraints and dimensions wholly among
  the copied entities come along (each dimension gets its own parameter
  with the same expression); ones that reach outside, fixes and pattern or
  offset relations are dropped. Paste goes centred at `at`, by
  `translate`, or offset from the original (same sketch) / at the same
  coordinates (another sketch, on its plane). One undo step; the pasted
  geometry is selected.
- Ctrl+C / Ctrl+X / Ctrl+V in a sketch (paste at the cursor), and Cut,
  Copy and Paste in the sketch context menu. Outside a sketch Ctrl+C /
  Ctrl+V copy and paste the selected timeline features. A copy also puts a
  line of text on the system clipboard so the next Ctrl+V is delivered.

Fixes #1480

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

* Keep a pasted text's height and angle expressions, drop its place's

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:
bherbruckandClaude Opus 5.5 authored and GitHub committed 2026-10-15 15:55:10 -04:00
1 parent 7934edcad4
commit 843c548589
20 files changed
+981 -8

No files matched your search

+8
View File
@@ -756,6 +756,8 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
v.push(cmd(app, "sketch.rectangle.two_point", "Rectangle"));
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", "").key("Ctrl+V").on(app.session.sketch_clipboard.is_some()));
return v;
}
let ents: Vec<String> = curves.iter().chain(points.iter()).cloned().collect();
@@ -770,6 +772,9 @@ fn sketch_entity_items(app: &SolveApp) -> Vec<Item> {
v.push(cmd(app, "sketch.edit_text", "Edit Text"));
}
v.push(cmd(app, "sketch.move", "Move/Copy").key("M"));
v.push(act("ui.cut", "Cut", "").key("Ctrl+X"));
v.push(act("ui.copy", "Copy", "").key("Ctrl+C"));
v.push(act("ui.paste", "Paste", "").key("Ctrl+V").on(app.session.sketch_clipboard.is_some()));
if !curves.is_empty() {
v.push(cmd(app, "sketch.construction", "Normal / Construction").with(json!({ "curves": curves })));
}
@@ -852,6 +857,9 @@ pub fn run_item(app: &mut SolveApp, item: &Item, at: Pos2) {
"ui.delete" if item.params.is_some() => crate::delete::request(app, p),
"ui.delete" => delete(app),
"ui.finishSketch" => app.finish_sketch(),
"ui.copy" => drop(crate::edit_clipboard::copy(app)),
"ui.cut" => drop(crate::edit_clipboard::cut(app)),
"ui.paste" => drop(crate::edit_clipboard::paste(app, Some(at))),
"ui.editSketchPattern" => {
if let Some(id) = p.get("pattern").and_then(Value::as_str) {
crate::sketch_modify_ui::edit_pattern(app, id);
+183
View File
@@ -0,0 +1,183 @@
//! Copy, Cut and Paste from the keyboard (Ctrl+C / Ctrl+X / Ctrl+V, ⌘C / ⌘X / ⌘V) and the context
//! menu (#1480).
//!
//! In a sketch they copy the selected sketch geometry (`sketch.copy`) and paste it at the cursor
//! (`sketch.paste` with `at`); Cut copies the sketch geometry and deletes it (`sketch.cut`), or offset from the original when the cursor is not over the
//! viewport. Outside a sketch they copy the selected timeline features and paste them at the
//! history marker (`timeline.copy` / `timeline.paste`).
//!
//! The window system turns Ctrl+C / Ctrl+V into clipboard events, not key presses, and only sends
//! the paste event while the system clipboard holds text. So a copy also puts a short line of
//! text on the system clipboard (a menu's Copy leaves it for the next frame, which has the
//! context to write it).
use std::sync::Mutex;
use egui::Pos2;
use serde_json::{Value, json};
use solidcraft_engine::Sel;
use crate::SolveApp;
/// Text for the system clipboard, written on the next frame.
static PENDING_TEXT: Mutex<Option<String>> = Mutex::new(None);
fn leave_text(text: String) {
if let Ok(mut pending) = PENDING_TEXT.lock() {
*pending = Some(text);
}
}
/// The selected sketch geometry of the active sketch.
fn sketch_selection(app: &SolveApp) -> Vec<String> {
app.session
.selection
.iter()
.filter_map(|s| match s {
Sel::SketchCurve { id } | Sel::SketchPoint { id } => Some(id.clone()),
_ => None,
})
.collect()
}
/// Is there something Copy would copy?
pub fn can_copy(app: &SolveApp) -> bool {
if app.session.active_sketch.is_some() { !sketch_selection(app).is_empty() } else { !crate::timeline::selected_feature_ids(app).is_empty() }
}
/// 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() } else { !app.session.clipboard.is_empty() }
}
/// Copy the selection: sketch geometry in a sketch, otherwise timeline features.
pub fn copy(app: &mut SolveApp) -> bool {
if app.session.active_sketch.is_some() {
let entities = sketch_selection(app);
if entities.is_empty() {
app.set_status("Select sketch geometry to copy", true);
return false;
}
let Ok(out) = app.run("sketch.copy", json!({ "entities": entities })) else { return false };
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");
app.set_status(format!("Copied {n} sketch entities with {k} constraints and dimensions"), false);
leave_text(text);
return true;
}
let features = crate::timeline::selected_feature_ids(app);
if features.is_empty() {
app.set_status("Select sketch geometry or timeline features to copy", true);
return false;
}
let Ok(out) = app.run("timeline.copy", json!({ "features": features })) else { return false };
let names: Vec<&str> = out.get("copied").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).collect()).unwrap_or_default();
app.set_status(format!("Copied {}", names.join(", ")), false);
leave_text(format!("SolidCraft features: {}", names.join(", ")));
true
}
/// Cut the selected sketch geometry: copy it, then delete it (one undo step).
pub fn cut(app: &mut SolveApp) -> bool {
if app.session.active_sketch.is_none() {
app.set_status("Cut works on sketch geometry: edit a sketch and select some", true);
return false;
}
let entities = sketch_selection(app);
if entities.is_empty() {
app.set_status("Select sketch geometry to cut", true);
return false;
}
let Ok(out) = app.run("sketch.cut", json!({ "entities": entities })) else { return false };
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(format!("SolidCraft sketch geometry: {n} entities"));
true
}
/// The point of the active sketch under `at` (screen), when `at` is over the viewport.
fn sketch_point(app: &SolveApp, at: Option<Pos2>) -> Option<[f64; 2]> {
let at = at?;
let rect = app.viewport.rect?;
if !rect.contains(at) {
return None;
}
let proj = crate::viewport::projection(app, rect);
let (p, _) = crate::viewport::sketch_point_at(app, &proj, at)?;
Some([p.x, p.y])
}
/// Paste: in a sketch, the copied sketch geometry centred at `at` (or offset from the original
/// when `at` is not over the sketch); otherwise the copied features at the history marker.
pub fn paste(app: &mut SolveApp, at: Option<Pos2>) -> bool {
if app.session.active_sketch.is_some() {
if app.session.sketch_clipboard.is_none() {
app.set_status("Nothing to paste: copy sketch geometry first", true);
return false;
}
let params = match sketch_point(app, at) {
Some(p) => json!({ "at": p }),
None => json!({}),
};
let Ok(out) = app.run("sketch.paste", params) else { return false };
let n = out.get("curves").and_then(Value::as_array).map_or(0, Vec::len) + out.get("points").and_then(Value::as_array).map_or(0, Vec::len);
app.set_status(format!("Pasted {n} sketch entities (selected: drag them, or press M to move them)"), false);
return true;
}
if app.session.clipboard.is_empty() {
app.set_status("Nothing to paste: copy timeline features first", true);
return false;
}
app.run("timeline.paste", json!({})).is_ok()
}
/// The frame's Copy, Cut and Paste events (and Ctrl+C / Ctrl+X / Ctrl+V sent as key presses), plus any
/// clipboard text a menu's Copy left. Called by the global shortcuts when no text field has the
/// keyboard.
pub fn handle(app: &mut SolveApp, ctx: &egui::Context) {
let (copies, cuts, pastes, pointer) = ctx.input(|i| {
let mut copies = 0;
let mut cuts = 0;
let mut pastes = 0;
for e in &i.events {
match e {
egui::Event::Copy => copies += 1,
egui::Event::Cut => cuts += 1,
egui::Event::Paste(_) => pastes += 1,
egui::Event::Key { key: egui::Key::C, pressed: true, modifiers, .. } if modifiers.command && !modifiers.shift && !modifiers.alt => {
copies += 1
}
egui::Event::Key { key: egui::Key::X, pressed: true, modifiers, .. } if modifiers.command && !modifiers.shift && !modifiers.alt => {
cuts += 1
}
egui::Event::Key { key: egui::Key::V, pressed: true, modifiers, .. } if modifiers.command && !modifiers.shift && !modifiers.alt => {
pastes += 1
}
_ => {}
}
}
(copies, cuts, pastes, i.pointer.latest_pos())
});
if copies > 0 {
copy(app);
}
if cuts > 0 {
cut(app);
}
if pastes > 0 {
paste(app, pointer);
}
flush(ctx);
}
/// Write clipboard text a copy left.
pub fn flush(ctx: &egui::Context) {
if let Some(text) = PENDING_TEXT.lock().ok().and_then(|mut p| p.take()) {
ctx.copy_text(text);
}
}
#[cfg(test)]
#[path = "edit_clipboard_tests.rs"]
mod tests;
+164
View File
@@ -0,0 +1,164 @@
//! Copy and Paste from the keyboard and the context menu (#1480).
use serde_json::{Value, json};
use solidcraft_engine::Sel;
use solidcraft_engine::geom::Vec2;
use crate::scenario::Harness;
fn strs(v: &Value) -> Vec<String> {
v.as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
/// A sketch on XY with a 20 × 10 rectangle (dimensioned, its corner on the origin), looked at
/// from the top, and the rectangle selected.
fn rectangle() -> (Harness, Vec<String>) {
let mut h = Harness::new();
h.app.run("sketch.create", json!({"plane": "XY"})).unwrap();
let rect = strs(&h.app.run("sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]})).unwrap()["curves"]);
h.app.run("sketch.constraint.coincident", json!({"a": format!("{}.start", rect[0]), "b": "origin"})).unwrap();
h.app.run("sketch.dimension", json!({"entities": [rect[0]], "value": 20})).unwrap();
h.app.run("sketch.dimension", json!({"entities": [rect[1]], "value": 10})).unwrap();
h.call("ui.view", json!({"view": "top"}));
h.call("ui.camera", json!({"target": [20, 10, 0], "distance": 150}));
let items: Vec<Value> = rect.iter().map(|id| json!({"type": "sketch_curve", "id": id})).collect();
h.app.run("select.set", json!({ "items": items })).unwrap();
h.frames(4);
(h, rect)
}
/// Send the window system's clipboard event (what Ctrl+C / Ctrl+V become), with the pointer at
/// `at` (sketch coordinates) or off the viewport.
fn clipboard_event(h: &mut Harness, event: egui::Event, at: Option<[f64; 2]>) {
match at {
Some(p) => h.step(&json!({"move": {"sketch": p}})).unwrap(),
None => drop(h.call("ui.move", json!({"x": 100, "y": 990}))),
}
h.app.synthetic.push(event);
h.settle();
}
fn curves(h: &Harness) -> Vec<String> {
h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap().curves.iter().map(|c| c.id.clone()).collect()
}
fn start(h: &Harness, id: &str) -> Vec2 {
let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap();
let c = &sk.curves[sk.curve_index(id).unwrap()];
sk.point(c.kind.point_ids()[0]).unwrap()
}
#[test]
fn ctrl_c_ctrl_v_pastes_the_sketch_selection_at_the_cursor_selected_in_one_undo_step() {
let (mut h, rect) = rectangle();
let before = curves(&h);
let undo = h.app.session.undo.len();
clipboard_event(&mut h, egui::Event::Copy, Some([10.0, 5.0]));
assert!(h.app.session.sketch_clipboard.is_some(), "{:?}", h.app.status);
// The window system only sends Paste while its clipboard holds text: a copy leaves some.
h.call("ui.inspect", json!({}));
clipboard_event(&mut h, egui::Event::Paste("x".into()), Some([60.0, 40.0]));
let after = curves(&h);
assert_eq!(after.len(), before.len() + 4, "{:?}", h.app.status);
let pasted: Vec<String> = after.iter().filter(|c| !before.contains(c)).cloned().collect();
// Centred at the cursor: the rectangle (centre 10, 5) goes to (60, 40), give or take the snap.
let corner = start(&h, &pasted[0]);
assert!(corner.dist(Vec2::new(50.0, 35.0)) < 1.0, "{corner:?}");
// The originals stay put, with their constraints.
assert!(start(&h, &rect[0]).dist(Vec2::ZERO) < 1e-9);
// Selected, ready to move.
let selected: Vec<String> =
h.app.session.selection.iter().filter_map(|s| if let Sel::SketchCurve { id } = s { Some(id.clone()) } else { None }).collect();
assert_eq!(selected, pasted);
// One undo step.
assert_eq!(h.app.session.undo.len(), undo + 1);
h.step(&json!({"key": "Z", "cmd": true})).unwrap();
assert_eq!(curves(&h), before);
}
#[test]
fn copy_leaves_text_on_the_system_clipboard_so_paste_can_follow() {
let (mut h, _) = rectangle();
h.step(&json!({"move": {"sketch": [10, 5]}})).unwrap();
h.app.synthetic.push(egui::Event::Copy);
let mut copied = Vec::new();
for _ in 0..6 {
h.frame();
copied.extend(h.output.commands.iter().filter_map(|c| match c {
egui::OutputCommand::CopyText(text) => Some(text.clone()),
_ => None,
}));
}
assert!(copied.iter().any(|t| t.starts_with("SolidCraft sketch geometry")), "{copied:?}");
}
#[test]
fn paste_away_from_the_viewport_offsets_from_the_original_and_cmd_keys_work_too() {
let (mut h, rect) = rectangle();
let before = curves(&h);
// Ctrl+C / Ctrl+V as key presses (as the control channel and some platforms send them).
h.step(&json!({"move": {"sketch": [10, 5]}})).unwrap();
h.step(&json!({"key": "C", "cmd": true})).unwrap();
h.call("ui.move", json!({"x": 100, "y": 990}));
h.step(&json!({"key": "V", "cmd": true})).unwrap();
let pasted: Vec<String> = curves(&h).into_iter().filter(|c| !before.contains(c)).collect();
assert_eq!(pasted.len(), 4, "{:?}", h.app.status);
// 20 mm wide: a 2 mm step down and to the right.
let d = start(&h, &pasted[0]) - start(&h, &rect[0]);
assert!(d.dist(Vec2::new(2.0, -2.0)) < 1e-6, "{d:?}");
}
#[test]
fn the_context_menu_copies_and_pastes_sketch_geometry_at_the_click() {
let (mut h, rect) = rectangle();
let before = curves(&h);
h.step(&json!({"click": {"sketch": [10, 0]}, "button": "right"})).unwrap();
let menu = h.call("ui.menu", json!({}));
let labels: Vec<&str> = menu["result"]["items"].as_array().unwrap().iter().filter_map(|i| i["label"].as_str()).collect();
assert!(labels.contains(&"Copy") && labels.contains(&"Paste"), "{labels:?}");
h.call("ui.menuPick", json!({"item": "Copy"}));
assert!(h.app.session.sketch_clipboard.is_some());
h.step(&json!({"click": {"sketch": [70, 30]}, "button": "right"})).unwrap();
h.call("ui.menuPick", json!({"item": "Paste"}));
h.frames(3);
let pasted: Vec<String> = curves(&h).into_iter().filter(|c| !before.contains(c)).collect();
assert!(!pasted.is_empty(), "{:?}", h.app.status);
// Whatever the right-click selected was copied, and its copy is centred on the click.
let sk = h.app.session.doc.sketch(h.app.session.active_sketch.unwrap()).unwrap();
let pts: Vec<Vec2> = pasted.iter().flat_map(|c| sk.curves[sk.curve_index(c).unwrap()].kind.point_ids()).map(|i| sk.point(i).unwrap()).collect();
let (lo, hi) = pts.iter().fold((Vec2::new(1e9, 1e9), Vec2::new(-1e9, -1e9)), |(lo, hi), p| {
(Vec2::new(lo.x.min(p.x), lo.y.min(p.y)), Vec2::new(hi.x.max(p.x), hi.y.max(p.y)))
});
assert!(((lo + hi) * 0.5).dist(Vec2::new(70.0, 30.0)) < 1.0, "{lo:?} {hi:?}");
assert!(start(&h, &rect[0]).dist(Vec2::ZERO) < 1e-9);
}
#[test]
fn ctrl_c_ctrl_v_outside_a_sketch_copies_and_pastes_timeline_features() {
let mut h = Harness::new();
h.app.run("solid.box", json!({"length": 10, "width": 10, "height": 10})).unwrap();
h.frames(3);
let id = h.app.session.doc.features[0].id;
h.app.run("select.set", json!({"items": [{"type": "feature", "id": id}]})).unwrap();
h.frames(2);
clipboard_event(&mut h, egui::Event::Copy, None);
clipboard_event(&mut h, egui::Event::Paste("x".into()), None);
assert_eq!(h.app.session.doc.features.len(), 2, "{:?}", h.app.status);
}
#[test]
fn ctrl_x_cuts_the_sketch_selection_and_ctrl_v_brings_it_back() {
let (mut h, rect) = rectangle();
let before = curves(&h);
clipboard_event(&mut h, egui::Event::Cut, Some([10.0, 5.0]));
let left = curves(&h);
assert!(rect.iter().all(|c| !left.contains(c)), "{:?}", h.app.status);
assert!(h.app.session.sketch_clipboard.is_some());
clipboard_event(&mut h, egui::Event::Paste("x".into()), Some([10.0, 5.0]));
assert_eq!(curves(&h).len(), before.len(), "{:?}", h.app.status);
// The context menu offers Cut too.
h.step(&json!({"click": {"sketch": [10, 0]}, "button": "right"})).unwrap();
let menu = h.call("ui.menu", json!({}));
let labels: Vec<&str> = menu["result"]["items"].as_array().unwrap().iter().filter_map(|i| i["label"].as_str()).collect();
assert!(labels.contains(&"Cut"), "{labels:?}");
}
+19 -2
View File
@@ -13,8 +13,25 @@ use crate::SolveApp;
use crate::theme::Tokens;
/// Keys the application handles before any command shortcut.
pub const RESERVED: &[&str] =
&["Escape", "S", "V", "F2", "F6", "Delete", "Backspace", "Ctrl+Z", "Ctrl+Y", "Ctrl+S", "Ctrl+N", "Ctrl+O", "Ctrl+Comma", "Ctrl+Shift+A"];
pub const RESERVED: &[&str] = &[
"Escape",
"S",
"V",
"F2",
"F6",
"Delete",
"Backspace",
"Ctrl+Z",
"Ctrl+Y",
"Ctrl+S",
"Ctrl+N",
"Ctrl+O",
"Ctrl+Comma",
"Ctrl+Shift+A",
"Ctrl+C",
"Ctrl+X",
"Ctrl+V",
];
#[derive(Default)]
pub struct Keymap {
+1
View File
@@ -39,6 +39,7 @@ pub mod dim_view;
mod dimension_create_ui_tests;
pub mod documents;
pub mod drag_snap;
pub mod edit_clipboard;
pub mod fonts;
pub mod frame;
pub mod gizmo;
+7
View File
@@ -1261,6 +1261,11 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
});
// Home hides the design: only New, Open and Preferences work there.
let shown = design_shown(app);
if shown {
crate::edit_clipboard::handle(app, ctx);
} else {
crate::edit_clipboard::flush(ctx);
}
for k in keys {
use egui::Key;
if mods.command {
@@ -1277,6 +1282,8 @@ pub fn shortcuts(app: &mut SolveApp, ctx: &egui::Context) {
_ if !shown => {}
Key::Z => drop(app.run("edit.undo", json!({}))),
Key::Y => drop(app.run("edit.redo", json!({}))),
// Copy, Cut and Paste (`edit_clipboard::handle`).
Key::C | Key::X | Key::V if !mods.shift && !mods.alt => {}
Key::S => save(app),
_ => crate::keymap::press(app, &crate::keymap::key_name(k, mods)),
}