1use 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
48fn problem_amber(ui: &egui::Ui) -> egui::Color32 {
53 crate::theme::Theme::of(ui).colors.warning
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59pub enum Tab {
60 Display,
62 Assemblies,
64 Plm,
68}
69
70pub struct SettingsPanel {
74 pub open: bool,
78 hits: HashMap<String, egui::Rect>,
82 settings_unwritten: bool,
86 tab: Tab,
89 display_collapsed: bool,
91 closed_groups: HashSet<String>,
94 assemblies_collapsed: bool,
96 bom_columns_buf: Option<String>,
102 plm: Option<crate::plm::connection::PlmConnection>,
105 url_buf: Option<(String, Option<String>)>,
109 url_outcome: Option<crate::plm::connection::Outcome>,
113 pub reconnect_blocker: Option<String>,
116 pub reconnecting: bool,
119 reconnect_request: Option<std::path::PathBuf>,
121 signed_out: Option<String>,
125}
126
127impl SettingsPanel {
128 pub fn show_plm_tab(&mut self) {
131 self.open = true;
132 self.tab = Tab::Plm;
133 }
134
135 pub fn ask_plm_sign_in(&mut self, why: String) {
138 self.signed_out = Some(why);
139 self.show_plm_tab();
140 }
141
142 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 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 pub fn plm_signed_out(&self) -> bool {
163 self.signed_out.is_some()
164 }
165
166 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 pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
193 if self.open {
194 let mut open = true;
197 egui::Window::new("Settings")
198 .open(&mut open)
199 .movable(true)
200 .resizable(true)
201 .default_size([460.0, 480.0])
206 .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 self.hits.clear();
220 }
221
222 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 fn body(&mut self, ui: &mut egui::Ui, state: &mut EngineState, store: &dyn ModelStore) {
238 self.hits.clear();
239 self.hits.insert("panel:clip".into(), ui.clip_rect());
250
251 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 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 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 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 "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 pub fn take_reconnect_request(&mut self) -> Option<std::path::PathBuf> {
349 self.reconnect_request.take()
350 }
351
352 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 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 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 Some(plm) => plm.set_status(status),
380 None => self.plm = Some(PlmConnection::new(status, session.keep)),
381 }
382 }
383
384 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 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 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 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 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 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 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 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 self.bom_columns_buf = None;
683 return;
684 }
685
686 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 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 *buffer = stored;
727 }
728
729 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 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 fn settings_section(
769 &mut self,
770 ui: &mut egui::Ui,
771 state: &mut EngineState,
772 store: &dyn ModelStore,
773 ) {
774 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 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 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 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 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 if root_open {
878 ui.add_space(2.0);
879 if ui.add(crate::ui_kit::Button::new("Reset to defaults")).clicked() {
880 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 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 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 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(egui::RichText::new(&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 pub fn hits_json(&self) -> String {
943 crate::automation::hit_rects::hits_json(&self.hits)
944 }
945}
946
947
948fn 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
1012fn reload_page() {
1014 #[cfg(target_arch = "wasm32")]
1015 if let Some(window) = web_sys::window() {
1016 let _ = window.location().reload();
1017 }
1018}
1019
1020pub 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];