BREP_render 0.32.0

Rendering engine of the next.BREP.io Rust B-rep CAD kernel: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
//! Rename a feature, solid, sketch or datum everywhere it is named (owner
//! 2026-11-27): one history edit, one undo step. The document rewrite is the
//! kernel's [`brep_kernel::rename_feature_in_document`]; this side resolves
//! what the user picked to the feature whose id is the name, moves the
//! name-keyed records the engine holds outside the document (object metadata,
//! the selection) and marks the undo step so undo and redo move them back.

use super::*;

/// What can be renamed (the `kind` of `entity_rename`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RenameKind {
    Feature,
    Solid,
    Sketch,
    Datum,
    Component,
}

impl RenameKind {
    pub fn parse(kind: &str) -> Result<RenameKind, String> {
        Ok(match kind {
            "feature" => RenameKind::Feature,
            "solid" => RenameKind::Solid,
            "sketch" => RenameKind::Sketch,
            "datum" => RenameKind::Datum,
            "component" => RenameKind::Component,
            other => return Err(format!("rename kind `{other}`: expected feature, solid, sketch, datum or component")),
        })
    }

    pub fn as_str(self) -> &'static str {
        match self {
            RenameKind::Feature => "feature",
            RenameKind::Solid => "solid",
            RenameKind::Sketch => "sketch",
            RenameKind::Datum => "datum",
            RenameKind::Component => "component",
        }
    }
}

const SKETCH_TYPES: &[&str] = &["S", "S3D"];
const DATUM_TYPES: &[&str] = &["D", "P"];
const COMPONENT_TYPES: &[&str] = &["ACOMP", "APAT"];

impl EngineState {
    /// The component ids this document's names may be namespaced by, level by
    /// level (its components, each with its part's below it): what reads a
    /// chain such as `Motor:Shaft:F1_PZ` instead of the `ACOMP<n>` shape alone.
    /// Built once per history revision.
    pub fn component_namespace(&self) -> std::rc::Rc<brep_kernel::ComponentNamespace> {
        let revision = self.history.revision();
        if let Some((built, namespace)) = self.component_namespace.borrow().as_ref() {
            if *built == revision {
                return namespace.clone();
            }
        }
        let namespace = std::rc::Rc::new(self.history.component_namespace());
        *self.component_namespace.borrow_mut() = Some((revision, namespace.clone()));
        namespace
    }

    /// The feature whose id `id` (of `kind`) is, or why it cannot be renamed.
    pub fn rename_target(&self, kind: RenameKind, id: &str) -> Result<String, String> {
        let namespace = self.component_namespace();
        let (chain, _) = namespace.split(id);
        if !chain.is_empty() {
            return Err(format!("`{id}` belongs to component `{}`: rename it in that component's part", chain[0]));
        }
        let feature_type = self.history.index_of(id).and_then(|index| self.history.feature_type(index));
        let what = kind.as_str();
        match (kind, feature_type.as_deref()) {
            (_, Some("APAT")) => Err(format!(
                "`{id}` is a pattern of components: its instances are named `{id}.<seed>.i<n>`, so a pattern keeps its APAT<n> id"
            )),
            (RenameKind::Component | RenameKind::Feature, Some(ty)) if COMPONENT_TYPES.contains(&ty) => Ok(id.to_string()),
            (RenameKind::Component, Some(ty)) => Err(format!("`{id}` is a `{ty}` feature, not a component")),
            (RenameKind::Component, None) => Err(format!("no component is named `{id}`")),
            (_, Some(ty)) if COMPONENT_TYPES.contains(&ty) => Err(format!("`{id}` is a component: rename it as a component")),
            (RenameKind::Feature, Some(_)) => Ok(id.to_string()),
            (RenameKind::Sketch, Some(ty)) if SKETCH_TYPES.contains(&ty) => Ok(id.to_string()),
            (RenameKind::Datum, Some(ty)) if DATUM_TYPES.contains(&ty) => Ok(id.to_string()),
            (RenameKind::Sketch | RenameKind::Datum, Some(ty)) => Err(format!("`{id}` is a `{ty}` feature, not a {what}")),
            (RenameKind::Solid, Some(_)) => Ok(id.to_string()),
            (RenameKind::Solid, None) => {
                if !self.scene.solids().iter().any(|solid| solid.name == id) {
                    return Err(format!("no solid is named `{id}`"));
                }
                let maker = self.provenance.get(id).map(|f| format!(" (made by `{f}`)")).unwrap_or_default();
                Err(format!(
                    "`{id}` is a derived name{maker}: a solid is named after the feature that first made it; rename that feature"
                ))
            }
            (_, None) => Err(format!("no {what} is named `{id}`")),
        }
    }

