SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Cancel Sketch: leave a sketch without keeping its changes (#3838) (#3938)
leValdemar197e472bc4da56
diff --git a/assets/icons/ui/design/aliases.toml b/assets/icons/ui/design/aliases.tomlindex adb998138c..ed1ec592ea 100644--- a/assets/icons/ui/design/aliases.toml+++ b/assets/icons/ui/design/aliases.toml@@ -29,6 +29,7 @@ ground = "c_fix"# Same finished drawing, different semantic operation. Colours live only in palette.toml.sketch_break = { master = "break", accent = "sketch" }+sketch_cancel = { master = "close", accent = "sketch" }sketch_dxf = { master = "dxf", accent = "sketch" }sketch_move = { master = "move", accent = "sketch" }sketch_scale = { master = "scale", accent = "sketch" }diff --git a/assets/icons/ui/design/requested_icons.txt b/assets/icons/ui/design/requested_icons.txtindex 7320b73aec..6efdd64547 100644--- a/assets/icons/ui/design/requested_icons.txt+++ b/assets/icons/ui/design/requested_icons.txt@@ -212,6 +212,7 @@ shield falsesilhouette falsesketch falsesketch_break false+sketch_cancel falsesketch_chamfer falsesketch_chamfer_angle falsesketch_chamfer_equal falsediff --git a/assets/locales/en.json b/assets/locales/en.jsonindex c28d1abc54..9145cbbb3a 100644--- a/assets/locales/en.json+++ b/assets/locales/en.json@@ -834,6 +834,7 @@"cmd.sketch_auto_constrain_from_datum": "AutoConstrain from datum","cmd.sketch_auto_project": "Auto-Project Edges on Reference","cmd.sketch_blend_curve": "Blend Curve",+ "cmd.sketch_cancel": "Cancel Sketch","cmd.sketch_chain": "Chain","cmd.sketch_chamfer_distance_angle": "Distance and Angle Chamfer","cmd.sketch_chamfer_equal_distance": "Equal Distance Chamfer",diff --git a/assets/locales/ja.json b/assets/locales/ja.jsonindex 002c0bad48..0105067e37 100644--- a/assets/locales/ja.json+++ b/assets/locales/ja.json@@ -834,6 +834,7 @@"cmd.sketch_auto_constrain_from_datum": "基準から自動拘束","cmd.sketch_auto_project": "参照上のエッジを自動投影","cmd.sketch_blend_curve": "ブレンド曲線",+ "cmd.sketch_cancel": "スケッチをキャンセル","cmd.sketch_chain": "チェーン","cmd.sketch_chamfer_distance_angle": "距離と角度の面取り","cmd.sketch_chamfer_equal_distance": "等距離面取り",diff --git a/assets/locales/zh.json b/assets/locales/zh.jsonindex 2fdfbcce8c..b542c05e30 100644--- a/assets/locales/zh.json+++ b/assets/locales/zh.json@@ -834,6 +834,7 @@"cmd.sketch_auto_constrain_from_datum": "基于基准自动约束","cmd.sketch_auto_project": "自动投影边到参考","cmd.sketch_blend_curve": "混合曲线",+ "cmd.sketch_cancel": "取消草图","cmd.sketch_chain": "连续链","cmd.sketch_chamfer_distance_angle": "距离和角度倒角","cmd.sketch_chamfer_equal_distance": "等距倒角",diff --git a/crates/engine/src/cmd/sketch.rs b/crates/engine/src/cmd/sketch.rsindex 0551783137..402bc116cd 100644--- a/crates/engine/src/cmd/sketch.rs+++ b/crates/engine/src/cmd/sketch.rs@@ -7,7 +7,7 @@ use solidcraft_sketch::{Analysis, Budget, ConstraintKind, CurveKind, Hold, Pointuse super::{CommandSpec, in_sketch};use crate::params::{bad, bool_, expr, num, req_vec2, str_, string_list, vec2, vec3};-use crate::{EngineError, Result, Session};+use crate::{EngineError, Result, Session, SketchEntry};#[path = "sketch_dimensioned.rs"]mod dimensioned;@@ -32,6 +32,11 @@ pub static COMMANDS: &[CommandSpec] = &[.params("plane: XY|XZ|YZ | construction plane name or id | {origin?: [x,y,z] numbers in mm, default [0,0,0] (not an expression), x_dir, y_dir} | {face: [world x,y,z], body?: exact world body, index?: face index, path?: complete occurrence ids, fixed?: bool}; new face attachments require a unique certified source (a flat face of a sheet metal body attaches to its panel instead, in the flat pattern's coordinates), fixed:true explicitly freezes the selected plane; offset?: expr, flip?: bool | \"x\" | \"y\" (not on a face: sketch the plane from its other side, so the normal and the default extrude direction are reversed; a half turn about the plane's own x or y axis, true picks the one keeping the sketch's y axis upward; offset still moves along the unflipped normal), project_edges?: bool, name?"),CommandSpec::new("sketch.edit", "Edit Sketch", edit_sketch).noundo().icon("sketch").params("sketch: id or name"),CommandSpec::new("sketch.finish", "Finish Sketch", finish_sketch).at("SKETCH", "FINISH SKETCH").icon("finish").enabled(in_sketch).noundo(),+ CommandSpec::new("sketch.cancel", "Cancel Sketch", cancel_sketch)+ .at("SKETCH", "FINISH SKETCH")+ .icon("sketch_cancel")+ .enabled(in_sketch)+ .params("Leaves the sketch without keeping what changed since it was created or opened for editing: the design goes back to how it was then (a new sketch is removed), as one step that Undo brings back. Refused when the undo history no longer leads back to that point (use Undo instead)"),CommandSpec::new("sketch.line", "Line", draw_line).at("SKETCH", "CREATE").icon("line")@@ -721,6 +726,7 @@ pub(super) fn create_face_profile(s: &mut Session, p: &Value, body: &str, index:}fn create_sketch_with_plane(s: &mut Session, p: &Value, plane: PlaneRef, internal_body: Option<(&str, usize)>) -> Result<Value> {+ let before = entry_point(s);if face::is_face(p) {face::capture_positions(s, &plane)?;}@@ -738,6 +744,7 @@ fn create_sketch_with_plane(s: &mut Session, p: &Value, plane: PlaneRef, internaf.component = comp;}s.active_sketch = Some(id);+ s.sketch_entry = Some(SketchEntry { sketch: id, ..before });let name = s.doc.feature(id).map(|f| f.name.clone()).unwrap_or_default();// Sketching on a face projects the face's edges (unless turned off).let face = p.get("plane").and_then(|v| v.get("face")).and_then(vec3);@@ -788,13 +795,56 @@ fn edit_sketch(s: &mut Session, p: &Value) -> Result<Value> {s.active_component = component;s.active_occurrence_path = (!path.is_empty()).then_some(path);}+ if s.active_sketch != Some(id) || s.sketch_entry.as_ref().is_none_or(|entry| entry.sketch != id) {+ s.sketch_entry = Some(SketchEntry { sketch: id, ..entry_point(s) });+ }s.active_sketch = Some(id);s.revision += 1;Ok(json!({"sketch": id, "name": name}))}+/// The design and undo history as they are now, where a sketch is entered (its id set after).+fn entry_point(s: &Session) -> SketchEntry {+ SketchEntry { sketch: 0, doc: s.doc.clone(), undo_len: s.undo.len(), undo_top: s.undo.last().map(|snap| snap.doc.clone()) }+}++/// Cancel Sketch (#3838): the design as it was when the open sketch was entered. The entry is+/// used only while the undo history still runs through it: the same steps before it, and every+/// step since taken in this sketch. Otherwise the steps since can't be told apart from others,+/// and Undo is the way back.+fn cancel_sketch(s: &mut Session, _p: &Value) -> Result<Value> {+ let cmd = "sketch.cancel";+ let id = s.active_sketch.ok_or_else(|| bad(cmd, "no sketch is being edited"))?;+ let entry = s.sketch_entry.clone().filter(|entry| entry.sketch == id);+ let current = entry.filter(|entry| {+ let top = entry.undo_len.checked_sub(1).and_then(|i| s.undo.get(i)).map(|snap| &snap.doc);+ let same_before = s.undo.len() >= entry.undo_len+ && match (top, &entry.undo_top) {+ (Some(a), Some(b)) => std::sync::Arc::ptr_eq(a, b),+ (None, None) => true,+ _ => false,+ };+ // The step that created the sketch was taken before it was open: its state is the entry's.+ let since = s.undo.get(entry.undo_len..).unwrap_or_default();+ same_before+ && since.iter().enumerate().all(|(i, snap)| snap.active_sketch == Some(id) || (i == 0 && std::sync::Arc::ptr_eq(&snap.doc, &entry.doc)))+ });+ let Some(entry) = current else {+ return Err(bad(cmd, "the undo history no longer leads back to where this sketch was opened: use Undo to go back"));+ };+ let created = entry.doc.feature(id).is_none();+ // As Undo does: the session evaluates the design it is given.+ s.doc = entry.doc;+ s.active_sketch = None;+ s.sketch_entry = None;+ s.selection.clear();+ s.revision += 1;+ Ok(json!({"sketch": id, "removed": created}))+}+fn finish_sketch(s: &mut Session, _p: &Value) -> Result<Value> {let id = s.active_sketch.take();+ s.sketch_entry = None;s.revision += 1;let profiles = id.and_then(|i| s.model.state().sketch(i).map(|ss| ss.profiles.len())).unwrap_or(0);Ok(json!({"sketch": id, "profiles": profiles}))diff --git a/crates/engine/src/cmd/sketch_ux_tests.rs b/crates/engine/src/cmd/sketch_ux_tests.rsindex da750c1935..27e59e9dd5 100644--- a/crates/engine/src/cmd/sketch_ux_tests.rs+++ b/crates/engine/src/cmd/sketch_ux_tests.rs@@ -1600,3 +1600,69 @@ fn budget_limited_cursor_progress_requests_a_frame_with_the_same_target() {}assert!(exercised, "exercise continuation after budget-limited progress");}++// ---------------------------------------------------------------------------------------------+// Cancel Sketch (#3838)++#[test]+fn cancel_removes_a_new_sketch_with_its_dimensions_and_undo_brings_it_back() {+ let mut s = Session::default();+ let before = s.doc.to_json();+ run(&mut s, "sketch.create", json!({"plane": "XY"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]}));+ run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 25}));+ let drawn = s.doc.to_json();+ let r = run(&mut s, "sketch.cancel", json!({}));+ assert_eq!(r["removed"], true);+ assert_eq!(s.active_sketch, None);+ assert_eq!(s.doc.to_json(), before, "the sketch and its dimension parameter are gone");+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(s.doc.to_json(), drawn);+ assert!(s.active_sketch.is_some(), "undo goes back into the sketch");+ run(&mut s, "edit.redo", json!({}));+ assert_eq!(s.doc.to_json(), before);+}++#[test]+fn cancel_puts_an_edited_sketch_back_as_it_was_opened() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Base"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [20, 10]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"distance": 5}));+ let opened = s.doc.to_json();+ let volume = |s: &mut Session| run(s, "inspect.measure", json!({}))["total"]["volume_mm3"].as_f64().unwrap();+ assert!((volume(&mut s) - 1000.0).abs() < 1e-6);+ run(&mut s, "sketch.edit", json!({"sketch": "Base"}));+ run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 40}));+ run(&mut s, "sketch.line", json!({"points": [[0, 20], [10, 30]]}));+ let r = run(&mut s, "sketch.cancel", json!({}));+ assert_eq!(r["removed"], false);+ assert_eq!(s.doc.to_json(), opened);+ assert!((volume(&mut s) - 1000.0).abs() < 1e-6, "the solid is built from the sketch as it was");++ // Finishing keeps the changes: there is nothing left to cancel.+ run(&mut s, "sketch.edit", json!({"sketch": "Base"}));+ run(&mut s, "sketch.dimension", json!({"entities": ["l1"], "value": 40}));+ run(&mut s, "sketch.finish", json!({}));+ assert!((volume(&mut s) - 2000.0).abs() < 1e-6);+ assert!(s.execute("sketch.cancel", &json!({})).is_err(), "not in a sketch");+}++#[test]+fn cancel_refuses_once_undo_has_gone_back_past_where_the_sketch_was_opened() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "S"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [10, 0]]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "sketch.edit", json!({"sketch": "S"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 5], [10, 5]]}));+ // Back past the edit: the first line's step is undone too, still inside the sketch.+ run(&mut s, "edit.undo", json!({}));+ run(&mut s, "edit.undo", json!({}));+ assert!(s.active_sketch.is_some());+ let before = s.doc.to_json();+ let e = s.execute("sketch.cancel", &json!({})).unwrap_err().to_string();+ assert!(e.contains("Undo"), "{e}");+ assert_eq!(s.doc.to_json(), before, "nothing changed");+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex da2d3f4b93..d17776a459 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -166,6 +166,16 @@ pub struct Snapshot {pub pending_moves: std::collections::BTreeMap<u64, solidcraft_doc::Mat>,}+/// Where the open sketch was entered (`sketch.create`, `sketch.edit`): the design before it and+/// the undo history then, so `sketch.cancel` can tell the entry still describes the history.+#[derive(Clone)]+pub(crate) struct SketchEntry {+ pub(crate) sketch: u64,+ pub(crate) doc: Arc<Document>,+ pub(crate) undo_len: usize,+ pub(crate) undo_top: Option<Arc<Document>>,+}+/// A copy of a session that evaluates commands ahead of it ([`Session::ahead`]).pub struct Ahead(Session);@@ -243,6 +253,8 @@ pub struct Session {pub redo: Vec<Snapshot>,/// Sketch feature being edited (sketch mode).pub active_sketch: Option<u64>,+ /// The design as it was when the open sketch was entered, for Cancel Sketch.+ pub(crate) sketch_entry: Option<SketchEntry>,pub selection: Vec<Sel>,pub path: Option<String>,/// One-shot display-only notification during doc.open, before authoritative evaluation.@@ -419,6 +431,7 @@ impl Session {undo: Vec::new(),redo: Vec::new(),active_sketch: None,+ sketch_entry: None,selection: Vec::new(),path: None,open_preview: None,@@ -998,6 +1011,7 @@ impl Session {undo: Vec::new(),redo: Vec::new(),active_sketch: self.active_sketch,+ sketch_entry: None,selection: self.selection.clone(),path: None,open_preview: None,diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rsindex 7ba10f0b8e..baabdc56dc 100644--- a/crates/ui-egui/src/context_menu.rs+++ b/crates/ui-egui/src/context_menu.rs@@ -489,6 +489,7 @@ fn viewport_items(app: &SolveApp) -> Vec<Item> {v.push(cmd(app, "sketch.offset", "Offset"));v.push(Item::sep());v.push(act("ui.finishSketch", "Finish Sketch", "finish"));+ v.push(act("ui.cancelSketch", "Cancel Sketch", "sketch_cancel"));v.push(Item::sep());v.push(cmd(app, "edit.undo", "Undo").on(!app.session.undo.is_empty()));v.push(cmd(app, "edit.redo", "Redo").on(!app.session.redo.is_empty()));@@ -1021,6 +1022,7 @@ 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.cancelSketch" => app.cancel_sketch(),"ui.relinkSource" => {if let Some(component) = id_of(&p, "component") {crate::linked_source::start(app, component);diff --git a/crates/ui-egui/src/i18n_ui_tests.rs b/crates/ui-egui/src/i18n_ui_tests.rsindex 952d90d246..2f05ab72ab 100644--- a/crates/ui-egui/src/i18n_ui_tests.rs+++ b/crates/ui-egui/src/i18n_ui_tests.rs@@ -243,8 +243,10 @@ fn finish_exit_label_and_its_button_are_centred() {h.app.run("sketch.create", json!({"plane":"xy"})).unwrap();h.frames(2);let label = scenario::handles("panel:SKETCH:FINISH SKETCH")[0].1;- let button = scenario::handles("button:sketch.finish")[0].1;- assert!((label.x - button.x).abs() < 1.0, "the only button sits centred over its label: {label:?} {button:?}");+ // Finish and Cancel Sketch (#3838) sit side by side, the pair centred over the label.+ let finish = scenario::handles("button:sketch.finish")[0].1;+ let cancel = scenario::handles("button:sketch.cancel")[0].1;+ assert!(finish.x < label.x && label.x < cancel.x, "the label is centred under the pair, Finish first: {label:?} {finish:?} {cancel:?}");let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1600.0, 1000.0));let mut out =diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex 7e61ba57db..2595a24d5d 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -1037,6 +1037,10 @@ impl SolveApp {self.finish_sketch();return;}+ if id == "sketch.cancel" {+ self.cancel_sketch();+ return;+ }// Press Pull: edges get a fillet, faces and profiles an extrude.if id == "solid.press_pull" {let edges = self.session.selection.iter().any(|s| matches!(s, solidcraft_engine::Sel::Edge { .. }));@@ -1184,13 +1188,25 @@ impl SolveApp {/// Finish the active sketch: stop editing and restore the history marker Edit Sketch moved./// The camera stays where it is, however the sketch is left.pub fn finish_sketch(&mut self) {+ self.leave_sketch("sketch.finish");+ }++ /// Cancel Sketch (#3838): leave the sketch without its changes. When the command refuses (the+ /// undo history no longer leads back to where the sketch was opened), the sketch stays open.+ pub fn cancel_sketch(&mut self) {+ self.leave_sketch("sketch.cancel");+ }++ fn leave_sketch(&mut self, command: &str) {sketch_text_move::cancel_drag(self);if sketch_text::editing(self) || self.dialog.as_ref().is_some_and(|d| matches!(d.kind, dialogs::Kind::TextMove(_))) {dialogs::cancel(self);}dim_view::cancel();self.tool = None;- let _ = self.run("sketch.finish", json!({}));+ if self.run(command, json!({})).is_err() && command != "sketch.finish" {+ return;+ }if let Some(marker) = self.pre_sketch_marker.take() {self.restore_marker(marker);}diff --git a/crates/ui-egui/src/workspace.rs b/crates/ui-egui/src/workspace.rsindex a2a4ae0465..00c07bc8c0 100644--- a/crates/ui-egui/src/workspace.rs+++ b/crates/ui-egui/src/workspace.rs@@ -246,7 +246,7 @@ pub const SECTIONS: &[Section] = &[},// Sketch dimensions are driven by parameters, so they are one click away while sketching.Section { tab: "SKETCH", panel: "CONFIGURE", promoted: 2, ids: CONFIGURE },- Section { tab: "SKETCH", panel: "FINISH SKETCH", promoted: 1, ids: &["sketch.finish"] },+ Section { tab: "SKETCH", panel: "FINISH SKETCH", promoted: 2, ids: &["sketch.finish", "sketch.cancel"] },// New Sketch leads the tab, as on MODEL: a sheet part starts from a sketch (#3250).Section { tab: "SHEET METAL", panel: "SKETCH", promoted: 1, ids: &["sketch.create"] },Section {@@ -301,6 +301,7 @@ pub const RIBBON_LABELS: &[(&str, &str)] = &[("sheet.export_dxf", "Export DXF"),("sheet.flat_pattern", "Flat Pattern"),("sheet.manage_rules", "Sheet Rules"),+ ("sketch.cancel", "Cancel"),("sketch.circle.center", "Circle"),("sketch.constraint.coincident", "Coincident"),("sketch.constraint.horizontal_vertical", "Horiz./Vert."),diff --git a/crates/ui-egui/tests/scenarios/sketch_cancel.json b/crates/ui-egui/tests/scenarios/sketch_cancel.jsonnew file mode 100644index 0000000000..28a75c6827--- /dev/null+++ b/crates/ui-egui/tests/scenarios/sketch_cancel.json@@ -0,0 +1,16 @@+[+ {"note": "#3838: Cancel Sketch leaves a sketch without keeping its changes. A new sketch is removed with what was drawn in it, and Undo goes back into it."},+ {"start": "sketch.create"},+ {"click": {"plane": "XY"}},+ {"expect": {"sketching": true}},+ {"start": "sketch.line"},+ {"click": {"sketch": [0, 0]}},+ {"click": {"sketch": [30, 10]}},+ {"key": "Escape"},+ {"expect": {"sketch_curves": {"own": 1}}},+ {"start": "sketch.cancel"},+ {"expect": {"sketching": false, "errors": 0}},+ {"expect": {"query": {"command": "document.inspect", "path": ["timeline"], "value": []}}},+ {"call": "engine.execute", "params": {"command": "edit.undo", "params": {}}},+ {"expect": {"sketching": true, "sketch_curves": {"own": 1}}}+]diff --git a/docs/book/src/guide/sketching.md b/docs/book/src/guide/sketching.mdindex 2b8b488c1d..014b4d0834 100644--- a/docs/book/src/guide/sketching.md+++ b/docs/book/src/guide/sketching.md@@ -3,7 +3,9 @@A sketch lies on a plane: an origin plane, a construction plane or a planar face. Start one with**Create Sketch** (`sketch.create`) and click a plane, or pick a face first. Right-clicking aplane, in the view or on its browser row, offers **Create Sketch** on that plane too.-**Finish Sketch** returns to the model.+**Finish Sketch** returns to the model. **Cancel Sketch** (`sketch.cancel`) returns without+keeping what changed since the sketch was created or opened for editing: a new sketch is removed,+an edited one goes back to how it was, as one step that Undo brings back.In scripts, `XY`, `XZ`, `YZ` and their `Top`, `Front`, `Right` aliases name origin planes.These names are reserved: a construction plane cannot be created with or renamed to one