Skip to main content

brep_app/panels/
part_properties.rs

1//! The PART PROPERTIES dialog — the open document's own BOM attributes, on the
2//! toolbar.
3//!
4//! # What it edits
5//!
6//! `partAttributes`, the top-level document key described in
7//! `brep_render::engine_state`'s BOM-attributes block. A document IS a part: a
8//! part file's Part Number, Material and Mass live on it and travel with it,
9//! which is exactly why an assembly's BOM can read them off a parts-library
10//! entry's EMBEDDED document. This dialog is the other door onto the same
11//! record — the one for the part you have OPEN, which until now had no editor
12//! at all. (An assembly document has the record too, and for the same reason: a
13//! rigidly nested assembly is ONE part, one BOM row, in its parent.)
14//!
15//! OCCURRENCE attributes are deliberately absent. They describe one PLACEMENT,
16//! so they belong to the assembly that places the part, not to the part — the
17//! BOM panel's occurrence columns are their editor.
18//!
19//! # Every field, not the starred ones
20//!
21//! The BOM column configuration decides what the parts LIST is wide enough to
22//! show. It says nothing about what a part HAS. So the dialog draws every part
23//! field — the configured ones in the user's own order, then the built-ins the
24//! configuration leaves out, then anything already stored that neither names
25//! (see [`bom_columns::part_fields`]). A field a user hid from the table is
26//! still a field of the part, and a dialog that hid it too would leave a stored
27//! value with no way to see or clear it.
28//!
29//! # The editors are the BOM's own
30//!
31//! Each row draws [`column_tree::value_editor`] for the field's `CellKind` —
32//! the very function the BOM table's cells draw. One attribute cannot have two
33//! editing behaviours when it has one store: text commits on focus-loss (an
34//! attribute write re-runs the history), a choice always offers the blank
35//! entry so it can be cleared, and clearing writes `""`, which the engine reads
36//! as REMOVE.
37
38use crate::automation::hit_keys::HitKeyDoc;
39use crate::column_tree;
40use crate::panels::bom_columns;
41use brep_render::engine_state::EngineState;
42use eframe::egui;
43use serde_json::Value;
44use std::collections::HashMap;
45
46/// The dialog's state: whether it is open, and this frame's widget rects.
47#[derive(Default)]
48pub struct PartPropertiesPanel {
49    /// Whether the floating window is shown. Toggled by the toolbar's
50    /// Properties button and by the window's own `×`; public so the toolbar can
51    /// bind it, exactly as the Settings window's flag is.
52    pub open: bool,
53    /// Per-frame egui widget screen rects (keyed `field:<Field>`), published for
54    /// the automation layer. Rebuilt every frame.
55    hits: HashMap<String, egui::Rect>,
56    configuration: crate::panels::bom_configuration::BomConfiguration,
57    plm_target: Option<(std::rc::Rc<crate::plm::client::PlmClient>,String)>,
58}
59
60impl PartPropertiesPanel {
61    pub fn configure_plm(&mut self,client:Option<std::rc::Rc<crate::plm::client::PlmClient>>,document:Option<&str>){
62        self.plm_target=client.zip(document.filter(|key|crate::plm::bom::revision_of_document(key).is_some()).map(str::to_string));
63        if self.open {if let Some((client,key))=&self.plm_target{self.configuration.ensure(client,vec![key.clone()],0);}}
64    }
65    pub fn new() -> Self {
66        Self::default()
67    }
68
69    /// Draw the floating window (if open) at ctx level, after the panels, so it
70    /// floats over the shell. `title` is the active document's tab title — the
71    /// part whose properties these are, named in the window so a user with
72    /// several tabs open can never edit the wrong one — and `document` its
73    /// process-unique id, which salts the per-field widget ids so an
74    /// in-progress edit belongs to the document it was typed into and cannot
75    /// reappear over another tab's value.
76    pub fn show(
77        &mut self,
78        ctx: &egui::Context,
79        state: &mut EngineState,
80        title: &str,
81        document: u64,
82    ) {
83        if !self.open {
84            return;
85        }
86        // `egui::Window::open` needs its own `&mut bool`; borrow a copy so the
87        // draw closure can still take `&mut self`, then fold the close back in.
88        let mut open = true;
89        egui::Window::new("Part Properties")
90            .open(&mut open)
91            .movable(true)
92            .resizable(true)
93            // A bounded default size + the filling ScrollArea in `body`: without
94            // a filling child egui hugs the window to its content and the user
95            // cannot drag it larger (the Settings window's rule).
96            .default_size([340.0, 420.0])
97            // Offset from the Settings window's own default rest position, so
98            // opening both does not stack them pixel-for-pixel.
99            .default_pos(super::below_chrome(ctx, 660.0, 40.0))
100            .show(ctx, |ui| self.body(ui, state, title, document));
101        self.open = open;
102
103        if crate::automation::registry::enabled() {
104            crate::automation::registry::publish(
105                "__brepPartPropertiesHit",
106                "part properties window widget rects (field:*)",
107                &self.hits_json(),
108            );
109        }
110    }
111
112    /// The window body: the part's name, then one labelled row per field.
113    fn body(&mut self, ui: &mut egui::Ui, state: &mut EngineState, title: &str, document: u64) {
114        self.hits.clear();
115        if let Some((client,key))=&self.plm_target {
116            ui.label(egui::RichText::new(title).strong());
117            self.configuration.attributes_ui(ui,client,key,&mut self.hits);
118            return;
119        }
120        ui.label(egui::RichText::new(title).strong());
121        ui.label(
122            egui::RichText::new(
123                "Stored on this document and carried into any assembly's BOM.",
124            )
125            .weak()
126            .small(),
127        );
128        ui.separator();
129
130        // Read the record LIVE each frame rather than caching it: an undo, the
131        // automation layer, or a switch to another document tab all change it
132        // under the dialog, and a cached copy would show — and then write back —
133        // the previous document's values.
134        let stored = state.document_part_attributes();
135        // Mass and Volume are COMPUTED from this document's geometry and the
136        // density it names; a document with no geometry types its Mass.
137        let report = state.document_mass();
138        let derived = brep_render::engine_state::part_mass::MassStatus::Override != report.status
139            && report.solid_count > 0;
140        let shown = state.document_bom_record();
141        // Through `effective_text`, exactly as the BOM table reads its columns:
142        // the stored setting is EMPTY until the user configures it, and the
143        // shipped default is what the table is ordered by. Reading the raw
144        // string here would order a never-configured document's fields by the
145        // catalogue instead, so the dialog and the table would disagree for
146        // every user who never opened the settings.
147        let fields = bom_columns::part_fields(
148            &bom_columns::effective_text(&state.settings.bom_columns),
149            &stored,
150        );
151
152        // Commit AFTER the loop: `set_document_part_attribute` re-runs the
153        // history, and re-entering the engine mid-draw while `stored` is
154        // borrowed from it is exactly the kind of half-applied frame that makes
155        // a text buffer fight its own value. A LIST, not one edit: a frame that
156        // blurs a text field while a drag value moves carries two, and dropping
157        // either is a lost keystroke.
158        let mut edits: Vec<(String, Value)> = Vec::new();
159        egui::ScrollArea::vertical()
160            .auto_shrink([false, false])
161            .show(ui, |ui| {
162                egui::Grid::new("part-properties-grid")
163                    .num_columns(2)
164                    .spacing([8.0, 4.0])
165                    .striped(true)
166                    .show(ui, |ui| {
167                        for field in &fields {
168                            ui.label(field.label());
169                            let size = egui::vec2(
170                                ui.available_width().max(80.0),
171                                ui.spacing().interact_size.y,
172                            );
173                            let (kind, value) = field_view(field, &stored, &shown, &report, derived);
174                            let (committed, rect) = column_tree::value_editor(
175                                ui,
176                                egui::Id::new(("part-properties", document, &field.field)),
177                                &kind,
178                                value.as_ref(),
179                                size,
180                            );
181                            self.hits.insert(format!("field:{}", field.field), rect);
182                            if let Some(value) = committed {
183                                edits.push((field.field.clone(), value));
184                            }
185                            ui.end_row();
186                        }
187                    });
188            });
189
190        for (key, value) in edits {
191            if let Err(error) = state.set_document_part_attribute(&key, value) {
192                state.push_notice(format!("Part Properties: {error}"));
193            }
194        }
195    }
196
197    /// The published widget hit-rects (egui points) for the automation layer.
198    pub fn hits_json(&self) -> String {
199        crate::automation::hit_rects::hits_json(&self.hits)
200    }
201}
202
203/// How one field is drawn: its editor kind and the value it shows. `Mass`
204/// and `Volume` show the COMPUTED reading with its unit, read-only — except
205/// a document with no geometry, whose Mass is typed (in kg). `Density`
206/// shows the Material's built-in density when none is typed.
207fn field_view(
208    field: &bom_columns::BomColumn,
209    stored: &Value,
210    shown: &Value,
211    report: &brep_render::engine_state::part_mass::MassReport,
212    derived: bool,
213) -> (column_tree::CellKind, Option<Value>) {
214    use brep_render::engine_state::part_mass::{format_derived, MASS_KEY, VOLUME_KEY, DENSITY_KEY};
215    match field.field.as_str() {
216        MASS_KEY if !derived => (
217            column_tree::CellKind::Numeric { step: 0.01 },
218            stored.get(MASS_KEY).cloned(),
219        ),
220        MASS_KEY | VOLUME_KEY => {
221            let text = shown
222                .get(&field.field)
223                .and_then(|value| format_derived(&field.field, value))
224                .or_else(|| report.status.note().filter(|_| field.field == MASS_KEY));
225            (column_tree::CellKind::ReadOnly, text.map(Value::String))
226        }
227        DENSITY_KEY => (field.kind(), shown.get(DENSITY_KEY).cloned()),
228        _ => (field.kind(), stored.get(&field.field).cloned()),
229    }
230}
231
232/// The hit keys this panel publishes (see `automation::hit_keys`).
233pub static HIT_KEYS: &[HitKeyDoc] = &[HitKeyDoc {
234    panel: "partproperties",
235    prefix: "field:",
236    meaning: "a part-attribute editor in the Part Properties window (field:<Field>)",
237    command: Some("part_attribute_set"),
238}];
239