SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Preserve plastic rules and hidden bodies through renames (#4421) (#4425)
Colin Faulkinghamcd66495e14f4
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rsindex 4f92f66daf..f13025bb44 100644--- a/crates/doc/src/document.rs+++ b/crates/doc/src/document.rs@@ -2869,7 +2869,7 @@ impl Document {}/// Rename body `old` to `new` where the design keeps things by body name outside its- /// features: materials, appearances, configuration columns, offsets, components and the+ /// features: materials, appearances, plastic rules, configuration columns, offsets, components and the/// browser's groups and order. (The features are the rename command's to change.)////// A name the design numbered (`Body1`) is not used again after the rename: the design's@@ -2882,6 +2882,9 @@ impl Document {if let Some(m) = self.materials.remove(old) {self.materials.insert(new.to_string(), m);}+ if let Some(rule) = self.plastic.assigned.remove(old) {+ self.plastic.assigned.insert(new.to_string(), rule);+ }if let Some(c) = self.appearances.bodies.remove(old) {self.appearances.bodies.insert(new.to_string(), c);}diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rsindex 42a47c168f..1bf8049085 100644--- a/crates/engine/src/cmd/browser.rs+++ b/crates/engine/src/cmd/browser.rs@@ -367,7 +367,10 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {}let v = &mut s.visibility;match str_(p, "folder") {- Some("bodies" | "all") if visible => v.hidden_occurrences.clear(),+ Some("bodies" | "all") if visible => {+ v.hidden_bodies.clear();+ v.hidden_occurrences.clear();+ }// Showing a whole folder shows the folder too.Some("origin") if visible => v.origin_hidden = Some(false),_ => {}@@ -760,6 +763,7 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {if name == old {return Ok(json!({"body": old, "name": name}));}+ let previous = s.doc.clone();let st = s.model.state();let b = st.body(&old).ok_or_else(|| bad(cmd, format!("no body `{old}`")))?;if st.body(name).is_some() {@@ -878,10 +882,10 @@ fn rename_body(s: &mut Session, p: &Value) -> Result<Value> {return Err(bad(cmd, e));}d.rename_body_keys(&old, name);- let v = &mut s.visibility;- for b in v.hidden_bodies.iter_mut().chain(v.locked_bodies.iter_mut()).filter(|b| **b == old) {+ for b in s.visibility.locked_bodies.iter_mut().filter(|b| **b == old) {*b = name.to_string();}+ s.remember_body_rename(&previous, &old, name);Ok(json!({"body": old, "name": name}))}@@ -1011,6 +1015,88 @@ mod tests {s.model.state().bodies.iter().map(|b| b.name.clone()).collect()}+ #[test]+ fn body_rename_preserves_plastic_rules_and_current_visibility_through_history() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Plate"}));+ run(&mut s, "plastic.manage_rules", json!({"name": "Housing", "draft": "3 deg"}));+ run(&mut s, "plastic.assign_rule", json!({"bodies": ["Plate"], "rule": "Housing"}));+ run(&mut s, "browser.visibility", json!({"items": ["Plate"], "visible": false}));+ run(&mut s, "body.rename", json!({"body": "Plate", "name": "Base"}));+ assert_eq!(run(&mut s, "plastic.rules", json!({}))["assigned"], json!({"Base": "Housing"}));+ assert!(!s.body_visible("Base"));+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(run(&mut s, "plastic.rules", json!({}))["assigned"], json!({"Plate": "Housing"}));+ assert!(!s.body_visible("Plate"), "undo must keep the body hidden");+ run(&mut s, "edit.redo", json!({}));+ assert!(!s.body_visible("Base"));+ // Showing a body is its own undo step; the rename keeps the correct hidden name on+ // either side of that step, and neither operation loses the assigned rule.+ run(&mut s, "browser.visibility", json!({"items": ["Base"], "visible": true}));+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(names(&s), ["Base"]);+ assert!(!s.body_visible("Base"));+ run(&mut s, "edit.undo", json!({}));+ assert_eq!(names(&s), ["Plate"]);+ assert!(!s.body_visible("Plate"));+ run(&mut s, "edit.redo", json!({}));+ assert!(!s.body_visible("Base"));+ run(&mut s, "edit.redo", json!({}));+ assert!(s.body_visible("Base"));+ run(&mut s, "browser.visibility", json!({"items": ["Base"], "visible": false}));+ let mut saved = (*s.doc).clone();+ saved.visibility = s.visibility.clone();+ let reopened = Session::new(serde_json::from_str(&serde_json::to_string(&saved).unwrap()).unwrap());+ assert_eq!(reopened.doc.plastic.assigned.get("Base").map(String::as_str), Some("Housing"));+ assert!(!reopened.body_visible("Base"));+ }++ #[test]+ fn body_rename_undo_keeps_hidden_bodies_with_downstream_users_hidden() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Peg"}));+ run(&mut s, "solid.move", json!({"bodies": ["Peg"], "translate": [0, 0, 5]}));+ run(&mut s, "browser.visibility", json!({"items": ["Peg"], "visible": false}));+ run(&mut s, "body.rename", json!({"body": "Peg", "name": "Stud"}));+ run(&mut s, "edit.undo", json!({}));+ assert!(!s.body_visible("Peg"));+ assert_eq!(s.visibility.hidden_bodies, ["Peg"]);+ run(&mut s, "edit.redo", json!({}));+ assert!(!s.body_visible("Stud"));+ }++ #[test]+ fn show_all_bodies_clears_stale_hidden_names() {+ for folder in ["bodies", "all"] {+ let mut s = Session::default();+ s.visibility.hidden_bodies.push("Old body name".into());+ run(&mut s, "browser.visibility", json!({"folder": folder, "visible": true}));+ assert!(s.visibility.hidden_bodies.is_empty(), "{folder}");+ }+ }++ #[test]+ fn computed_body_rename_keeps_the_latest_visibility_and_undo_mapping() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Peg"}));+ run(&mut s, "solid.move", json!({"bodies": ["Peg"], "translate": [0, 0, 5]}));+ let mut computed = s.scratch();+ run(&mut computed, "body.rename", json!({"body": "Peg", "name": "Stud"}));+ // The user hides the body while the rename is being evaluated.+ run(&mut s, "browser.visibility", json!({"items": ["Peg"], "visible": false}));+ s.accept_computed(computed);+ assert!(!s.body_visible("Stud"));+ assert_eq!(s.visibility.hidden_bodies, ["Stud"]);+ run(&mut s, "edit.undo", json!({}));+ assert!(!s.body_visible("Peg"));+ run(&mut s, "edit.undo", json!({}));+ assert!(s.body_visible("Peg"), "the concurrent hide remains its own undo step");+ run(&mut s, "edit.redo", json!({}));+ assert!(!s.body_visible("Peg"));+ run(&mut s, "edit.redo", json!({}));+ assert!(!s.body_visible("Stud"));+ }+#[test]fn renamed_body_keeps_its_users() {let mut s = Session::default();diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rsindex a5d57816b3..122922f9aa 100644--- a/crates/engine/src/cmd/occurrence_tests.rs+++ b/crates/engine/src/cmd/occurrence_tests.rs@@ -52,6 +52,55 @@ fn component_create_rejects_unknown_keys_and_accepts_documented_keys() {assert_eq!(s.active_occurrence_path, Some(vec![occurrence]));}+#[test]+fn body_and_component_renames_keep_hidden_copies_through_history() {+ let mut s = Session::default();+ let (component, first) = created(&mut s, "Knob");+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Knob"}));+ let second = run(&mut s, "occurrence.copy", json!({"component": component, "translate": [20, 0, 0]}))["occurrence"].as_u64().unwrap();+ let name = |s: &Session, path: &[u64]| s.occurrence_placement(path).unwrap().bodies[0].world.clone();+ let hidden = name(&s, &[second]);+ run(&mut s, "browser.visibility", json!({"items": [hidden], "visible": false}));+ for (command, params) in [+ ("body.rename", json!({"body": "Knob", "name": "Grip"})),+ ("component.rename", json!({"component": component, "name": "Dial"})),+ ("edit.undo", json!({})),+ ("edit.undo", json!({})),+ ("edit.redo", json!({})),+ ("edit.redo", json!({})),+ ] {+ run(&mut s, command, params);+ assert!(s.body_visible(&name(&s, &[first])), "{command}: the first copy stays visible");+ assert!(!s.body_visible(&name(&s, &[second])), "{command}: the hidden copy stays hidden");+ assert_eq!(s.visibility.hidden_bodies, [name(&s, &[second])], "no stale names after {command}");+ }+}++#[test]+fn renaming_a_parent_preserves_hidden_nested_copies_with_ambiguous_labels() {+ let mut s = Session::default();+ let (parent, first_parent) = created(&mut s, "Assembly");+ let (_, child) = created(&mut s, "Knob");+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Knob"}));+ let second_parent = run(&mut s, "occurrence.copy", json!({"component": parent, "translate": [20, 0, 0]}))["occurrence"].as_u64().unwrap();+ let name = |s: &Session, path: &[u64]| s.occurrence_placement(path).unwrap().bodies[0].world.clone();+ let hidden = name(&s, &[second_parent, child]);+ run(&mut s, "browser.visibility", json!({"items": [hidden], "visible": false}));+ for (command, params) in [+ ("component.rename", json!({"component": parent, "name": "Assembly/Other"})),+ ("body.rename", json!({"body": "Knob", "name": "Grip (@occ[custom])"})),+ ("edit.undo", json!({})),+ ("edit.undo", json!({})),+ ("edit.redo", json!({})),+ ("edit.redo", json!({})),+ ] {+ run(&mut s, command, params);+ assert!(s.body_visible(&name(&s, &[first_parent, child])), "{command}");+ assert!(!s.body_visible(&name(&s, &[second_parent, child])), "{command}");+ assert_eq!(s.visibility.hidden_bodies, [name(&s, &[second_parent, child])]);+ }+}+#[test]fn instance_copy_uses_selected_source_transform() {let mut s = Session::default();diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex 2f6cdfe3ed..1c4c2133f7 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -167,11 +167,13 @@ pub enum Sel {}/// A body rename between two designs (see `Session::body_renames`).+#[derive(Clone)]struct BodyRename {before: std::sync::Weak<Document>,after: std::sync::Weak<Document>,old: String,new: String,+ names_only: bool,}/// One undo step.@@ -772,7 +774,10 @@ impl Session {fn refresh_from(&mut self, previous: &Arc<Document>) {self.follow_plane_renames(previous);self.follow_axis_point_renames(previous);- if let Some((old, new)) = self.body_rename(previous)+ let rename = self.body_rename(previous);+ self.remap_hidden_bodies(previous, &self.model.state(), rename.as_ref().map(|(old, new, _)| (old.as_str(), new.as_str())));+ if let Some((old, new, names_only)) = rename+ && names_only&& self.model.rename_body(&self.doc, &old, &new){self.revision += 1;@@ -812,29 +817,48 @@ impl Session {}}- /// The body rename that turned `previous` into the design (old name, new name), if that is- /// the whole change: one this session made (either way round), else one the designs show.- fn body_rename(&mut self, previous: &Arc<Document>) -> Option<(String, String)> {+ /// The body rename that turned `previous` into the design (old name, new name, whether+ /// only names changed): one this session made (either way round), else one the designs show.+ fn body_rename(&mut self, previous: &Arc<Document>) -> Option<(String, String, bool)> {let holds = |w: &std::sync::Weak<Document>, d: &Arc<Document>| w.upgrade().is_some_and(|x| Arc::ptr_eq(&x, d));self.body_renames.retain(|r| r.before.strong_count() > 0 && r.after.strong_count() > 0);for r in &self.body_renames {if holds(&r.before, previous) && holds(&r.after, &self.doc) {- return Some((r.old.clone(), r.new.clone()));+ return Some((r.old.clone(), r.new.clone(), r.names_only));}if holds(&r.after, previous) && holds(&r.before, &self.doc) {- return Some((r.new.clone(), r.old.clone()));+ return Some((r.new.clone(), r.old.clone(), r.names_only));}}- let model = &self.model;- let made = |id: u64| -> Vec<String> {- model.result(id).map(|r| r.state.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect()).unwrap_or_default()- };- let (old, new) = self.doc.body_rename_from(previous, made)?;- self.body_renames.push(BodyRename { before: Arc::downgrade(previous), after: Arc::downgrade(&self.doc), old: old.clone(), new: new.clone() });+ let (old, new) = self.inferred_body_rename(previous)?;+ self.record_body_rename(previous, &old, &new, true);+ Some((old, new, true))+ }++ fn inferred_body_rename(&self, previous: &Document) -> Option<(String, String)> {+ self.doc.body_rename_from(previous, |id| {+ self.model.result(id).map(|r| r.state.bodies.iter().filter(|b| b.feature == id).map(|b| b.name.clone()).collect()).unwrap_or_default()+ })+ }++ /// Remember explicit renames too: features that refer to the body also change their+ /// parameters, so the document-only fast-path proof may not recognize their undo/redo.+ fn remember_body_rename(&mut self, previous: &Arc<Document>, old: &str, new: &str) {+ let names_only = self.inferred_body_rename(previous).is_some();+ self.record_body_rename(previous, old, new, names_only);+ }++ fn record_body_rename(&mut self, previous: &Arc<Document>, old: &str, new: &str, names_only: bool) {+ self.body_renames.push(BodyRename {+ before: Arc::downgrade(previous),+ after: Arc::downgrade(&self.doc),+ old: old.into(),+ new: new.into(),+ names_only,+ });if self.body_renames.len() > MAX_UNDO {self.body_renames.remove(0);}- Some((old, new))}/// Only persistent render intent, or only part properties, changed. Never evaluate or clear@@ -1167,7 +1191,7 @@ impl Session {removed_later_cache: Default::default(),occurrence_bodies_cache: Default::default(),clearance_cache: self.clearance_cache.clone(),- body_renames: Vec::new(),+ body_renames: self.body_renames.clone(),contact_meshes: self.contact_meshes.clone(),clipboard: self.clipboard.clone(),sketch_clipboard: self.sketch_clipboard.clone(),@@ -1214,6 +1238,18 @@ impl Session {/// saved state, view state, checkpoints or earlier undo steps.pub fn accept_computed(&mut self, mut computed: Session) {let previous_revision = self.revision;+ // The first computed step starts from this document. Its undo must restore the view+ // at acceptance, including a body hidden while the computation was running.+ if let Some(before) = computed.undo.first_mut()+ && Arc::ptr_eq(&before.doc, &self.doc)+ {+ before.visibility.hidden_bodies.clone_from(&self.visibility.hidden_bodies);+ }+ let rename = computed.body_rename(&self.doc);+ computed.visibility.hidden_bodies.clone_from(&self.visibility.hidden_bodies);+ computed.remap_hidden_bodies(&self.doc, &self.model.state(), rename.as_ref().map(|(old, new, _)| (old.as_str(), new.as_str())));+ self.visibility.hidden_bodies = std::mem::take(&mut computed.visibility.hidden_bodies);+ self.body_renames = computed.body_renames;self.doc = computed.doc;self.model = computed.model;self.world_cache = computed.world_cache;diff --git a/crates/engine/src/occurrences.rs b/crates/engine/src/occurrences.rsindex e763fec16f..1411091668 100644--- a/crates/engine/src/occurrences.rs+++ b/crates/engine/src/occurrences.rs@@ -60,6 +60,51 @@ pub(crate) struct RemovedLaterCache {}impl Session {+ /// Hidden names follow the same body and exact occurrence path through a rename. Undo+ /// history restores visibility separately. Never parse display labels:+ /// ambiguous labels and names containing slashes use the document's canonical naming.+ pub(crate) fn remap_hidden_bodies(+ &mut self,+ previous: &solidcraft_doc::Document,+ state: &solidcraft_doc::ModelState,+ rename: Option<(&str, &str)>,+ ) {+ if self.visibility.hidden_bodies.is_empty() {+ return;+ }+ if rename.is_none() {+ if previous.occurrences == self.doc.occurrences {+ return;+ }+ let old_names: std::collections::BTreeMap<_, _> = previous.occurrences.iter().map(|o| (o.id, &o.name)).collect();+ if !self.doc.occurrences.iter().any(|o| old_names.get(&o.id).is_some_and(|name| **name != o.name)) {+ return;+ }+ }+ let mut renamed = state.clone();+ if let Some((old, new)) = rename {+ for body in renamed.bodies.iter_mut().filter(|body| body.name == old) {+ body.name = new.to_string();+ }+ }+ let hidden: std::collections::BTreeSet<_> = self.visibility.hidden_bodies.iter().map(String::as_str).collect();+ let mut names = std::collections::BTreeMap::new();+ for (component, path, _) in previous.placements() {+ for body in state.bodies.iter().filter(|body| previous.model_body_component(body) == component) {+ let old = previous.world_body_name(state, &body.name, component, &path);+ if hidden.contains(old.as_str()) {+ let source = rename.filter(|(old, _)| *old == body.name).map_or(body.name.as_str(), |(_, new)| new);+ names.insert(old, self.doc.world_body_name(&renamed, source, component, &path));+ }+ }+ }+ for hidden in &mut self.visibility.hidden_bodies {+ if let Some(new) = names.get(hidden) {+ hidden.clone_from(new);+ }+ }+ }+/// Visibility keeps construction names, while undo history keeps feature ids. Follow the/// same axis or point into the new document on rename, undo and redo (#4419).pub(crate) fn follow_axis_point_renames(&mut self, previous: &solidcraft_doc::Document) {