Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Deleting an inserted file removes its components, placements and joints (#4100) (#4113)

raykholoe1bf784014a1
diff --git a/crates/doc/src/component_removal.rs b/crates/doc/src/component_removal.rs
new file mode 100644
index 0000000000..1e32566145
--- /dev/null
+++ b/crates/doc/src/component_removal.rs
@@ -0,0 +1,92 @@
+//! Removing a component tree: its components, the features made in them, their placements, and
+//! every assembly record that refers to them.
+
+use std::collections::BTreeSet;
+
+use crate::{DocError, Document, FeatureKind, Result};
+
+/// What [`Document::remove_component_tree`] removed.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct RemovedTree {
+ /// The removed components: the root and everything inside it.
+ pub components: Vec<u64>,
+ /// The features that were inside them, in timeline order.
+ pub features: Vec<u64>,
+ /// Every deleted feature: `features`, then features elsewhere built on their sketches.
+ pub deleted: Vec<u64>,
+ /// The removed occurrences: placements of the components and placements inside them.
+ pub occurrences: Vec<u64>,
+ /// The removed joints: those with either side on a removed occurrence.
+ pub joints: Vec<u64>,
+}
+
+impl Document {
+ /// Did feature `f` make the component tree it sits at the top of: an inserted file
+ /// (`Feature::inserted`) or a linked design's bodies? Deleting it then removes that tree.
+ pub fn feature_owns_component(&self, f: &crate::Feature) -> bool {
+ f.component != 0
+ && matches!(f.kind, FeatureKind::Import { .. } | FeatureKind::MeshImport { .. })
+ && (f.inserted || self.links.get(&f.component).is_some_and(|link| link.feature == f.id))
+ }
+
+ /// Remove component `root` with every component inside it, the features made in them, their
+ /// occurrences, the joints, motion links, joint origins, contact sets, motion keys and
+ /// exploded moves that refer to those occurrences, the bodies' component assignments, and the
+ /// components' standard-part, link, appearance and configuration records.
+ ///
+ /// Refused (nothing changes) for the design itself, an unknown component, or a tree that
+ /// supplies a body transfer recorded outside it.
+ pub fn remove_component_tree(&mut self, root: u64) -> Result<RemovedTree> {
+ if root == 0 {
+ return Err(DocError::Invalid("the design itself can't be deleted".into()));
+ }
+ if !self.components.iter().any(|c| c.id == root) {
+ return Err(DocError::Unknown(format!("component {root}")));
+ }
+ let components: Vec<u64> = self.components.iter().filter(|c| self.component_within(c.id, root)).map(|c| c.id).collect();
+ let inside: BTreeSet<u64> = components.iter().copied().collect();
+ if self.features.iter().any(|feature| {
+ !inside.contains(&feature.component)
+ && matches!(&feature.kind, FeatureKind::BodyTransfer { from, to, .. } if inside.contains(from) || inside.contains(to))
+ }) {
+ return Err(DocError::Invalid(
+ "component supplies a recorded body transfer outside this subtree; remove that transfer history before deleting its source".into(),
+ ));
+ }
+ let features: Vec<u64> = self.features.iter().filter(|f| inside.contains(&f.component)).map(|f| f.id).collect();
+ let deleted = if features.is_empty() { Vec::new() } else { self.delete_features(&features)? };
+
+ let occurrences: BTreeSet<u64> =
+ self.occurrences.iter().filter(|o| inside.contains(&o.component) || inside.contains(&o.parent)).map(|o| o.id).collect();
+ let joints: BTreeSet<u64> = self
+ .assembly
+ .joints
+ .iter()
+ .filter(|j| occurrences.contains(&j.a.occurrence) || occurrences.contains(&j.b.occurrence))
+ .map(|j| j.id)
+ .collect();
+ let assembly = &mut self.assembly;
+ assembly.joints.retain(|j| !joints.contains(&j.id));
+ assembly.links.retain(|l| !joints.contains(&l.a) && !joints.contains(&l.b));
+ assembly.origins.retain(|o| !occurrences.contains(&o.origin.occurrence));
+ for set in &mut assembly.contact_sets {
+ set.occurrences.retain(|o| !occurrences.contains(o));
+ }
+ for study in &mut assembly.studies {
+ study.keys.retain(|k| !joints.contains(&k.joint));
+ }
+ for view in &mut assembly.exploded {
+ view.moves.retain(|(o, _)| !occurrences.contains(o));
+ }
+ self.occurrences.retain(|o| !occurrences.contains(&o.id));
+
+ let bodies: BTreeSet<String> = self.body_components.iter().filter(|(_, c)| inside.contains(*c)).map(|(name, _)| name.clone()).collect();
+ self.body_components.retain(|_, c| !inside.contains(c));
+ self.body_offsets.retain(|name, _| !bodies.contains(name));
+ self.components.retain(|c| !inside.contains(&c.id));
+ self.parts.retain(|c, _| !inside.contains(c));
+ self.links.retain(|c, _| !inside.contains(c));
+ self.remove_configuration_components(&components);
+ Ok(RemovedTree { components, features, deleted, occurrences: occurrences.into_iter().collect(), joints: joints.into_iter().collect() })
+ }
+}
diff --git a/crates/doc/src/document.rs b/crates/doc/src/document.rs
index 3cc022d659..df04cba819 100644
--- a/crates/doc/src/document.rs
+++ b/crates/doc/src/document.rs
@@ -2375,6 +2375,12 @@ pub struct Feature {
/// mean that numbering.
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub kernel_piece_order: bool,
+ /// Made by inserting a file (STEP, IGES or a mesh file) into the design: the feature built
+ /// the component tree its component is the top of, and deleting it removes that tree
+ /// ([`Document::remove_component_tree`]). Not set on other imported bodies, such as the
+ /// independent base of a copied component.
+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]
+ pub inserted: bool,
#[serde(flatten)]
pub kind: FeatureKind,
}
@@ -3130,6 +3136,7 @@ impl Document {
participants: Vec::new(),
shell_piece_order: false,
kernel_piece_order: false,
+ inserted: false,
kind,
};
self.place_feature(f);
@@ -3223,11 +3230,39 @@ impl Document {
self.name_feature_inputs(id);
}
- /// Delete a feature (and, for a sketch, the features that use it).
+ /// Delete a feature (and, for a sketch, the features that use it). The feature of an inserted
+ /// file or a linked design takes the component tree it made with it: everything in that tree
+ /// and every assembly record that refers to it ([`Document::remove_component_tree`]). Other
+ /// imported bodies (a copied component's independent base) go alone.
pub fn delete_feature(&mut self, id: u64) -> Result<Vec<u64>> {
- let idx = self.feature_index(id).ok_or_else(|| DocError::Unknown(format!("feature {id}")))?;
- let mut gone = vec![id];
- gone.extend(self.features.iter().filter(|f| f.kind.input_sketches().contains(&id)).map(|f| f.id));
+ let owned = self.feature(id).filter(|f| self.feature_owns_component(f)).map(|f| f.component);
+ match owned {
+ Some(root) => Ok(self.remove_component_tree(root)?.deleted),
+ None => self.delete_features(&[id]),
+ }
+ }
+
+ /// Delete features `ids` and the features whose sketches they are. Returns every deleted id,
+ /// `ids` first.
+ pub(crate) fn delete_features(&mut self, ids: &[u64]) -> Result<Vec<u64>> {
+ let mut gone: Vec<u64> = Vec::with_capacity(ids.len());
+ for id in ids {
+ if self.feature_index(*id).is_none() {
+ return Err(DocError::Unknown(format!("feature {id}")));
+ }
+ if !gone.contains(id) {
+ gone.push(*id);
+ }
+ }
+ let dependants: Vec<u64> = self
+ .features
+ .iter()
+ .filter(|f| !gone.contains(&f.id) && f.kind.input_sketches().iter().any(|sketch| gone.contains(sketch)))
+ .map(|f| f.id)
+ .collect();
+ gone.extend(dependants);
+ // How many of them come before the rollback marker: it keeps its place among the rest.
+ let before_marker = self.marker.map(|m| self.features.iter().take(m).filter(|f| gone.contains(&f.id)).count());
let gone_params: Vec<String> = self.features.iter().filter(|f| gone.contains(&f.id)).flat_map(|f| f.param_names.clone()).collect();
self.configs
.rules
@@ -3259,10 +3294,8 @@ impl Document {
r.cells.retain(|_| k.next().copied().unwrap_or(true));
}
}
- if let Some(m) = self.marker
- && m > idx
- {
- self.marker = Some(m.saturating_sub(gone.len()).max(idx));
+ if let (Some(m), Some(n)) = (self.marker, before_marker) {
+ self.marker = Some(m.saturating_sub(n));
}
// Drop model parameters nobody references any more.
self.prune_model_params();
diff --git a/crates/doc/src/format/pending/inserted-file-features.rs b/crates/doc/src/format/pending/inserted-file-features.rs
new file mode 100644
index 0000000000..17c1719650
--- /dev/null
+++ b/crates/doc/src/format/pending/inserted-file-features.rs
@@ -0,0 +1,52 @@
+//! The feature of a file inserted into a design (STEP, IGES or a mesh file) is marked `inserted`:
+//! it made the component tree at whose top it sits, and deleting it removes that tree with it.
+//! Older designs are rewritten as they open: an import or mesh import inside a component is
+//! marked, except the independent base of a copied component, which goes alone as before. The
+//! last release refuses a design saved with this (the newer format number).
+use serde_json::Value;
+
+pub fn step(v: &mut Value) -> crate::Result<()> {
+ let Some(Value::Array(features)) = v.get_mut("features") else {
+ return Ok(());
+ };
+ for feature in features {
+ let Some(object) = feature.as_object_mut() else { continue };
+ let in_component = object.get("component").and_then(Value::as_u64).is_some_and(|c| c != 0);
+ let inserted = match object.get("type").and_then(Value::as_str) {
+ Some("mesh_import") => true,
+ // A copied component's independent base: a body re-exported on its own, no file tree.
+ Some("import") => {
+ let base = object.get("file").and_then(Value::as_str).is_some_and(|f| f.ends_with(" independent base"))
+ && object.get("components").and_then(Value::as_array).is_none_or(Vec::is_empty);
+ !base
+ }
+ _ => false,
+ };
+ if in_component && inserted {
+ object.insert("inserted".into(), Value::Bool(true));
+ }
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use serde_json::json;
+
+ #[test]
+ fn older_inserted_files_are_marked_but_copied_bases_are_not() {
+ let mut v = json!({"features": [
+ {"type": "import", "file": "parts.step", "component": 2},
+ {"type": "mesh_import", "file": "bracket.stl", "component": 5},
+ {"type": "import", "file": "Block independent base", "component": 7},
+ {"type": "import", "file": "opened.step"},
+ {"type": "extrude", "component": 2}
+ ]});
+ super::step(&mut v).unwrap();
+ let marked: Vec<bool> = v["features"].as_array().unwrap().iter().map(|f| f["inserted"] == json!(true)).collect();
+ assert_eq!(marked, [true, true, false, false, false]);
+ let mut empty = json!({"name": "Untitled"});
+ super::step(&mut empty).unwrap();
+ assert_eq!(empty, json!({"name": "Untitled"}));
+ }
+}
diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs
index 2a0b5cf34c..b2e57d3bea 100644
--- a/crates/doc/src/lib.rs
+++ b/crates/doc/src/lib.rs
@@ -14,6 +14,8 @@ pub use body_transfer::{valid_transfer_matrix, validate_body_transfer};
pub mod canvas;
mod clipboard;
pub use clipboard::{clone_expression, remap_topology};
+mod component_removal;
+pub use component_removal::RemovedTree;
pub mod config;
pub mod construct;
pub mod display_quality;
diff --git a/crates/engine/src/cmd/component.rs b/crates/engine/src/cmd/component.rs
index 7165824eeb..2d57723b6e 100644
--- a/crates/engine/src/cmd/component.rs
+++ b/crates/engine/src/cmd/component.rs
@@ -244,31 +244,15 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
if id == 0 {
return Err(bad(cmd, "the design itself can't be deleted"));
}
- let gone: Vec<u64> = s.doc.components.iter().filter(|c| s.doc.component_within(c.id, id)).map(|c| c.id).collect();
- if s.doc.features.iter().any(|feature| {
- !gone.contains(&feature.component)
- && matches!(&feature.kind, FeatureKind::BodyTransfer { from, to, .. } if gone.contains(from) || gone.contains(to))
- }) {
- return Err(bad(
- cmd,
- "component supplies a recorded body transfer outside this subtree; remove that transfer history before deleting its source",
- ));
- }
- let feats: Vec<u64> = s.doc.features.iter().filter(|f| gone.contains(&f.component)).map(|f| f.id).collect();
- let d = s.doc_mut();
- for f in &feats {
- let _ = d.delete_feature(*f);
- }
- d.components.retain(|c| !gone.contains(&c.id));
- d.remove_configuration_components(&gone);
- d.occurrences.retain(|o| !gone.contains(&o.component) && !gone.contains(&o.parent));
- let moved_out: Vec<String> = d.body_components.iter().filter(|(_, c)| gone.contains(c)).map(|(b, _)| b.clone()).collect();
- d.body_components.retain(|_, c| !gone.contains(c));
- d.body_offsets.retain(|b, _| !moved_out.contains(b));
+ let removed = s.doc_mut().remove_component_tree(id).map_err(|e| match e {
+ solidcraft_doc::DocError::Invalid(msg) => bad(cmd, msg),
+ e => e.into(),
+ })?;
+ let gone = removed.components;
if gone.contains(&s.active_component) {
s.active_component = 0;
}
- Ok(json!({"deleted": gone, "features": feats}))
+ Ok(json!({"deleted": gone, "features": removed.features}))
}
fn unlock(s: &mut Session, p: &Value) -> Result<Value> {
diff --git a/crates/engine/src/cmd/component_clone_tests.rs b/crates/engine/src/cmd/component_clone_tests.rs
index 081d403857..aeac5ebf1f 100644
--- a/crates/engine/src/cmd/component_clone_tests.rs
+++ b/crates/engine/src/cmd/component_clone_tests.rs
@@ -75,6 +75,25 @@ fn reassigned_body_is_an_independent_base_feature() {
near(volume(&mut s, new), 8.0);
}
+#[test]
+fn deleting_an_independent_base_keeps_the_copied_component() {
+ let mut s = Session::default();
+ box2(&mut s);
+ let part = component(&mut s, "Part");
+ run(&mut s, "component.move_bodies", json!({"component":part,"bodies":["Cube"]}));
+ let new = copy(&mut s, part)["component"].as_u64().unwrap();
+ let base = s.doc.features.iter().find(|f| f.component == new && matches!(f.kind, solidcraft_doc::FeatureKind::Import { .. })).unwrap();
+ assert!(!base.inserted && !s.doc.feature_owns_component(base));
+ let (base, others) = (base.id, s.doc.features.iter().filter(|f| f.component == new).count() - 1);
+ let (components, occurrences, joints) = (s.doc.components.clone(), s.doc.occurrences.clone(), s.doc.assembly.joints.clone());
+ let reply = run(&mut s, "timeline.delete", json!({"feature": base.to_string()}));
+ assert_eq!(reply["deleted"], json!([base]));
+ assert_eq!(s.doc.components, components);
+ assert_eq!(s.doc.occurrences, occurrences);
+ assert_eq!(s.doc.assembly.joints, joints);
+ assert_eq!(s.doc.features.iter().filter(|f| f.component == new).count(), others);
+}
+
#[test]
fn clone_preserves_physical_material_and_independent_styles() {
let mut s = Session::default();
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rs
index e84816f037..ee69fbd160 100644
--- a/crates/engine/src/cmd/edit.rs
+++ b/crates/engine/src/cmd/edit.rs
@@ -168,6 +168,10 @@ fn delete(s: &mut Session, p: &Value) -> Result<Value> {
if s.active_sketch.is_some_and(|a| gone.contains(&a)) {
s.active_sketch = None;
}
+ // An inserted file's feature takes its components with it.
+ if s.active_component != 0 && !s.doc.components.iter().any(|c| c.id == s.active_component) {
+ s.active_component = 0;
+ }
s.selection.clear();
s.refresh();
let failing: Vec<Value> = s
diff --git a/crates/engine/src/cmd/file_import.rs b/crates/engine/src/cmd/file_import.rs
index fae0a51a00..0a3ea1d103 100644
--- a/crates/engine/src/cmd/file_import.rs
+++ b/crates/engine/src/cmd/file_import.rs
@@ -290,6 +290,7 @@ pub(crate) fn add_in_component(
if let Some(f) = s.doc_mut().feature_mut(id) {
f.component = top;
f.body_names = body_names;
+ f.inserted = true;
}
let moves: Vec<(usize, u64, Mat)> = plan.bodies.iter().filter_map(|(b, slot, offset)| comps.get(*slot).map(|c| (*b, *c, *offset))).collect();
put_bodies(s, &names, &moves);
diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs
index ea5d69f859..d5e748511a 100644
--- a/crates/engine/src/cmd/occurrence_tests.rs
+++ b/crates/engine/src/cmd/occurrence_tests.rs
@@ -828,3 +828,35 @@ fn joins_into_a_moved_occurrence_meet_the_tool_where_it_is_shown() {
let want = 10.0 * 10.0 * 10.0 - 4.0 * 4.0 * 10.0;
assert!((volume(&s, "C") - want).abs() < 1e-6 * want, "C: {} vs {want}", volume(&s, "C"));
}
+
+#[test]
+fn component_delete_removes_joints_to_its_occurrences_and_undo_restores_them() {
+ let mut s = Session::default();
+ for (name, corner) in [("Arm", [20, -2, -2]), ("Kept", [-2, 20, -2])] {
+ run(&mut s, "component.activate", json!({"component": 0}));
+ created(&mut s, name);
+ run(&mut s, "solid.box", json!({"length": 4, "width": 4, "height": 4, "corner": corner}));
+ }
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "revolute", "a": {"occurrence": 0, "point": [0,0,0]}, "b": {"occurrence": "Arm", "point": [0,0,0]}, "name": "Pivot"}),
+ );
+ run(
+ &mut s,
+ "joint.create",
+ json!({"type": "rigid", "a": {"occurrence": 0, "point": [0,0,0]}, "b": {"occurrence": "Kept", "point": [0,0,0]}, "name": "Held"}),
+ );
+ let arm = s.doc.find_component("Arm").unwrap();
+ let before = s.doc.clone();
+
+ let reply = run(&mut s, "component.delete", json!({"component": "Arm"}));
+ let features: Vec<u64> = before.features.iter().filter(|f| f.component == arm).map(|f| f.id).collect();
+ assert_eq!(reply, json!({"deleted": [arm], "features": features}));
+ let joints: Vec<&str> = s.doc.assembly.joints.iter().map(|j| j.name.as_str()).collect();
+ assert_eq!(joints, ["Held"]);
+ run(&mut s, "joint.list", json!({}));
+
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc, before);
+}
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index c2c138dc88..0cb56f5976 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -1258,6 +1258,55 @@ 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.
+#[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()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let path = dir.join("parts.step");
+ let mut source = Session::default();
+ for (name, x) in [("Part", 0), ("Other", 20)] {
+ run(&mut source, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [x, 0, 0], "operation": "new", "body_name": name}));
+ }
+ run(&mut source, "component.from_bodies", json!({"bodies": ["Part", "Other"]}));
+ run(&mut source, "file.export", json!({"path": path.to_string_lossy()}));
+
+ let mut s = Session::default();
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Part"}));
+ let kept = s.doc_mut().add_component(Some("Kept"), 0).unwrap();
+ let kept_occurrence = s.doc.occurrence_of(kept).unwrap().clone();
+ run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy(), "name": "Imported"}));
+ let reopened = solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap();
+ assert!(reopened.find_feature("Imported").unwrap().inserted, "the insert keeps its mark through save");
+ run(&mut s, "solid.mirror", json!({"bodies": ["Part"], "plane": {"origin": [0, 30, 0], "normal": [0, 1, 0]}}));
+ assert!(s.model.state().body("Part (3)").is_some());
+ assert!(!s.doc.assembly.joints.is_empty());
+ assert!(!s.doc.body_components.is_empty());
+ let before = s.doc.clone();
+ let history = s.undo.len();
+
+ run(&mut s, "timeline.delete", json!({"feature": "Imported"}));
+ assert_eq!(s.undo.len(), history + 1);
+ assert_eq!(s.doc.components.iter().map(|c| c.id).collect::<Vec<_>>(), [kept]);
+ assert_eq!(s.doc.occurrences, [kept_occurrence]);
+ assert!(s.doc.assembly.joints.is_empty());
+ 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();
+ 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);
+ run(&mut s, "edit.undo", json!({}));
+ run(&mut s, "edit.undo", json!({}));
+ assert_eq!(s.doc, before);
+ assert!(s.model.state().body("Part (3)").is_some());
+ run(&mut s, "edit.redo", json!({}));
+ assert!(s.doc.body_components.is_empty());
+ assert!(s.doc.assembly.joints.is_empty());
+ std::fs::remove_dir_all(dir).unwrap();
+}
+
/// Previews evaluate on a scratch copy: the document, undo history and model are untouched.
#[test]
fn preview_has_no_side_effects() {