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