Skip to main content

brep_app/panels/
settings.rs

1//! Display-settings panel — the schema-driven settings form. Drawn as a
2//! FLOATING window (movable + resizable [`egui::Window`], toggled from the
3//! toolbar gear ⚙ button), mirroring the Properties window: a `pub open` flag the
4//! toolbar binds + a ctx-level `show(&mut self, ctx, state, store)` the shell
5//! calls after the panels. The panel OWNS only its transient UI state (which
6//! nodes are open); `EngineState` stays the single brain, borrowed in.
7//!
8//! # Model colours are NOT set here
9//!
10//! A body's or face's colour is a durable `color` METADATA attribute, set in the
11//! Info window and saved with the document. This panel carries only the display
12//! switch over it — `Faces ▸ Override model colors`, an ordinary schema `Bool`
13//! that makes the viewport ignore those colours without touching them. The old
14//! `Per-Solid Colors` tab wrote a transient override that no document ever
15//! stored and any feature edit threw away; it is gone.
16//!
17//! # One TAB per section, each drawn as a tree
18//!
19//! The window opens on a tab strip ([`Tab`], the Info window's `selectable_value`
20//! strip) — `Display` / `Assemblies` — and draws exactly ONE section below it. Each section is still the SAME connector-line `[+]/[-]` tree
21//! the feature history and Scene panels use (the shared [`tree`] node helper), so
22//! the whole app reads as one system:
23//!   * `Display` → `[-] Display settings` (root) → one collapsible BRANCH per
24//!     schema group (`Scene`, `Faces`, `Edges`, …) → one LEAF per field, whose
25//!     node label is the field label and whose right-aligned content is the field
26//!     input ([`form::field_input`], EXACTLY like the feature tree's
27//!     `schema_field`).
28//!   * `Assemblies` → `[-] Assemblies` (root) → the BOM column configuration.
29//! Group open-state is tracked on the panel (default open). Every ROOT defaults
30//! OPEN too: the roots that used to default collapsed did so only because they
31//! shared one scroll — a tab whose entire content is one `[+]` row is not
32//! worth the click.
33//!
34//! Only the ACTIVE tab's widget rects are published to `__brepSettingsHit`, since
35//! `hits` is rebuilt each frame from what was actually drawn.
36
37use crate::automation::hit_keys::HitKeyDoc;
38use crate::form;
39use crate::panels::bom_columns;
40use crate::panels::tree::{self, TreeRow};
41use crate::store::{ModelStore, SETTINGS_KEY};
42use brep_render::engine_state::EngineState;
43use brep_render::style::{settings_form_fields, FormField, RenderSettings};
44use eframe::egui;
45use serde_json::Value;
46use std::collections::{HashMap, HashSet};
47
48/// The amber a BOM-column parse problem is listed in — the status map's
49/// warning amber, the same one the structure tree's outdated badge uses. A
50/// problem is a note about ONE line, not a failure, so it is not error red.
51const PROBLEM_AMBER: egui::Color32 = egui::Color32::from_rgb(0xff, 0x9f, 0x0a);
52
53/// The tabs of the Settings window — one per section. Each draws its own tree;
54/// nothing is shared between them but the window.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Tab {
57    /// The schema-driven render settings.
58    Display,
59    /// Assembly-wide configuration (today: the BOM's columns).
60    Assemblies,
61    /// The PLM server: its URL (editable wherever `plm.json` can be written),
62    /// and for the PLM this session is on or configured for, sign-in, check,
63    /// forget (plan S1 part 3). Present in every session (owner 2026-10-29).
64    Plm,
65}
66
67/// The display-settings panel's own transient UI state. It holds NO model state:
68/// the settings buffer is re-seeded from the live engine each frame (see
69/// `SettingsPanel::settings_section`).
70pub struct SettingsPanel {
71    /// Whether the floating window is shown. Toggled by the toolbar gear button
72    /// and by the window's own close (`×`) button; public so the toolbar can bind
73    /// it.
74    pub open: bool,
75    /// Per-frame egui widget screen rects (keyed `tab:<name>` / `field:<key>` /
76    /// `group:<name>` / …), published to JS for the headed verifier. Rebuilt every
77    /// frame, so it holds only the ACTIVE tab's widgets.
78    hits: HashMap<String, egui::Rect>,
79    /// Which tab is shown. Defaults to `Display`, the tab the window has always
80    /// opened on.
81    tab: Tab,
82    /// The `Display settings` root is collapsed (false = open — it defaults open).
83    display_collapsed: bool,
84    /// Setting GROUPS explicitly COLLAPSED, by group name (absent = open — groups
85    /// default open, matching the retired per-group CollapsingHeaders).
86    closed_groups: HashSet<String>,
87    /// The `Assemblies` root is collapsed (false = open — see above).
88    assemblies_collapsed: bool,
89    /// The BOM-columns textarea's live edit buffer. Held here, not re-seeded
90    /// per frame like the settings JSON, because a multi-line editor cannot be
91    /// re-seeded mid-edit without fighting the caret. It tracks the engine
92    /// while UNFOCUSED and commits on focus-loss (the expressions editor's
93    /// rule); `None` = not yet seeded.
94    bom_columns_buf: Option<String>,
95    /// The PLM tab's state, built when the store first reports a PLM and
96    /// rebuilt if its URL changes. `None` in a file-only session.
97    plm: Option<crate::plm::connection::PlmConnection>,
98    /// The Server URL field's edit buffer, and the store URL it was seeded
99    /// from: re-seeded when the store's URL moves, never mid-edit. It commits
100    /// on focus loss (Enter included), the BOM columns editor's rule.
101    url_buf: Option<(String, Option<String>)>,
102    /// What the last Server URL commit did: saved (the sentence says what
103    /// happens next) or refused (the reason). Kept here, not on `plm`, which
104    /// a new URL rebuilds.
105    url_outcome: Option<crate::plm::connection::Outcome>,
106    /// Set by the app every frame: why this session cannot switch to the PLM
107    /// live (open named or dirty documents), or `None` when it can.
108    pub reconnect_blocker: Option<String>,
109    /// Connect now was pressed: the config root the app switches to.
110    reconnect_request: Option<std::path::PathBuf>,
111    /// The live session's sign-in was refused by the server (revoked,
112    /// expired): the tab reads not connected, with this reason, until the
113    /// person signs in again.
114    signed_out: Option<String>,
115}
116
117impl SettingsPanel {
118    /// Open the window on its PLM tab ("Open in CAD" before signing in): the
119    /// tab exists while the store reports a PLM, signed in or not.
120    pub fn show_plm_tab(&mut self) {
121        self.open = true;
122        self.tab = Tab::Plm;
123    }
124
125    /// The server ended this session's sign-in: open the PLM tab on its
126    /// sign-in, saying `why`, instead of a raw error on every request.
127    pub fn ask_plm_sign_in(&mut self, why: String) {
128        self.signed_out = Some(why);
129        self.show_plm_tab();
130    }
131
132    /// A native sign-in in the tab passed: `(username, token)`. The shell
133    /// hands it to the live session when that session's token was refused;
134    /// the tab reads connected again.
135    pub fn take_fresh_plm_token(&mut self) -> Option<(String, String)> {
136        let fresh = self.plm.as_mut()?.take_fresh_token()?;
137        self.signed_out = None;
138        Some(fresh)
139    }
140
141    /// Forget signed this machine out on the server since the last call: the
142    /// tab reads not connected, and the shell expects the server's refusal.
143    pub fn take_plm_signed_out_here(&mut self) -> bool {
144        if !self.plm.as_mut().is_some_and(|plm| plm.take_signed_out_here()) {
145            return false;
146        }
147        self.signed_out = Some("you signed out of the PLM on this machine: the next start is the file app, or sign in again".into());
148        true
149    }
150
151    /// The live session's sign-in was refused (see [`Self::ask_plm_sign_in`]).
152    pub fn plm_signed_out(&self) -> bool {
153        self.signed_out.is_some()
154    }
155
156    /// A fresh panel. The settings buffer is re-seeded from the engine every frame
157    /// (not stored), so construction needs no engine handle.
158    pub fn new() -> Self {
159        Self {
160            open: false,
161            hits: HashMap::new(),
162            tab: Tab::Display,
163            display_collapsed: false,
164            closed_groups: HashSet::new(),
165            assemblies_collapsed: false,
166            bom_columns_buf: None,
167            plm: None,
168            url_buf: None,
169            url_outcome: None,
170            reconnect_blocker: None,
171            reconnect_request: None,
172            signed_out: None,
173        }
174    }
175
176    /// Draw the floating window (if open) at ctx level — after the panels, like
177    /// the file dialog, so it floats over the shell. The `open` flag is shared with
178    /// the toolbar gear button (which toggles it) and the window's own `×` (which
179    /// closes it). `EngineState` is the single brain, borrowed in.
180    pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
181        if self.open {
182            // `egui::Window::open` needs its own `&mut bool`; borrow a copy so the
183            // draw closure can still take `&mut self`, then fold the close back in.
184            let mut open = true;
185            egui::Window::new("Settings")
186                .open(&mut open)
187                .movable(true)
188                .resizable(true)
189                // A bounded default size + a fill ScrollArea (in `body`, under the
190                // tab strip) makes the window FREELY resizable LARGER than its
191                // content: without a filling child egui hugs the window to content
192                // and won't grow.
193                .default_size([460.0, 480.0])
194                // Rest on the right so it floats clear of the left panel; the user
195                // can drag it anywhere.
196                .default_pos(super::below_chrome(ctx, 720.0, 0.0))
197                .show(ctx, |ui| self.body(ui, state, store));
198            self.open = open;
199        } else {
200            // A CLOSED window publishes no rects. The publish used to sit inside
201            // the branch above, so the last open frame's map stayed in the
202            // registry for the rest of the session: `hit_rects settings/` kept
203            // answering with fifty fields of a window that was not on screen, and
204            // `click_widget` on one of them aimed a click at empty space. Same
205            // rule as the workbench strip and the sketch overlay, which publish an
206            // empty map while they are hidden.
207            self.hits.clear();
208        }
209
210        // Publish this frame's widget rects for the headed verifier (parity
211        // with the history + scene panels) — empty while the window is closed.
212        if crate::automation::registry::enabled() {
213            crate::automation::registry::publish("__brepSettingsHit", "settings window widget rects (field:*, group:*, panel:clip); empty while the window is closed", &self.hits_json());
214            crate::automation::registry::publish("__brepPlm", "the Settings PLM tab (present in every session, so tab is always true): {tab, status, url, username, reason, busy, outcome, failed, linking, linkCode, linkUrl, linkToken, linkNote} for the session's PLM — status \"not-configured\" (and those null) when there is none — and the Server URL field {serverUrl, urlSource (\"plm.json\", \"BREP_PLM_URL\", \"--plm-url\" or null), urlEditable, urlField, urlOutcome, urlFailed}", &self.plm_json(store));
215        }
216    }
217
218    /// The window body: the tab strip, then the ONE section that tab selects —
219    /// each still built on the shared [`tree`] node helper, so every tab reads as
220    /// the same tree the history + scene panels draw.
221    ///
222    /// The strip sits ABOVE the ScrollArea (rather than inside the one `show` used
223    /// to wrap the whole body in), so the tabs stay put while a long settings tree
224    /// scrolls under them.
225    fn body(&mut self, ui: &mut egui::Ui, state: &mut EngineState, store: &dyn ModelStore) {
226        self.hits.clear();
227        // The window's VISIBLE region, under the same key every scrolling pane
228        // publishes. The Display tree is longer than the window, and egui hands
229        // out a layout rect for a row that is scrolled past the bottom edge — a
230        // click there lands outside the window's clip and does nothing at all,
231        // which reads as "the switch is broken" rather than "the switch is off
232        // screen". With the region published, `scroll_into_view` wheels the row
233        // up first. Taken HERE rather than inside the scroll area so the tab
234        // strip above it counts as visible too: a clip that excluded the strip
235        // would send a click on `tab:assemblies` scrolling forever looking for
236        // a widget that never moves.
237        self.hits.insert("panel:clip".into(), ui.clip_rect());
238
239        // The tab drawn this frame is the one that was active BEFORE the strip.
240        // `selectable_value` switches `self.tab` mid-frame, and a section that
241        // vanishes the same frame it loses the click never gets its focus-loss —
242        // which is how the Assemblies editor COMMITS. Deferring by one frame lets
243        // the editor blur normally (invisible at 60fps, and the difference between
244        // "my BOM columns saved" and "my typing disappeared").
245        // The PLM tab is in every session: a file-only one shows its Server
246        // URL field, which is how such a session connects.
247        self.sync_plm(store.plm_session());
248        let tab = self.tab;
249        ui.horizontal(|ui| {
250            let display = ui.selectable_value(&mut self.tab, Tab::Display, "Display");
251            let assemblies = ui.selectable_value(&mut self.tab, Tab::Assemblies, "Assemblies");
252            self.hits.insert("tab:display".into(), display.rect);
253            self.hits.insert("tab:assemblies".into(), assemblies.rect);
254            let plm = ui.selectable_value(&mut self.tab, Tab::Plm, "PLM");
255            self.hits.insert("tab:plm".into(), plm.rect);
256        });
257        // ...and because of that defer, the switch needs ONE more frame to show
258        // its new section. The shell only requests a repaint while work is
259        // pending (`app.rs`: a run / queries / mesh imports), so on native a
260        // click with no further input would leave the strip highlighting a tab
261        // whose content has not been drawn yet. Ask for that frame here.
262        if self.tab != tab {
263            ui.ctx().request_repaint();
264        }
265        ui.separator();
266
267        egui::ScrollArea::vertical()
268            .auto_shrink([false, false])
269            .show(ui, |ui| {
270                // Tight, tree-like row spacing so connector verticals read
271                // continuously — the same the history + scene trees set (this panel
272                // must match them). Set INSIDE the scroll so the tab strip above
273                // keeps ordinary widget spacing.
274                ui.spacing_mut().item_spacing.y = 2.0;
275                match tab {
276                    Tab::Display => self.settings_section(ui, state, store),
277                    Tab::Assemblies => self.assemblies_section(ui, state, store),
278                    Tab::Plm => {
279                        self.plm_url_section(ui, store);
280                        self.plm_section(ui);
281                    }
282                }
283            });
284    }
285
286    /// The `__brepPlm` state. Read from the store whether or not the window is
287    /// open, so a script can see the session's PLM without opening Settings.
288    fn plm_json(&mut self, store: &dyn ModelStore) -> String {
289        use crate::plm::connection::{Outcome, Status};
290        self.sync_plm(store.plm_session());
291        let setting = store.plm_url_setting();
292        let (url_outcome, url_failed) = match &self.url_outcome {
293            Some(Outcome::Done(text)) => (Some(text.clone()), false),
294            Some(Outcome::Failed(text)) => (Some(text.clone()), true),
295            None => (None, false),
296        };
297        let field = serde_json::json!({
298            "serverUrl": setting.as_ref().and_then(|s| s.url.clone()),
299            "urlSource": setting.as_ref().and_then(|s| s.source).map(crate::plm::config::url_origin),
300            "urlEditable": setting.is_some(),
301            "urlField": self.url_buf.as_ref().map(|(buf, _)| buf.clone()),
302            "urlOutcome": url_outcome, "urlFailed": url_failed,
303        });
304        let Some(plm) = self.plm.as_mut() else {
305            let mut json = serde_json::json!({ "tab": true, "status": "not-configured", "url": null });
306            json.as_object_mut().expect("an object").extend(field.as_object().expect("an object").clone());
307            return json.to_string();
308        };
309        plm.poll();
310        let (status, url, username, reason) = match &plm.status {
311            Status::Connected { url, username } => ("connected", url.clone(), Some(username.clone()), None),
312            Status::NotConnected { url, reason } => ("not-connected", url.clone(), None, reason.clone()),
313        };
314        let (outcome, failed) = match &plm.last {
315            Some(Outcome::Done(text)) => (Some(text.clone()), false),
316            Some(Outcome::Failed(text)) => (Some(text.clone()), true),
317            None => (None, false),
318        };
319        let mut json = serde_json::json!({
320            "tab": true, "status": status, "url": url, "username": username, "reason": reason,
321            "busy": plm.busy(), "outcome": outcome, "failed": failed,
322            "connectable": plm.connectable(), "reconnectBlocker": self.reconnect_blocker,
323            "linking": plm.linking(),
324            "linkCode": plm.link.as_ref().map(|l| l.code.clone()),
325            "linkUrl": plm.link.as_ref().map(|l| l.url.clone()),
326            // The token alone, for a script deciding the link as the browser would.
327            "linkToken": plm.link.as_ref().and_then(|l| l.url.split_once("token=").map(|(_, t)| t.to_string())),
328            "linkNote": plm.link.as_ref().and_then(|l| l.note.clone()),
329        });
330        json.as_object_mut().expect("an object").extend(field.as_object().expect("an object").clone());
331        json.to_string()
332    }
333
334    /// Connect now's request, for the app to act on (once).
335    pub fn take_reconnect_request(&mut self) -> Option<std::path::PathBuf> {
336        self.reconnect_request.take()
337    }
338
339    /// What the app's switch did: shown in the tab as its outcome.
340    pub fn reconnected(&mut self, outcome: Result<String, String>) {
341        if let Some(plm) = self.plm.as_mut() {
342            plm.reconnected(outcome);
343        }
344    }
345
346    /// Keep the PLM tab's state in step with what the store reports.
347    fn sync_plm(&mut self, session: Option<crate::plm::connection::Session>) {
348        use crate::plm::connection::PlmConnection;
349        let Some(session) = session else {
350            self.plm = None;
351            return;
352        };
353        let url = match &session.status {
354            crate::plm::connection::Status::Connected { url, .. } | crate::plm::connection::Status::NotConnected { url, .. } => url.clone(),
355        };
356        let same = self.plm.as_ref().is_some_and(|c| c.url() == url && *c.keep() == session.keep);
357        // Refused by the server: not connected, whatever the store's label says.
358        let status = match (&self.signed_out, session.status) {
359            (Some(why), crate::plm::connection::Status::Connected { url, .. }) => {
360                crate::plm::connection::Status::NotConnected { url, reason: Some(why.clone()) }
361            }
362            (_, status) => status,
363        };
364        match self.plm.as_mut().filter(|_| same) {
365            // Same server, same keep: a live switch moves only the status.
366            Some(plm) => plm.set_status(status),
367            None => self.plm = Some(PlmConnection::new(status, session.keep)),
368        }
369    }
370
371    /// The PLM tab's Server URL (owner 2026-10-29): the URL this session uses
372    /// or would use and where it came from, and — wherever a `plm.json` can be
373    /// written — the field that writes it, committed on focus loss (Enter
374    /// included) exactly as `--plm-configure` would write it. Hit keys
375    /// `plm:url`, `plm:url-source`, `plm:url-outcome`.
376    fn plm_url_section(&mut self, ui: &mut egui::Ui, store: &dyn ModelStore) {
377        use crate::plm::config::{url_origin, Source};
378        use crate::plm::connection::{Outcome, Status};
379        let setting = store.plm_url_setting();
380        let editable = setting.is_some();
381        // No setting is the browser: its PLM is the server serving the page.
382        let shown = match &setting {
383            Some(setting) => setting.url.clone(),
384            None => self.plm.as_ref().map(|plm| plm.url().to_string()).filter(|url| !url.is_empty()),
385        };
386        let source = setting.as_ref().and_then(|s| s.source);
387        if self.url_buf.as_ref().is_none_or(|(_, from)| *from != shown) {
388            self.url_buf = Some((shown.clone().unwrap_or_default(), shown.clone()));
389        }
390
391        tree::node(
392            ui,
393            TreeRow {
394                guides: &[],
395                is_last: true,
396                expandable: false,
397                expanded: true,
398                root: true,
399                glyph: None,
400                label: "PLM server",
401                selected: false,
402                highlighted: false,
403                draggable: false,
404                tint: None,
405            },
406            |_| {},
407        );
408        let mut committed = false;
409        let mut rect = egui::Rect::NOTHING;
410        let (buf, _) = self.url_buf.as_mut().expect("seeded above");
411        tree::node(ui, TreeRow::leaf(&[], true, "Server URL"), |ui| {
412            ui.add_enabled_ui(editable, |ui| {
413                let width = form::text_input_width(ui);
414                let field = form::text_input(ui, buf, width);
415                committed = field.lost_focus();
416                rect = field.rect;
417            });
418        });
419        self.hits.insert("plm:url".into(), rect);
420
421        if committed && editable {
422            let typed = buf.trim().to_string();
423            if typed != shown.clone().unwrap_or_default() {
424                self.url_outcome = Some(if typed.is_empty() {
425                    Outcome::Failed("an empty URL is not saved: Forget this machine's sign-in removes the server from this machine".into())
426                } else {
427                    match store.save_plm_url(&typed) {
428                        Err(why) => Outcome::Failed(format!("not saved: {why}")),
429                        Ok(saved) => {
430                            let mut said = format!("saved to plm.json: {}", saved.url);
431                            if saved.token_dropped {
432                                said += "; this machine's sign-in for the previous server is forgotten (a token is never sent to another server)";
433                            }
434                            match (source, self.plm.as_ref().map(|plm| &plm.status)) {
435                                (Some(Source::Env | Source::Flag), _) => {
436                                    said += &format!(
437                                        "; this launch stays on {} ({} overrides plm.json), and a start without it uses {}",
438                                        shown.clone().unwrap_or_default(),
439                                        url_origin(source.expect("matched")),
440                                        saved.url
441                                    );
442                                }
443                                (_, Some(Status::Connected { url, .. })) if *url != saved.url => {
444                                    said += &format!("; this session stays on {url} until the next start");
445                                }
446                                _ => said += "; sign in below, then Connect now (or the next start) puts this session on it",
447                            }
448                            // The store's URL moves only for a session on
449                            // plm.json; keep the saved text either way.
450                            let from = store.plm_url_setting().and_then(|s| s.url);
451                            self.url_buf = Some((saved.url.clone(), from));
452                            Outcome::Done(said)
453                        }
454                    }
455                });
456            }
457        }
458
459        let note = match (&setting, source) {
460            (Some(_), Some(source @ (Source::Env | Source::Flag))) => format!(
461                "From {}, which overrides plm.json for this launch. A URL saved here is what a launch without it uses.",
462                url_origin(source)
463            ),
464            (Some(_), Some(Source::File)) => {
465                "From plm.json. Changing the server forgets this machine's sign-in: a token is never sent to a different server.".into()
466            }
467            (Some(_), None) => "No PLM server is set: this session uses the files on this machine. Enter the server's URL (http:// or https://) and press Enter, then sign in.".into(),
468            (None, _) if shown.is_some() => "The web app uses the PLM that serves this page.".into(),
469            (None, _) => "This page is not served by a PLM, so there is no server to point it at: open the CAD app from your PLM's web page to use one.".into(),
470        };
471        let said = ui.add(egui::Label::new(note).wrap());
472        self.hits.insert("plm:url-source".into(), said.rect);
473        if let Some(outcome) = &self.url_outcome {
474            let (text, color) = match outcome {
475                Outcome::Done(text) => (text.clone(), ui.visuals().text_color()),
476                Outcome::Failed(text) => (text.clone(), PROBLEM_AMBER),
477            };
478            let said = ui.add(egui::Label::new(egui::RichText::new(text).color(color)).wrap());
479            self.hits.insert("plm:url-outcome".into(), said.rect);
480        }
481        ui.separator();
482    }
483
484    /// The `PLM` TAB (plan S1 part 3): where this session's PLM is and who it
485    /// is signed in as, or why it is not; a token paste and a password
486    /// sign-in; a check; and Forget. Hit keys `plm:*`.
487    fn plm_section(&mut self, ui: &mut egui::Ui) {
488        use crate::plm::connection::{Keep, Outcome, Status};
489        let Some(plm) = self.plm.as_mut() else { return };
490        if plm.poll() || plm.busy() {
491            ui.ctx().request_repaint();
492        }
493        if plm.take_reload() {
494            reload_page();
495        }
496        let hits = &mut self.hits;
497        let status = match &plm.status {
498            Status::Connected { url, username } => format!("Connected to {url} as {username}."),
499            Status::NotConnected { url, reason: None } => format!("Not connected to {url}."),
500            Status::NotConnected {
501                url,
502                reason: Some(why),
503            } => format!("Not connected to {url}: {why}"),
504        };
505        let shown = ui.add(egui::Label::new(status).wrap());
506        hits.insert("plm:status".into(), shown.rect);
507        ui.separator();
508        // A plm.json that names no usable server: the field above is the fix,
509        // and nothing below has a server to ask.
510        if plm.url().is_empty() {
511            return;
512        }
513
514        let native = matches!(plm.keep(), Keep::Files(_));
515        let idle = !plm.busy();
516        if native {
517            browser_sign_in(ui, plm, hits, idle);
518            ui.separator();
519            // The fallback, for a machine with no browser (or a person who
520            // would rather type): a pasted token, or a password traded for one.
521            let here = egui::CollapsingHeader::new("Sign in here instead")
522                .id_salt("plm-sign-in-here")
523                .default_open(false)
524                .show(ui, |ui| {
525                    ui.label("Paste an API token (from the PLM's web page):");
526                    let token = ui.add(
527                        egui::TextEdit::singleline(&mut plm.token_input)
528                            .password(true)
529                            .hint_text("plm_…"),
530                    );
531                    hits.insert("plm:token".into(), token.rect);
532                    let use_token = ui.add_enabled(
533                        idle && !plm.token_input.trim().is_empty(),
534                        egui::Button::new("Use token"),
535                    );
536                    hits.insert("plm:use-token".into(), use_token.rect);
537                    if use_token.clicked() {
538                        plm.use_token();
539                    }
540                    ui.separator();
541                    ui.label("Or sign in, and this machine keeps a token (not the password):");
542                    let username =
543                        ui.add(egui::TextEdit::singleline(&mut plm.username).hint_text("username"));
544                    hits.insert("plm:username".into(), username.rect);
545                    let password = ui.add(
546                        egui::TextEdit::singleline(&mut plm.password)
547                            .password(true)
548                            .hint_text("password"),
549                    );
550                    hits.insert("plm:password".into(), password.rect);
551                    let can_sign_in =
552                        idle && !plm.username.trim().is_empty() && !plm.password.is_empty();
553                    let sign_in = ui.add_enabled(can_sign_in, egui::Button::new("Sign in"));
554                    hits.insert("plm:sign-in".into(), sign_in.rect);
555                    if sign_in.clicked() {
556                        plm.use_password();
557                    }
558                });
559            hits.insert("plm:sign-in-here".into(), here.header_response.rect);
560            ui.separator();
561        } else {
562            ui.label("This browser uses your PLM session. Manage your account and sign in on the PLM page.");
563            let account = ui.hyperlink_to(
564                "Open PLM account",
565                format!("{}/#/account", plm.url().trim_end_matches('/')),
566            );
567            hits.insert("plm:account".into(), account.rect);
568        }
569        // Connect now (native): once the server has taken this machine's
570        // sign-in, switch this session to it live instead of at next start
571        // (only in the state a fresh start has: no named or dirty document).
572        if native && matches!(plm.status, Status::NotConnected { .. }) && plm.connectable() {
573            let blocked = self.reconnect_blocker.clone();
574            let connect =
575                ui.add_enabled(idle && blocked.is_none(), egui::Button::new("Connect now"));
576            hits.insert("plm:connect".into(), connect.rect);
577            if let Some(why) = &blocked {
578                ui.label(egui::RichText::new(why).color(PROBLEM_AMBER));
579            }
580            if connect.clicked() {
581                if let Keep::Files(root) = plm.keep() {
582                    self.reconnect_request = Some(root.clone());
583                }
584            }
585        }
586        ui.horizontal(|ui| {
587            let check = ui.add_enabled(idle, egui::Button::new("Check connection"));
588            hits.insert("plm:check".into(), check.rect);
589            if check.clicked() {
590                plm.check();
591            }
592            if native {
593                let forget =
594                    ui.add_enabled(idle, egui::Button::new("Forget this machine's sign-in"));
595                hits.insert("plm:forget".into(), forget.rect);
596                if forget.clicked() {
597                    plm.forget();
598                }
599            }
600        });
601        if !idle {
602            ui.horizontal(|ui| {
603                ui.spinner();
604                ui.label("Asking the server…");
605            });
606        }
607        if let Some(outcome) = &plm.last {
608            let (text, color) = match outcome {
609                Outcome::Done(text) => (text.clone(), ui.visuals().text_color()),
610                Outcome::Failed(text) => (text.clone(), PROBLEM_AMBER),
611            };
612            let said = ui.add(egui::Label::new(egui::RichText::new(text).color(color)).wrap());
613            hits.insert("plm:outcome".into(), said.rect);
614        }
615    }
616
617    /// The `Assemblies` TAB: the BOM's COLUMN CONFIGURATION as one multiline
618    /// textarea, one column per line, a leading `*` for shown.
619    ///
620    /// A hand-written root rather than a schema field: the schema's `FieldKind`s
621    /// are all
622    /// single-widget and render into a tree row's RIGHT-ALIGNED content slot,
623    /// which is exactly the wrong place for a full-width multi-line editor.
624    /// Adding a `TextArea` variant would also force both exhaustive
625    /// `FieldKind` matches open for one consumer.
626    ///
627    /// Commits on focus-LOSS — which includes LEAVING THE TAB, since [`body`]
628    /// draws the pre-click tab for one more frame so this editor is still on
629    /// screen to blur ([`SettingsPanel::body`]) — not per keystroke: this text is
630    /// persisted to the store on commit, and on native that is a rewrite of
631    /// `~/.config/brep-app/settings.json` — per character is a file write per
632    /// character. Parse problems are listed under the editor, naming the line,
633    /// and the text is never rewritten by the panel: a typo costs one column,
634    /// not the configuration.
635    fn assemblies_section(
636        &mut self,
637        ui: &mut egui::Ui,
638        state: &mut EngineState,
639        store: &dyn ModelStore,
640    ) {
641        let open = !self.assemblies_collapsed;
642        let root_resp = tree::node(
643            ui,
644            TreeRow {
645                guides: &[],
646                is_last: true,
647                expandable: true,
648                expanded: open,
649                root: true,
650                glyph: None,
651                label: "Assemblies",
652                selected: false,
653                highlighted: false,
654                draggable: false,
655                tint: None,
656            },
657            |_| {},
658        );
659        self.hits.insert("box:__assemblies".into(), root_resp.box_rect);
660        if root_resp.toggled || root_resp.clicked() {
661            self.assemblies_collapsed = !self.assemblies_collapsed;
662        }
663        if !open {
664            // Drop the buffer while closed so the next open re-seeds from the
665            // engine (a BOM header drag rewrites this text behind the panel).
666            self.bom_columns_buf = None;
667            return;
668        }
669
670        // Empty stored text means "the shipped default", so the editor shows
671        // the default rather than a blank box the user has to guess at.
672        let stored = bom_columns::effective_text(&state.settings.bom_columns);
673        let buffer = self.bom_columns_buf.get_or_insert_with(|| stored.clone());
674
675        ui.label(egui::RichText::new("BOM columns").strong());
676        ui.label(
677            egui::RichText::new(
678                "One per line, in order. A leading * shows it. \
679                 part.<Field> is stored on the part, occurrence.<Field> on one placement. \
680                 A line that is just - freezes the columns above it; the rest scroll.",
681            )
682            .weak(),
683        );
684        let editor = ui.add(
685            egui::TextEdit::multiline(buffer)
686                .id_salt("bom-columns-editor")
687                .desired_rows(8)
688                .desired_width(f32::INFINITY)
689                .code_editor(),
690        );
691        self.hits.insert("field:bomColumns".into(), editor.rect);
692
693        if editor.lost_focus() {
694            // Commit: store the text VERBATIM (never the parse's idea of it).
695            let mut settings_json: serde_json::Value =
696                serde_json::from_str(&state.settings_json()).unwrap_or(serde_json::Value::Null);
697            if let Some(object) = settings_json.as_object_mut() {
698                object.insert(
699                    "bomColumns".into(),
700                    serde_json::Value::String(buffer.clone()),
701                );
702                let json = settings_json.to_string();
703                let _ = state.apply_settings_json(&json);
704                let _ = store.write(SETTINGS_KEY, &json);
705            }
706        } else if !editor.has_focus() && *buffer != stored {
707            // Unfocused and out of step with the engine — the BOM's own header
708            // drag rewrote the configuration. Track it rather than showing a
709            // stale copy the next commit would write back.
710            *buffer = stored;
711        }
712
713        // Parse problems, by line. Listed rather than thrown: the text stands
714        // exactly as typed and every other line still works.
715        let parsed = bom_columns::parse(buffer);
716        if parsed.problems.is_empty() {
717            ui.label(
718                egui::RichText::new(format!(
719                    "{} columns, {} shown",
720                    parsed.columns.len(),
721                    parsed.columns.iter().filter(|column| column.shown).count()
722                ))
723                .weak(),
724            );
725        } else {
726            for problem in &parsed.problems {
727                ui.label(egui::RichText::new(problem).color(PROBLEM_AMBER));
728            }
729        }
730        let reset = ui.button("Reset BOM columns");
731        self.hits.insert("bom-columns:reset".into(), reset.rect);
732        if reset.clicked() {
733            self.bom_columns_buf = None;
734            let mut settings_json: serde_json::Value =
735                serde_json::from_str(&state.settings_json()).unwrap_or(serde_json::Value::Null);
736            if let Some(object) = settings_json.as_object_mut() {
737                // Back to EMPTY, which means "the shipped default" — so a later
738                // change to that default still reaches this user.
739                object.insert("bomColumns".into(), serde_json::Value::String(String::new()));
740                let json = settings_json.to_string();
741                let _ = state.apply_settings_json(&json);
742                let _ = store.write(SETTINGS_KEY, &json);
743            }
744        }
745        ui.add_space(4.0);
746    }
747
748    /// The schema-driven display-settings TREE: a `Display settings` root, one
749    /// collapsible branch per schema group, one leaf per field. Any edit applies to
750    /// `EngineState` (bumps `settings_generation` + `dirty`, so the GPU refreshes)
751    /// and persists through the storage seam.
752    fn settings_section(
753        &mut self,
754        ui: &mut egui::Ui,
755        state: &mut EngineState,
756        store: &dyn ModelStore,
757    ) {
758        // Re-seed a per-frame LOCAL buffer from the LIVE engine settings BEFORE
759        // rendering. The apply below writes the WHOLE buffer, so a buffer kept
760        // across frames would clobber every setting changed elsewhere (the toolbar
761        // wireframe / projection toggles) back to a stale snapshot — the "changing
762        // Render Quality resets my wireframe" bug. A fresh local each frame makes
763        // external changes authoritative and keeps untouched fields a no-op
764        // round-trip (`apply_json`/`to_json` are a documented identity).
765        let before = state.settings_json();
766        let mut settings_json: Value = serde_json::from_str(&before).unwrap_or(Value::Null);
767        let fields = settings_form_fields();
768
769        // Group the schema's contiguous same-group runs, preserving order (the
770        // schema lists each group's fields together).
771        let mut groups: Vec<(String, Vec<&FormField>)> = Vec::new();
772        for f in &fields {
773            if let Some(g) = groups.iter_mut().find(|(n, _)| *n == f.group) {
774                g.1.push(f);
775            } else {
776                groups.push((f.group.clone(), vec![f]));
777            }
778        }
779
780        // --- ROOT: `[-] Display settings` (defaults open) ---------------------
781        let root_open = !self.display_collapsed;
782        let root_resp = tree::node(
783            ui,
784            TreeRow {
785                guides: &[],
786                is_last: true,
787                expandable: true,
788                expanded: root_open,
789                root: true,
790                glyph: None,
791                label: "Display settings",
792                selected: false,
793                highlighted: false,
794                draggable: false,
795                tint: None,
796            },
797            |_| {},
798        );
799        if root_resp.toggled || root_resp.clicked() {
800            self.display_collapsed = !self.display_collapsed;
801        }
802
803        let mut changed = false;
804        if root_open {
805            let n = groups.len();
806            for (gi, (gname, gfields)) in groups.iter().enumerate() {
807                let is_last = gi + 1 == n;
808                let open = !self.closed_groups.contains(gname);
809                let resp = tree::node(ui, TreeRow::branch(&[], is_last, open, gname), |_| {});
810                self.hits.insert(format!("group:{gname}"), resp.box_rect);
811                if resp.toggled || resp.clicked() {
812                    if open {
813                        self.closed_groups.insert(gname.clone());
814                    } else {
815                        self.closed_groups.remove(gname);
816                    }
817                }
818                if !open {
819                    continue;
820                }
821                let base = tree::child_guides(&[], is_last);
822                let m = gfields.len();
823                for (fi, &f) in gfields.iter().enumerate() {
824                    changed |= self.settings_leaf(ui, f, &mut settings_json, &base, fi + 1 == m);
825                }
826            }
827        }
828
829        // Commit the whole buffer ONCE on any edit (same apply + persist path as
830        // before), so the engine re-runs / the GPU refreshes exactly as it did.
831        //
832        // ...and only when the settings actually MOVED. Some field reports a
833        // change on every frame the tree is drawn, and the write it caused went
834        // unnoticed on a file store (one settings.json rewrite per frame) until
835        // the PLM made each one a request: with the window open the store was
836        // never idle. Comparing through the engine's own serialisation makes a
837        // no-op edit a no-op whichever widget claims otherwise.
838        if changed {
839            let json = settings_json.to_string();
840            let _ = state.apply_settings_json(&json);
841            if state.settings_json() != before {
842                let _ = store.write(SETTINGS_KEY, &json);
843            }
844        }
845
846        // Reset to defaults — only while the display root is OPEN, matching the
847        // retired CollapsingHeader that hid it when the section was collapsed. It
848        // resets the DISPLAY settings only, which is why it belongs to this tab.
849        if root_open {
850            ui.add_space(2.0);
851            if ui.button("Reset to defaults").clicked() {
852                // Full reset: rebase to defaults, then apply the serialized defaults
853                // (so every key returns, not just the overridden ones) + persist.
854                state.settings = RenderSettings::default();
855                let json = state.settings.to_json();
856                let _ = state.apply_settings_json(&json);
857                let _ = store.write(SETTINGS_KEY, &json);
858            }
859        }
860    }
861
862    /// Render one settings field as a tree LEAF: the field label is the node label;
863    /// its input widget ([`form::field_input`]) fills the row's RIGHT-aligned
864    /// content, exactly like the feature tree's `schema_field`. Settings keys are
865    /// unique across the schema, so no id-stack scoping is needed. Returns whether
866    /// the field changed (the caller commits the whole buffer once).
867    fn settings_leaf(
868        &mut self,
869        ui: &mut egui::Ui,
870        field: &FormField,
871        current: &mut Value,
872        guides: &[bool],
873        is_last: bool,
874    ) -> bool {
875        let mut changed = false;
876        let mut rect = egui::Rect::NOTHING;
877        tree::node(ui, TreeRow::leaf(guides, is_last, &field.label), |ui| {
878            // The tree row's content area is RIGHT-aligned (`right_to_left`), so the
879            // input sits at the panel edge with the label on the left — the feature
880            // tree's exact placement, and the layout `field_input` reads to keep its
881            // inputs COMPACT here. Settings have no reference / button fields, so
882            // `field_input`'s click sink is `None`.
883            let (ch, r) = form::field_input(ui, field, current, None, &mut form::FieldActions::default());
884            changed = ch;
885            rect = r;
886        });
887        self.hits.insert(format!("field:{}", field.key()), rect);
888        changed
889    }
890
891    /// The published widget hit-rects (egui points) for the headed verifier.
892    pub fn hits_json(&self) -> String {
893        crate::automation::hit_rects::hits_json(&self.hits)
894    }
895}
896
897
898/// The PLM tab's browser sign-in (native): one button, then "Continue in your
899/// browser" with the code the page will show, the link to copy when no browser
900/// opened, and Cancel. The link page opens through `open_url`: eframe hands it
901/// to the default browser, and the headless automation host opens nothing. Hit keys `plm:browser-sign-in`, `plm:link-code`,
902/// `plm:link-url`, `plm:copy-link`, `plm:cancel-link`.
903fn browser_sign_in(
904    ui: &mut egui::Ui,
905    plm: &mut crate::plm::connection::PlmConnection,
906    hits: &mut HashMap<String, egui::Rect>,
907    idle: bool,
908) {
909    if let Some(url) = plm.take_open_request() {
910        ui.ctx().open_url(egui::OpenUrl::new_tab(url));
911    }
912    if let Some(wait) = plm.link_wait() {
913        ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(wait.max(0.05)));
914    }
915    let Some(link) = &plm.link else {
916        if plm.linking() {
917            ui.horizontal(|ui| {
918                ui.spinner();
919                ui.label("Starting the sign-in…");
920            });
921            return;
922        }
923        ui.label("Sign in with your PLM account in your web browser. This machine keeps a token, never your password.");
924        let start = ui.add_enabled(idle, egui::Button::new("Sign in with your browser"));
925        hits.insert("plm:browser-sign-in".into(), start.rect);
926        if start.clicked() {
927            plm.sign_in_with_browser();
928        }
929        return;
930    };
931    ui.strong("Continue in your browser");
932    ui.label("Approve the sign-in on the PLM page that opened in your browser. It shows this code:");
933    let code = ui.label(egui::RichText::new(&link.code).monospace().size(22.0).strong());
934    hits.insert("plm:link-code".into(), code.rect);
935    ui.label("No browser page? Copy this link into a browser:");
936    let url = ui.add(egui::Label::new(egui::RichText::new(&link.url).small().weak()).wrap().selectable(true));
937    hits.insert("plm:link-url".into(), url.rect);
938    let (url_text, note) = (link.url.clone(), link.note.clone());
939    ui.horizontal(|ui| {
940        let copy = ui.button("Copy link");
941        hits.insert("plm:copy-link".into(), copy.rect);
942        if copy.clicked() {
943            ui.ctx().copy_text(url_text);
944        }
945        let cancel = ui.button("Cancel");
946        hits.insert("plm:cancel-link".into(), cancel.rect);
947        if cancel.clicked() {
948            plm.cancel_link();
949        }
950    });
951    if let Some(note) = note {
952        ui.label(egui::RichText::new(note).color(PROBLEM_AMBER));
953    }
954    if plm.link.is_some() {
955        ui.horizontal(|ui| {
956            ui.spinner();
957            ui.label("Waiting for the approval…");
958        });
959    }
960}
961
962/// Reload the page onto the PLM session a web sign-in (or sign-out) made.
963fn reload_page() {
964    #[cfg(target_arch = "wasm32")]
965    if let Some(window) = web_sys::window() {
966        let _ = window.location().reload();
967    }
968}
969
970/// The hit keys this panel publishes (see `automation::hit_keys`).
971pub static HIT_KEYS: &[HitKeyDoc] = &[
972    HitKeyDoc { panel: "settings", prefix: "field:", meaning: "a settings field by key", command: None },
973    HitKeyDoc { panel: "settings", prefix: "group:", meaning: "a settings group header", command: None },
974    HitKeyDoc { panel: "settings", prefix: "tab:", meaning: "a settings tab (tab:display, tab:assemblies, tab:plm — the PLM tab is in every session)", command: None },
975    HitKeyDoc { panel: "settings", prefix: "plm:", meaning: "the PLM tab: url (the Server URL field, committed on Enter or focus loss into plm.json), url-source, url-outcome; status, check, outcome; hosted account; desktop token, use-token, username, password, sign-in, forget", command: None },
976    HitKeyDoc { panel: "settings", prefix: "box:", meaning: "expand/collapse a section", command: None },
977    HitKeyDoc { panel: "settings", prefix: "bom-columns:reset", meaning: "reset the BOM columns", command: None },
978    HitKeyDoc { panel: "settings", prefix: "panel:clip", meaning: "the visible region of the window", command: None },
979];