SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Feature editor: allow visibility changes while editing (#8810) (#8827)
Colin Faulkingham443e5cd59da7
diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rsindex d6a30c24ba..4ecc83297d 100644--- a/crates/engine/src/cmd/browser.rs+++ b/crates/engine/src/cmd/browser.rs@@ -290,7 +290,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {s.visibility.hidden_folders.push(k.clone());}}- s.revision += 1;+ s.refresh_display();return Ok(json!({"visible":visible,"changed":keys.len(),"visibility":s.visibility}));}if let Some(value) = p.get("paths") {@@ -341,7 +341,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {root_bodies.extend(ancestor_bodies);s.visibility.hidden_occurrences = hidden;s.visibility.hidden_bodies = root_bodies;- s.revision += 1;+ s.refresh_display();return Ok(json!({"visible":true,"isolated":paths,"visibility":s.visibility}));}for path in &paths {@@ -350,7 +350,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {s.visibility.hidden_occurrences.push(path.clone());}}- s.revision += 1;+ s.refresh_display();return Ok(json!({"visible":visible,"changed":paths.len(),"visibility":s.visibility}));}let items: Vec<Shown> = match (str_(p, "folder"), p.get("items")) {@@ -462,7 +462,7 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {}}}- s.revision += 1;+ s.refresh_display();Ok(json!({ "visible": visible, "changed": items.len(), "visibility": s.visibility }))}diff --git a/crates/engine/src/computed_commands_tests.rs b/crates/engine/src/computed_commands_tests.rsindex b5efde92af..5e6d6c0e13 100644--- a/crates/engine/src/computed_commands_tests.rs+++ b/crates/engine/src/computed_commands_tests.rs@@ -87,3 +87,167 @@ fn an_editor_cannot_take_a_pinned_model_from_another_document() {assert!(session.scratch().compute_editor_commands(&[], &source, Session::default()).is_err());assert!(Arc::ptr_eq(&document, &session.doc));}++fn extrusion_editor() -> (Session, Session, Session, Vec<(String, serde_json::Value)>) {+ let mut session = Session::default();+ session.execute("solid.box", &json!({"corner":[-10,0,0],"length":2,"width":3,"height":4,"body_name":"Other"})).unwrap();+ let sketch = session.execute("sketch.create", &json!({"plane":"XY"})).unwrap()["sketch"].as_u64().unwrap();+ session.execute("sketch.rectangle.two_point", &json!({"p0":[0,0],"p1":[30,20]})).unwrap();+ session.execute("sketch.finish", &json!({})).unwrap();+ let feature = session.execute("solid.extrude", &json!({"distance":10,"operation":"new"})).unwrap()["feature"].as_u64().unwrap();+ let original = session.scratch();+ // The UI's temporary rollback does not create an undo step.+ let undo = std::mem::take(&mut session.undo);+ session.execute("timeline.roll_to", &json!({"position":2})).unwrap();+ session.undo = undo;+ let source = session.scratch();+ let commands = vec![(+ "timeline.redefine".into(),+ json!({"feature":feature,"command":"solid.extrude","params":{"sketch":sketch,"profiles":"all","distance":20,"operation":"new"}}),+ )];+ (session, source, original, commands)+}++fn assert_editor_volume(session: &mut Session, volume: f64) {+ assert_eq!(session.doc.marker, None, "visibility history must not restore the editor's temporary rollback");+ let actual = session.execute("inspect.measure", &json!({})).unwrap()["total"]["volume_mm3"].as_f64().unwrap();+ assert!((actual - volume).abs() < 1e-6, "expected {volume}, got {actual}");+}++#[test]+fn editor_visibility_changes_allow_apply_and_preserve_separate_undo_steps() {+ for params in [+ json!({"items":["Other"],"visible":false}),+ json!({"items":["XY"],"visible":false}),+ json!({"items":["Sketch1"],"visible":false}),+ json!({"tree_folders":["c0/bodies"],"visible":false}),+ ] {+ let (mut session, source, original, commands) = extrusion_editor();+ let shown = session.visibility.clone();+ let history = session.undo.len();+ session.execute("browser.visibility", ¶ms).unwrap();+ let hidden = session.visibility.clone();+ assert_ne!(hidden, shown, "{params}");+ assert!(Arc::ptr_eq(&source.doc, &session.doc));+ let prepared = session.scratch().compute_editor_commands(&commands, &source, original).unwrap();+ session.accept_commands(prepared).unwrap();+ assert_eq!(session.undo.len(), history + 2, "hide and edit are separate undo steps");+ assert_eq!(session.visibility, hidden);+ assert_editor_volume(&mut session, 12024.0);+ session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(session.visibility, hidden);+ assert_editor_volume(&mut session, 6024.0);+ session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(session.visibility, shown);+ assert_editor_volume(&mut session, 6024.0);+ session.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(session.visibility, hidden);+ assert_editor_volume(&mut session, 6024.0);+ session.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(session.visibility, hidden);+ assert_editor_volume(&mut session, 12024.0);+ }+}++#[test]+fn editor_visibility_changes_allow_cancel_and_keep_undo_and_redo_at_the_original_marker() {+ for undo_hide in [false, true] {+ let (mut session, source, original, _) = extrusion_editor();+ let shown = session.visibility.clone();+ session.execute("browser.visibility", &json!({"items":["Other","XY"],"visible":false})).unwrap();+ let hidden = session.visibility.clone();+ if undo_hide {+ session.execute("edit.undo", &json!({})).unwrap();+ }+ let history = (session.undo.len(), session.redo.len());+ let live = session.visibility.clone();+ *session.model.cache.lock().unwrap() = Default::default();+ let evaluations = session.evaluations;+ session.restore_editor(&source, original).unwrap();+ assert_eq!(session.evaluations, evaluations, "Cancel reuses the pinned model");+ assert_eq!(session.visibility, live);+ assert_eq!((session.undo.len(), session.redo.len()), history);+ assert_editor_volume(&mut session, 6024.0);+ if undo_hide {+ session.execute("edit.redo", &json!({})).unwrap();+ assert_eq!(session.visibility, hidden);+ } else {+ session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(session.visibility, shown);+ }+ assert_editor_volume(&mut session, 6024.0);+ }+}++#[test]+fn visibility_changes_while_an_editor_computes_preserve_the_latest_view() {+ let (mut session, source, original, commands) = extrusion_editor();+ let prepared = session.scratch().compute_editor_commands(&commands, &source, original).unwrap();+ session.execute("browser.visibility", &json!({"items":["Other","XY"],"visible":false})).unwrap();+ let visibility = session.visibility.clone();+ assert!(prepared.is_current(&session));+ session.accept_commands(prepared).unwrap();+ assert_eq!(session.visibility, visibility);+ assert_editor_volume(&mut session, 12024.0);+ session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(session.visibility, visibility);+ assert_editor_volume(&mut session, 6024.0);+ session.execute("edit.undo", &json!({})).unwrap();+ assert_editor_volume(&mut session, 6024.0);+}++#[test]+fn visibility_does_not_make_a_stale_editor_current() {+ for change in 0..7 {+ let (mut session, source, original, commands) = extrusion_editor();+ match change {+ 0 => session.revision += 1,+ 1 => session.active_sketch = Some(2),+ 2 => session.active_component = 17,+ 3 => session.active_occurrence_path = Some(vec![1]),+ 4 => {+ session.execute("solid.box", &json!({"length":1,"width":1,"height":1})).unwrap();+ }+ 5 => {+ session.pending_moves.insert(1, solidcraft_doc::IDENTITY);+ }+ _ => session = Session::default(),+ }+ session.execute("browser.visibility", &json!({"items":["XY"],"visible":false})).unwrap();+ let doc = session.doc.clone();+ let visibility = session.visibility.clone();+ assert!(session.scratch().compute_editor_commands(&commands, &source, original.scratch()).is_err(), "change {change}");+ assert!(session.restore_editor(&source, original).is_err(), "change {change}");+ assert!(Arc::ptr_eq(&session.doc, &doc));+ assert_eq!(session.visibility, visibility);+ }+}++#[test]+fn accepting_commands_keeps_a_joint_shown_while_the_worker_ran() {+ let mut session = Session::default();+ let part = session.execute("component.create", &json!({"name":"Part","activate":false})).unwrap();+ let occurrence = part["occurrence"].as_u64().unwrap();+ let joint = session.execute("joint.as_built", &json!({"type":"revolute","a":0,"b":occurrence})).unwrap()["joint"].as_u64().unwrap();+ session.execute("browser.visibility", &json!({"joints":[joint],"visible":false})).unwrap();+ let prepared = session.scratch().compute_commands(&commands(), None).unwrap();+ session.execute("browser.visibility", &json!({"joints":[joint],"visible":true})).unwrap();+ session.execute("browser.visibility", &json!({"paths":[[occurrence]],"visible":false})).unwrap();+ let visibility = session.visibility.clone();+ session.accept_commands(prepared).unwrap();+ assert_eq!(session.visibility, visibility, "the worker's old joint hide must not be merged back");+ session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(session.visibility, visibility, "undoing geometry keeps both concurrent visibility changes");+}++#[test]+fn cancelling_an_editor_with_visibility_changes_restores_an_existing_history_marker() {+ let (mut session, source, mut original, _) = extrusion_editor();+ original.execute("timeline.roll_to", &json!({"position":1})).unwrap();+ session.execute("browser.visibility", &json!({"items":["XY"],"visible":false})).unwrap();+ session.restore_editor(&source, original).unwrap();+ assert_eq!(session.doc.marker, Some(1));+ session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(session.doc.marker, Some(1));+ assert!(session.visibility.hidden_origin.is_empty());+}diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex c8f4311a61..296bd36308 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -294,6 +294,7 @@ pub struct ComputedCommands {source: Session,computed: Session,steps: Vec<ComputedCommand>,+ editor_original: Option<Arc<Document>>,}struct ComputedCommand {@@ -360,6 +361,9 @@ pub struct Session {pub log: Vec<String>,/// Increments on every document change (views use it to refresh).pub revision: u64,+ /// Revision increments caused only by visibility. Comparing both counters proves that+ /// every intervening increment left an editor's document and model untouched.+ visibility_revision: u64,/// This open design's id for programs that follow it (`document.revision`, #6646): kept/// while it stays open, through saves and renames; another for each design started or opened.pub document_id: String,@@ -568,6 +572,7 @@ impl Session {open_preview: None,log: Vec::new(),revision: 1,+ visibility_revision: 0,document_id: cmd::inspect::new_document_id(),followed: None,auto_project: true,@@ -1069,6 +1074,7 @@ impl Session {/// moves (the visibility caches are keyed on it) and the viewport redraws.pub(crate) fn refresh_display(&mut self) {self.revision += 1;+ self.visibility_revision += 1;}/// Show the sketch a live frame changed, leaving the features after it as they were last@@ -1409,6 +1415,7 @@ impl Session {saved: self.saved.clone(),log: Vec::new(),revision: self.revision,+ visibility_revision: self.visibility_revision,document_id: self.document_id.clone(),followed: None,auto_project: self.auto_project,@@ -1477,6 +1484,7 @@ impl Session {marker: Option<Option<usize>>,original: Option<Session>,) -> Result<ComputedCommands> {+ let editor_original = original.as_ref().map(|session| session.doc.clone());let mut computed = self.scratch();let mut steps = Vec::new();if let Some(marker) = marker {@@ -1513,15 +1521,26 @@ impl Session {}// What the source was primed with stays out of the session that is adopted (#6901).computed.unprime();- Ok(ComputedCommands { source: self, computed, steps })+ Ok(ComputedCommands { source: self, computed, steps, editor_original })}/// Adopt evaluated commands only if their document and authoring context are still current./// No model evaluation occurs here. Rejected or cancelled work never enters the journal.- pub fn accept_commands(&mut self, prepared: ComputedCommands) -> Result<Vec<(String, Value)>> {+ pub fn accept_commands(&mut self, mut prepared: ComputedCommands) -> Result<Vec<(String, Value)>> {if !prepared.is_current(self) {return Err(EngineError::Other("the design changed while the feature was computing".into()));}+ if let Some(original) = &prepared.editor_original {+ self.restore_editor_history(&prepared.source.doc, original);+ }+ // Visibility may have changed while the worker ran. Undoing its first command must+ // restore that current view, including sketches, folders and joint glyphs.+ if let Some(before) = prepared.computed.undo.first_mut() {+ before.visibility.clone_from(&self.visibility);+ }+ // Only joints newly hidden by the computation (e.g. an import's rigid group) join+ // the live view. A joint shown meanwhile must not inherit the worker's old hide.+ prepared.computed.visibility.hidden_joints.retain(|joint| !prepared.source.visibility.hidden_joints.contains(joint));for step in &prepared.steps {crash::accepted_command(self, &step.before, &step.after, &step.id, &step.params, step.changed);}@@ -1532,7 +1551,10 @@ impl Session {fn same_document_context(&self, source: &Session) -> bool {Arc::ptr_eq(&self.doc, &source.doc)- && self.revision == source.revision+ && self+ .revision+ .checked_sub(source.revision)+ .is_some_and(|delta| self.visibility_revision.checked_sub(source.visibility_revision) == Some(delta))&& self.active_sketch == source.active_sketch&& self.active_component == source.active_component&& self.active_occurrence_path == source.active_occurrence_path@@ -1547,6 +1569,7 @@ impl Session {}let params = original.doc.marker.map(|position| serde_json::json!({"position":position})).unwrap_or_else(|| serde_json::json!({}));crash::accepted_command(self, &self.doc, &original.doc, "timeline.roll_to", ¶ms, !Arc::ptr_eq(&self.doc, &original.doc));+ self.restore_editor_history(&source.doc, &original.doc);let undo = std::mem::take(&mut self.undo);let redo = std::mem::take(&mut self.redo);let selection = std::mem::take(&mut self.selection);@@ -1558,6 +1581,16 @@ impl Session {Ok(())}+ /// Hide/show steps taken in an editor belong to the complete design, not its temporary+ /// rollback. Keep each step's visibility and ordering, on both sides of the history.+ fn restore_editor_history(&mut self, source: &Arc<Document>, original: &Arc<Document>) {+ for snapshot in self.undo.iter_mut().chain(&mut self.redo) {+ if Arc::ptr_eq(&snapshot.doc, source) {+ snapshot.doc = original.clone();+ }+ }+ }+/// Refresh UI caches when adopting a session or switching tabs, without discarding its/// already prepared world-space geometry. This does not change the document.pub fn invalidate_view(&mut self, previous_revision: u64) {diff --git a/crates/ui-egui/src/apply_off_thread_tests.rs b/crates/ui-egui/src/apply_off_thread_tests.rsindex 489bf4261c..4ac5dd4f03 100644--- a/crates/ui-egui/src/apply_off_thread_tests.rs+++ b/crates/ui-egui/src/apply_off_thread_tests.rs@@ -371,6 +371,50 @@ fn cancelling_a_stale_editor_preserves_the_newer_document() {assert!(h.app.status.as_ref().is_some_and(|(_, _, error)| *error));}+#[test]+fn hiding_an_origin_plane_during_feature_edit_allows_ok_and_cancel() {+ for apply in [false, true] {+ let mut h = Harness::new();+ h.app.home.open = false;+ for (command, params) in [+ ("sketch.create", json!({"plane":"XY"})),+ ("sketch.rectangle.two_point", json!({"p0":[0,0],"p1":[30,20]})),+ ("sketch.finish", json!({})),+ ("solid.extrude", json!({"distance":10,"operation":"new"})),+ ] {+ h.app.run(command, params).unwrap();+ }+ h.call("ui.editFeature", json!({"feature":"Extrude1"}));+ h.frames(2);+ h.step(&json!({"click":{"handle":"dialog:Distance"}})).unwrap();+ h.step(&json!({"key":"A","cmd":true})).unwrap();+ h.step(&json!({"text":"20 mm"})).unwrap();+ h.step(&json!({"click":{"handle":"fold:Origin"}})).unwrap();+ h.step(&json!({"click":{"handle":"eye:XY"}})).unwrap();+ assert!(h.app.session.visibility.hidden_origin.iter().any(|name| name == "XY"));+ if apply {+ h.step(&json!({"click":{"handle":"dialog:OK"}})).unwrap();+ until_applied(&mut h);+ } else {+ h.step(&json!({"key":"Escape"})).unwrap();+ }+ assert!(h.app.dialog.is_none(), "{:?}", h.app.dialog.as_ref().and_then(|dialog| dialog.error.as_ref()));+ assert!(h.app.status.as_ref().is_none_or(|(_, _, error)| !error), "{:?}", h.app.status);+ assert_eq!(h.app.session.doc.marker, None);+ assert!(h.app.session.visibility.hidden_origin.iter().any(|name| name == "XY"));+ h.step(&json!({"expect":{"bodies":1,"volume":if apply {12000} else {6000}}})).unwrap();+ if apply {+ h.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(h.app.session.doc.marker, None);+ assert!(h.app.session.visibility.hidden_origin.iter().any(|name| name == "XY"));+ }+ h.app.run("edit.undo", json!({})).unwrap();+ assert_eq!(h.app.session.doc.marker, None, "undoing the eye click keeps the complete timeline");+ assert!(!h.app.session.visibility.hidden_origin.iter().any(|name| name == "XY"));+ h.step(&json!({"expect":{"bodies":1,"volume":6000}})).unwrap();+ }+}+#[test]fn a_worker_error_then_cancel_preserves_original_world_history_redo_and_selection() {let (mut h, target) = cut_chain();