Skip to main content

brep_render/engine_state/
rename_ops.rs

1//! Rename a feature, solid, sketch or datum everywhere it is named (owner
2//! 2026-11-27): one history edit, one undo step. The document rewrite is the
3//! kernel's [`brep_kernel::rename_feature_in_document`]; this side resolves
4//! what the user picked to the feature whose id is the name, moves the
5//! name-keyed records the engine holds outside the document (object metadata,
6//! the selection) and marks the undo step so undo and redo move them back.
7
8use super::*;
9
10/// What can be renamed (the `kind` of `entity_rename`).
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum RenameKind {
13    Feature,
14    Solid,
15    Sketch,
16    Datum,
17    Component,
18}
19
20impl RenameKind {
21    pub fn parse(kind: &str) -> Result<RenameKind, String> {
22        Ok(match kind {
23            "feature" => RenameKind::Feature,
24            "solid" => RenameKind::Solid,
25            "sketch" => RenameKind::Sketch,
26            "datum" => RenameKind::Datum,
27            "component" => RenameKind::Component,
28            other => return Err(format!("rename kind `{other}`: expected feature, solid, sketch, datum or component")),
29        })
30    }
31
32    pub fn as_str(self) -> &'static str {
33        match self {
34            RenameKind::Feature => "feature",
35            RenameKind::Solid => "solid",
36            RenameKind::Sketch => "sketch",
37            RenameKind::Datum => "datum",
38            RenameKind::Component => "component",
39        }
40    }
41}
42
43const SKETCH_TYPES: &[&str] = &["S", "S3D"];
44const DATUM_TYPES: &[&str] = &["D", "P"];
45const COMPONENT_TYPES: &[&str] = &["ACOMP", "APAT"];
46
47impl EngineState {
48    /// The component ids this document's names may be namespaced by, level by
49    /// level (its components, each with its part's below it): what reads a
50    /// chain such as `Motor:Shaft:F1_PZ` instead of the `ACOMP<n>` shape alone.
51    /// Built once per history revision.
52    pub fn component_namespace(&self) -> std::rc::Rc<brep_kernel::ComponentNamespace> {
53        let revision = self.history.revision();
54        if let Some((built, namespace)) = self.component_namespace.borrow().as_ref() {
55            if *built == revision {
56                return namespace.clone();
57            }
58        }
59        let namespace = std::rc::Rc::new(self.history.component_namespace());
60        *self.component_namespace.borrow_mut() = Some((revision, namespace.clone()));
61        namespace
62    }
63
64    /// The feature whose id `id` (of `kind`) is, or why it cannot be renamed.
65    pub fn rename_target(&self, kind: RenameKind, id: &str) -> Result<String, String> {
66        let namespace = self.component_namespace();
67        let (chain, _) = namespace.split(id);
68        if !chain.is_empty() {
69            return Err(format!("`{id}` belongs to component `{}`: rename it in that component's part", chain[0]));
70        }
71        let feature_type = self.history.index_of(id).and_then(|index| self.history.feature_type(index));
72        let what = kind.as_str();
73        match (kind, feature_type.as_deref()) {
74            (_, Some("APAT")) => Err(format!(
75                "`{id}` is a pattern of components: its instances are named `{id}.<seed>.i<n>`, so a pattern keeps its APAT<n> id"
76            )),
77            (RenameKind::Component | RenameKind::Feature, Some(ty)) if COMPONENT_TYPES.contains(&ty) => Ok(id.to_string()),
78            (RenameKind::Component, Some(ty)) => Err(format!("`{id}` is a `{ty}` feature, not a component")),
79            (RenameKind::Component, None) => Err(format!("no component is named `{id}`")),
80            (_, Some(ty)) if COMPONENT_TYPES.contains(&ty) => Err(format!("`{id}` is a component: rename it as a component")),
81            (RenameKind::Feature, Some(_)) => Ok(id.to_string()),
82            (RenameKind::Sketch, Some(ty)) if SKETCH_TYPES.contains(&ty) => Ok(id.to_string()),
83            (RenameKind::Datum, Some(ty)) if DATUM_TYPES.contains(&ty) => Ok(id.to_string()),
84            (RenameKind::Sketch | RenameKind::Datum, Some(ty)) => Err(format!("`{id}` is a `{ty}` feature, not a {what}")),
85            (RenameKind::Solid, Some(_)) => Ok(id.to_string()),
86            (RenameKind::Solid, None) => {
87                if !self.scene.solids().iter().any(|solid| solid.name == id) {
88                    return Err(format!("no solid is named `{id}`"));
89                }
90                let maker = self.provenance.get(id).map(|f| format!(" (made by `{f}`)")).unwrap_or_default();
91                Err(format!(
92                    "`{id}` is a derived name{maker}: a solid is named after the feature that first made it; rename that feature"
93                ))
94            }
95            (_, None) => Err(format!("no {what} is named `{id}`")),
96        }
97    }
98
99    /// Rename `id` (of `kind`) to `new` throughout the document as one undo
100    /// step, then re-run. Answers what changed; refused by name, changing
101    /// nothing, when any name could not be followed. Also answers the run
102    /// report, as every history edit does.
103    pub fn rename_entity(&mut self, kind: RenameKind, id: &str, new: &str) -> Result<(serde_json::Value, String), String> {
104        if self.any_sketch_mode() {
105            return Err("finish the open sketch before renaming".into());
106        }
107        let old = self.rename_target(kind, id)?;
108        let mut document = self.history.request_value();
109        let outcome = brep_kernel::rename_feature_in_document(&mut document, &old, new)?;
110        let run = self.edit_document(document)?;
111        self.history.note_rename(&old, new);
112        self.rename_held_names(&old, new);
113        Ok((serde_json::json!({
114            "kind": kind.as_str(),
115            "old": old,
116            "new": new,
117            "rewritten": outcome.rewritten,
118            "referencingFeatures": outcome.referencing_features,
119            "blocks": outcome.blocks,
120        }), run))
121    }
122
123    /// Move the names the engine holds outside the document: object metadata
124    /// keys and the selection.
125    pub(super) fn rename_held_names(&mut self, old: &str, new: &str) {
126        // The document's components, with the two ids of a renamed component
127        // standing for one, so what follows either is its part's and stays.
128        let mut namespace = (*self.component_namespace()).clone();
129        if let Some(inner) = namespace.inner(old).or(namespace.inner(new)).cloned() {
130            namespace.insert(old, inner.clone());
131            namespace.insert(new, inner);
132        }
133        let map = |name: &String| brep_kernel::rename_name_in(name, old, new, &namespace).unwrap_or_else(|| name.clone());
134        self.metadata.rename_names(old, new, &namespace);
135        let solids: Vec<String> = self.emphasis.selected_solids.iter().map(map).collect();
136        let faces: Vec<String> = self.emphasis.selected_faces.iter().map(map).collect();
137        let edges: Vec<String> = self.emphasis.selected_edges.iter().map(map).collect();
138        let datums: Vec<String> = self.emphasis.selected_datums.iter().map(map).collect();
139        let feature = self.selected_feature.as_ref().map(|(id, _)| map(id));
140        self.set_selection(&solids, &faces, &edges, &datums);
141        if let (Some(feature), Some((_, selection))) = (feature, self.selected_feature.take()) {
142            self.selected_feature = Some((feature, selection));
143        }
144    }
145
146    /// What a rename from the selection would rename: the feature selected in
147    /// the tree (as its kind), else one lone selected solid, else one lone
148    /// selected datum plane (as the datum feature that makes it).
149    pub fn rename_candidate(&self) -> Option<(RenameKind, String)> {
150        if let Some(id) = self.selected_feature() {
151            let ty = self.history.index_of(id).and_then(|index| self.history.feature_type(index)).unwrap_or_default();
152            let kind = if SKETCH_TYPES.contains(&ty.as_str()) {
153                RenameKind::Sketch
154            } else if DATUM_TYPES.contains(&ty.as_str()) {
155                RenameKind::Datum
156            } else if COMPONENT_TYPES.contains(&ty.as_str()) {
157                RenameKind::Component
158            } else {
159                RenameKind::Feature
160            };
161            return Some((kind, id.to_string()));
162        }
163        let e = &self.emphasis;
164        let no_parts = e.selected_faces.is_empty() && e.selected_edges.is_empty() && e.selected_vertices.is_empty();
165        if no_parts && e.selected_datums.is_empty() && e.selected_solids.len() == 1 {
166            let name = e.selected_solids.iter().next()?.clone();
167            let ty = self.history.index_of(&name).and_then(|index| self.history.feature_type(index));
168            if ty.as_deref().is_some_and(|ty| COMPONENT_TYPES.contains(&ty)) {
169                return Some((RenameKind::Component, name));
170            }
171            return Some((RenameKind::Solid, name));
172        }
173        if no_parts && e.selected_solids.is_empty() && e.selected_datums.len() == 1 {
174            let frame = e.selected_datums.iter().next()?;
175            let (id, _) = self.datum_feature_for_name(frame)?;
176            return Some((RenameKind::Datum, id));
177        }
178        None
179    }
180
181    /// After an undo, redo or rollback: move the held names across the rename
182    /// that step crossed, if it was one.
183    pub(super) fn apply_travel_rename(&mut self) {
184        if let Some((old, new)) = self.history.take_travel_rename() {
185            self.rename_held_names(&old, &new);
186        }
187    }
188}
189