    /// Rename `id` (of `kind`) to `new` throughout the document as one undo
    /// step, then re-run. Answers what changed; refused by name, changing
    /// nothing, when any name could not be followed. Also answers the run
    /// report, as every history edit does.
    pub fn rename_entity(&mut self, kind: RenameKind, id: &str, new: &str) -> Result<(serde_json::Value, String), String> {
        if self.any_sketch_mode() {
            return Err("finish the open sketch before renaming".into());
        }
        let old = self.rename_target(kind, id)?;
        let mut document = self.history.request_value();
        let outcome = brep_kernel::rename_feature_in_document(&mut document, &old, new)?;
        let run = self.edit_document(document)?;
        self.history.note_rename(&old, new);
        self.rename_held_names(&old, new);
        Ok((serde_json::json!({
            "kind": kind.as_str(),
            "old": old,
            "new": new,
            "rewritten": outcome.rewritten,
            "referencingFeatures": outcome.referencing_features,
            "blocks": outcome.blocks,
        }), run))
    }

    /// Move the names the engine holds outside the document: object metadata
    /// keys and the selection.
    pub(super) fn rename_held_names(&mut self, old: &str, new: &str) {
        // The document's components, with the two ids of a renamed component
        // standing for one, so what follows either is its part's and stays.
        let mut namespace = (*self.component_namespace()).clone();
        if let Some(inner) = namespace.inner(old).or(namespace.inner(new)).cloned() {
            namespace.insert(old, inner.clone());
            namespace.insert(new, inner);
        }
        let map = |name: &String| brep_kernel::rename_name_in(name, old, new, &namespace).unwrap_or_else(|| name.clone());
        self.metadata.rename_names(old, new, &namespace);
        let solids: Vec<String> = self.emphasis.selected_solids.iter().map(map).collect();
        let faces: Vec<String> = self.emphasis.selected_faces.iter().map(map).collect();
        let edges: Vec<String> = self.emphasis.selected_edges.iter().map(map).collect();
        let datums: Vec<String> = self.emphasis.selected_datums.iter().map(map).collect();
        let feature = self.selected_feature.as_ref().map(|(id, _)| map(id));
        self.set_selection(&solids, &faces, &edges, &datums);
        if let (Some(feature), Some((_, selection))) = (feature, self.selected_feature.take()) {
            self.selected_feature = Some((feature, selection));
        }
    }

    /// What a rename from the selection would rename: the feature selected in
    /// the tree (as its kind), else one lone selected solid, else one lone
    /// selected datum plane (as the datum feature that makes it).
    pub fn rename_candidate(&self) -> Option<(RenameKind, String)> {
        if let Some(id) = self.selected_feature() {
            let ty = self.history.index_of(id).and_then(|index| self.history.feature_type(index)).unwrap_or_default();
            let kind = if SKETCH_TYPES.contains(&ty.as_str()) {
                RenameKind::Sketch
            } else if DATUM_TYPES.contains(&ty.as_str()) {
                RenameKind::Datum
            } else if COMPONENT_TYPES.contains(&ty.as_str()) {
                RenameKind::Component
            } else {
                RenameKind::Feature
            };
            return Some((kind, id.to_string()));
        }
        let e = &self.emphasis;
        let no_parts = e.selected_faces.is_empty() && e.selected_edges.is_empty() && e.selected_vertices.is_empty();
        if no_parts && e.selected_datums.is_empty() && e.selected_solids.len() == 1 {
            let name = e.selected_solids.iter().next()?.clone();
            let ty = self.history.index_of(&name).and_then(|index| self.history.feature_type(index));
            if ty.as_deref().is_some_and(|ty| COMPONENT_TYPES.contains(&ty)) {
                return Some((RenameKind::Component, name));
            }
            return Some((RenameKind::Solid, name));
        }
        if no_parts && e.selected_solids.is_empty() && e.selected_datums.len() == 1 {
            let frame = e.selected_datums.iter().next()?;
            let (id, _) = self.datum_feature_for_name(frame)?;
            return Some((RenameKind::Datum, id));
        }
        None
    }

    /// After an undo, redo or rollback: move the held names across the rename
    /// that step crossed, if it was one.
    pub(super) fn apply_travel_rename(&mut self) {
        if let Some((old, new)) = self.history.take_travel_rename() {
            self.rename_held_names(&old, &new);
        }
    }
}