From 2755c9ccfbeeeae0e42b3b62d28d5b8f19924d1c Mon Sep 17 00:00:00 2001 From: Steven Waters <39838467+stevenpwaters@users.noreply.github.com> Date: Mon, 26 Oct 2026 12:33:58 +0000 Subject: [PATCH] Pin auto-generated body names (#6402) (#6403) * Pin auto-generated body names Co-Authored-By: Claude Sonnet 5.5 * Fixed body counter Co-Authored-By: Claude Sonnet 5.5 * Fixed formatting Co-Authored-By: Claude Sonnet 5.5 * Altered test behaviour to reflect new pinned body names Co-authored-by: Claude --------- Co-authored-by: Claude Sonnet 5.5 --- crates/doc/src/document.rs | 12 ++++++-- crates/doc/src/eval.rs | 7 ++++- crates/engine/src/cmd/browser.rs | 3 +- crates/engine/src/cmd/edit_tests.rs | 47 +++++++++++++++++++++++++++++ crates/engine/src/lib.rs | 47 +++++++++++++++++++++++++++++ crates/engine/src/tests.rs | 5 +-- 6 files changed, 115 insertions(+), 6 deletions(-) diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs index 4512e5895..63e980513 100644 --- a/crates/doc/src/document.rs +++ b/crates/doc/src/document.rs @@ -2580,6 +2580,11 @@ pub struct DesignLink { pub feature: u64, } +/// A name the design's counter hands out (`Body1`). +pub fn is_counted_body_name(name: &str) -> bool { + name.strip_prefix("Body").is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()) && n.parse::().is_ok()) +} + /// The document. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Document { @@ -2914,9 +2919,12 @@ impl Document { /// /// A name the design numbered (`Body1`) is not used again after the rename: the design's /// counter starts over at every evaluation, so without this a design that is evaluated - /// again hands the freed name to the next body (#4957). + /// again hands the freed name to the next body (#4957). Every counted name is reserved as + /// soon as a body has it (`Session::pin_body_names`), so this only matters for a design + /// that has not been through a command since then. `new` may be a reserved name: a rename + /// is deliberate, and the body then has what the design keeps under it. pub fn rename_body_keys(&mut self, old: &str, new: &str) { - if old.strip_prefix("Body").and_then(|n| n.parse::().ok()).is_some() { + if is_counted_body_name(old) { self.reserved_body_names.insert(old.to_string()); } if let Some(m) = self.materials.remove(old) { diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index c473fd0b0..bccac6144 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -2365,7 +2365,7 @@ impl Model { /// Set every result's fingerprint to `doc`'s, so the next evaluation reuses every result /// (after a change that builds nothing differently). - fn refingerprint(&mut self, doc: &Document) { + pub fn refingerprint(&mut self, doc: &Document) { let (vals, _) = evaluation_values(doc); let marker = doc.marker.unwrap_or(usize::MAX); self.step_digests = StepDigests::of(doc, &self.step_digests); @@ -2479,6 +2479,11 @@ fn new_name(state: &mut ModelState, f: &Feature, k: usize) -> String { && !n.is_empty() && state.body(n).is_none() { + // A pinned `BodyN` counts as handed out, so a design evaluated again from its stored + // names ends with the counter it had when the counter numbered them. + if let Some(number) = n.strip_prefix("Body").filter(|_| crate::is_counted_body_name(n)).and_then(|d| d.parse::().ok()) { + state.body_counter = state.body_counter.max(number); + } return n.clone(); } // Bodies past the stored names (a profile added after the feature was made) are numbered diff --git a/crates/engine/src/cmd/browser.rs b/crates/engine/src/cmd/browser.rs index 1bf804908..4ad70c863 100644 --- a/crates/engine/src/cmd/browser.rs +++ b/crates/engine/src/cmd/browser.rs @@ -1295,8 +1295,9 @@ mod tests { assert!(["Body1", "Body2", "Body3", "Body4", "Body5"].iter().all(|n| before.contains(&n.to_string())), "{before:?}"); run(&mut s, "solid.combine", json!({"target": "Body3", "tools": ["Body5"], "operation": "join", "name": "Joined"})); // Renaming a body that already has a name of its own stores nothing elsewhere. + let stored = s.doc.find_feature("P2").unwrap().body_names.clone(); run(&mut s, "body.rename", json!({"body": "Second", "name": "Row"})); - assert!(s.doc.find_feature("P2").unwrap().body_names.is_empty()); + assert_eq!(s.doc.find_feature("P2").unwrap().body_names, stored); run(&mut s, "body.rename", json!({"body": "Body1", "name": "FirstCopyA"})); run(&mut s, "body.rename", json!({"body": "Body2", "name": "FirstCopyB"})); assert!( diff --git a/crates/engine/src/cmd/edit_tests.rs b/crates/engine/src/cmd/edit_tests.rs index 10c675094..2bc560ebe 100644 --- a/crates/engine/src/cmd/edit_tests.rs +++ b/crates/engine/src/cmd/edit_tests.rs @@ -822,6 +822,53 @@ fn suppressing_a_feature_keeps_later_counted_body_names() { assert!(works(&s)); } +/// Counted body names are pinned when the body is made, as if the user had renamed it: deleting, +/// reordering or rolling back another feature leaves the other bodies' names alone, and a number +/// a deleted feature held is not handed to the next body. +#[test] +fn counted_body_names_stay_when_the_timeline_changes() { + let mut s = Session::default(); + for (name, x) in [("A", 0), ("B", 20), ("C", 40)] { + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "name": name})); + } + run(&mut s, "solid.move", json!({"bodies": ["Body2"], "translate": [0, 30, 0], "name": "Move"})); + let bodies = |s: &Session| -> Vec<(String, String)> { + let st = s.model.state(); + st.bodies.iter().map(|b| (b.name.clone(), s.doc.feature(b.feature).map(|f| f.name.clone()).unwrap_or_default())).collect() + }; + let named = |pairs: &[(&str, &str)]| pairs.iter().map(|(b, f)| (b.to_string(), f.to_string())).collect::>(); + let works = |s: &Session| s.doc.features.iter().all(|f| s.model.result(f.id).is_some_and(|r| r.error.is_none())); + // The names are stored on the features as soon as the bodies exist. + assert_eq!(s.doc.find_feature("B").map(|f| f.body_names.clone()), Some(vec!["Body2".to_string()])); + assert!(["Body1", "Body2", "Body3"].iter().all(|n| s.doc.reserved_body_names.contains(*n))); + + // Reordering A behind B: every body keeps its number, wherever it comes in the list. + run(&mut s, "timeline.reorder", json!({"feature": "A", "position": 2, "active": true})); + let mut reordered = bodies(&s); + reordered.sort(); + assert_eq!(reordered, named(&[("Body1", "A"), ("Body2", "B"), ("Body3", "C")])); + assert!(works(&s)); + run(&mut s, "edit.undo", json!({})); + + // Rolled back to before B and forward again. + run(&mut s, "timeline.roll_to", json!({"position": 1})); + run(&mut s, "timeline.roll_to", json!({"position": "end"})); + assert_eq!(bodies(&s), named(&[("Body1", "A"), ("Body2", "B"), ("Body3", "C")])); + + // Deleting A: B and C keep their names, so the Move still finds Body2. + run(&mut s, "timeline.delete", json!({"feature": "A"})); + assert_eq!(bodies(&s), named(&[("Body2", "B"), ("Body3", "C")])); + assert!(works(&s), "the Move still finds Body2"); + + // The number A held is not handed out again. + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [60, 0, 0], "name": "D"})); + assert_eq!(bodies(&s), named(&[("Body2", "B"), ("Body3", "C"), ("Body4", "D")])); + // Undo takes the box away, and the number back with it. + run(&mut s, "edit.undo", json!({})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [60, 0, 0], "name": "E"})); + assert_eq!(bodies(&s), named(&[("Body2", "B"), ("Body3", "C"), ("Body4", "E")])); +} + /// The value at a dotted path of a definition. fn dotted<'a>(def: &'a Value, path: &str) -> &'a Value { path.split('.').fold(def, |v, k| &v[k]) diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8a78e7660..de3089509 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -802,6 +802,49 @@ impl Session { self.refresh(); } + /// Pin the name of every body the features made, as if the body had been renamed to it, and + /// reserve the `Body` names, so that no later command renames a body or hands its number + /// to another. It is part of the command that made the bodies. A design saved before names + /// were pinned is pinned by its first command that changes it, with the names it has after + /// that command: when that command is itself a delete, reorder, suppress or rollback, the + /// later counted bodies are renumbered once, as they always were. + fn pin_body_names(&mut self) { + if self.model.is_stale() { + return; + } + let mut pins: Vec<(u64, Vec)> = Vec::new(); + let mut reserve: Vec = Vec::new(); + for f in self.doc.features.iter().filter(|f| !matches!(f.kind, solidcraft_doc::FeatureKind::FrameMember { .. })) { + let Some(r) = self.model.result(f.id).filter(|r| r.error.is_none() && !r.skipped && !r.stale) else { continue }; + let made: Vec<&str> = r.state.bodies.iter().filter(|b| b.feature == f.id).map(|b| b.name.as_str()).collect(); + reserve.extend( + made.iter().filter(|n| solidcraft_doc::is_counted_body_name(n) && !self.doc.reserved_body_names.contains(**n)).map(|n| n.to_string()), + ); + let mut names = f.body_names.clone(); + names.resize(names.len().max(made.len()), String::new()); + for (slot, name) in names.iter_mut().zip(&made) { + if slot.trim().is_empty() { + *slot = name.to_string(); + } + } + if names != f.body_names { + pins.push((f.id, names)); + } + } + if pins.is_empty() && reserve.is_empty() { + return; + } + let doc = self.doc_mut(); + for (id, names) in pins { + if let Some(f) = doc.feature_mut(id) { + f.body_names = names; + } + } + doc.reserved_body_names.extend(reserve); + // The pinned names are the ones the bodies have: no result changes, so none is evaluated. + self.model.refingerprint(&self.doc); + } + /// A hidden construction plane stays hidden when the design renames it, or undo or redo /// gives it another name (#4353): the hidden list keeps planes by name. fn follow_plane_renames(&mut self, previous: &Document) { @@ -1062,6 +1105,7 @@ impl Session { } self.redo.clear(); } + let pin = outermost && live_edit.is_none() && !render_only; match live_edit { Some(edit) => { let sketch = edit.sketch; @@ -1072,6 +1116,9 @@ impl Session { None if display_only => self.refresh_display(), None => self.refresh_from(&previous_doc), } + if pin { + self.pin_body_names(); + } } Ok(v) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index ccc86d87f..6d84ed265 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -1279,7 +1279,8 @@ fn body_volume(st: &solidcraft_doc::ModelState) -> f64 { st.bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum() } -/// Deleting an inserted assembly frees its body names without leaving assembly ownership behind. +/// Deleting an inserted assembly keeps the names of the bodies that remain, and leaves no assembly +/// ownership behind. #[test] fn step_insert_delete_removes_assembly_and_undo_restores_it() { let dir = std::env::temp_dir().join(format!("solidcraft-step-delete-{}", std::process::id())); @@ -1314,7 +1315,7 @@ fn step_insert_delete_removes_assembly_and_undo_restores_it() { assert!(s.doc.body_components.is_empty()); assert!(s.doc.body_offsets.is_empty()); let state = s.model.state(); - let mirrored = state.body("Part (2)").unwrap(); + let mirrored = state.body("Part (3)").unwrap(); assert_eq!(s.doc.model_body_component(mirrored), 0); run(&mut s, "solid.box", json!({"length": 5, "width": 5, "height": 5, "corner": [40, 0, 0], "operation": "new", "body_name": "Other"})); assert_eq!(s.doc.model_body_component(s.model.state().body("Other").unwrap()), 0);