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
48const PROBLEM_AMBER: egui::Color32 = egui::Color32::from_rgb(0xff, 0x9f, 0x0a);
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub enum Tab {
57 Display,
59 Assemblies,
61 Plm,
65}
66
67pub struct SettingsPanel {
71 pub open: bool,
75 hits: HashMap<String, egui::Rect>,
79 settings_unwritten: bool,
83 tab: Tab,
86 display_collapsed: bool,
88 closed_groups: HashSet<String>,
91 assemblies_collapsed: bool,
93 bom_columns_buf: Option<String>,
99 plm: Option<crate::plm::connection::PlmConnection>,
102 url_buf: Option<(String, Option<String>)>,
106 url_outcome: Option<crate::plm::connection::Outcome>,
110 pub reconnect_blocker: Option<String>,
113 pub reconnecting: bool,
116 reconnect_request: Option<std::path::PathBuf>,
118 signed_out: Option<String>,
122}
123
124impl SettingsPanel {
125 pub fn show_plm_tab(&mut self) {
128 self.open = true;
129 self.tab = Tab::Plm;
130 }
131
132 pub fn ask_plm_sign_in(&mut self, why: String) {
135 self.signed_out = Some(why);
136 self.show_plm_tab();
137 }
138
139 pub fn take_fresh_plm_token(&mut self) -> Option<(String, String)> {
143 let fresh = self.plm.as_mut()?.take_fresh_token()?;
144 self.signed_out = None;
145 Some(fresh)
146 }
147
148 pub fn take_plm_signed_out_here(&mut self) -> bool {
151 if !self.plm.as_mut().is_some_and(|plm| plm.take_signed_out_here()) {
152 return false;
153 }
154 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());
155 true
156 }
157
158 pub fn plm_signed_out(&self) -> bool {
160 self.signed_out.is_some()
161 }
162
163 pub fn new() -> Self {
166 Self {
167 open: false,
168 hits: HashMap::new(),
169 settings_unwritten: false,
170 tab: Tab::Display,
171 display_collapsed: false,
172 closed_groups: HashSet::new(),
173 assemblies_collapsed: false,
174 bom_columns_buf: None,
175 plm: None,
176 url_buf: None,
177 url_outcome: None,
178 reconnect_blocker: None,
179 reconnecting: false,
180 reconnect_request: None,
181 signed_out: None,
182 }
183 }
184
185 pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
190 if self.open {
191 let mut open = true;
194 egui::Window::new("Settings")
195 .open(&mut open)
196 .movable(true)
197 .resizable(true)
198 .default_size([460.0, 480.0])
203 .default_pos(super::below_chrome(ctx, 720.0, 0.0))
206 .show(ctx, |ui| self.body(ui, state, store));
207 self.open = open;
208 } else {
209 self.hits.clear();
217 }
218
219 if crate::automation::registry::enabled() {
222 crate::automation::registry::publish("__brepSettingsHit", "settings window widget rects (field:*, group:*, panel:clip); empty while the window is closed", &self.hits_json());
223 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));
224 }
225 }
226
227 fn body(&mut self, ui: &mut egui::Ui, state: &mut EngineState, store: &dyn ModelStore) {
235 self.hits.clear();
236 self.hits.insert("panel:clip".into(), ui.clip_rect());
247
248 self.sync_plm(store.plm_session());
257 let tab = self.tab;
258 ui.horizontal(|ui| {
259 let display = ui.selectable_value(&mut self.tab, Tab::Display, "Display");
260 let assemblies = ui.selectable_value(&mut self.tab, Tab::Assemblies, "Assemblies");
261 self.hits.insert("tab:display".into(), display.rect);
262 self.hits.insert("tab:assemblies".into(), assemblies.rect);
263 let plm = ui.selectable_value(&mut self.tab, Tab::Plm, "PLM");
264 self.hits.insert("tab:plm".into(), plm.rect);
265 });
266 if self.tab != tab {
272 ui.ctx().request_repaint();
273 }
274 ui.separator();
275
276 egui::ScrollArea::vertical()
277 .auto_shrink([false, false])
278 .show(ui, |ui| {
279 ui.spacing_mut().item_spacing.y = 2.0;
284 match tab {
285 Tab::Display => self.settings_section(ui, state, store),
286 Tab::Assemblies => self.assemblies_section(ui, state, store),
287 Tab::Plm => {
288 self.plm_url_section(ui, store);
289 self.plm_section(ui);
290 }
291 }
292 });
293 }
294
295 fn plm_json(&mut self, store: &dyn ModelStore) -> String {
298 use crate::plm::connection::{Outcome, Status};
299 self.sync_plm(store.plm_session());
300 let setting = store.plm_url_setting();
301 let (url_outcome, url_failed) = match &self.url_outcome {
302 Some(Outcome::Done(text)) => (Some(text.clone()), false),
303 Some(Outcome::Failed(text)) => (Some(text.clone()), true),
304 None => (None, false),
305 };
306 let field = serde_json::json!({
307 "serverUrl": setting.as_ref().and_then(|s| s.url.clone()),
308 "urlSource": setting.as_ref().and_then(|s| s.source).map(crate::plm::config::url_origin),
309 "urlEditable": setting.is_some(),
310 "urlField": self.url_buf.as_ref().map(|(buf, _)| buf.clone()),
311 "urlOutcome": url_outcome, "urlFailed": url_failed,
312 });
313 let Some(plm) = self.plm.as_mut() else {
314 let mut json = serde_json::json!({ "tab": true, "status": "not-configured", "url": null });
315 json.as_object_mut().expect("an object").extend(field.as_object().expect("an object").clone());
316 return json.to_string();
317 };
318 plm.poll();
319 let (status, url, username, reason) = match &plm.status {
320 Status::Connected { url, username } => ("connected", url.clone(), Some(username.clone()), None),
321 Status::NotConnected { url, reason } => ("not-connected", url.clone(), None, reason.clone()),
322 };
323 let (outcome, failed) = match &plm.last {
324 Some(Outcome::Done(text)) => (Some(text.clone()), false),
325 Some(Outcome::Failed(text)) => (Some(text.clone()), true),
326 None => (None, false),
327 };
328 let mut json = serde_json::json!({
329 "tab": true, "status": status, "url": url, "username": username, "reason": reason,
330 "busy": plm.busy(), "outcome": outcome, "failed": failed,
331 "connectable": plm.connectable(), "reconnectBlocker": self.reconnect_blocker,
332 "connecting": self.reconnecting,
333 "linking": plm.linking(),
334 "linkCode": plm.link.as_ref().map(|l| l.code.clone()),
335 "linkUrl": plm.link.as_ref().map(|l| l.url.clone()),
336 "linkToken": plm.link.as_ref().and_then(|l| l.url.split_once("token=").map(|(_, t)| t.to_string())),
338 "linkNote": plm.link.as_ref().and_then(|l| l.note.clone()),
339 });
340 json.as_object_mut().expect("an object").extend(field.as_object().expect("an object").clone());
341 json.to_string()
342 }
343
344 pub fn take_reconnect_request(&mut self) -> Option<std::path::PathBuf> {
346 self.reconnect_request.take()
347 }
348
349 pub fn reconnected(&mut self, outcome: Result<String, String>) {
351 if let Some(plm) = self.plm.as_mut() {
352 plm.reconnected(outcome);
353 }
354 }
355
356 fn sync_plm(&mut self, session: Option<crate::plm::connection::Session>) {
358 use crate::plm::connection::PlmConnection;
359 let Some(session) = session else {
360 self.plm = None;
361 return;
362 };
363 let url = match &session.status {
364 crate::plm::connection::Status::Connected { url, .. } | crate::plm::connection::Status::NotConnected { url, .. } => url.clone(),
365 };
366 let same = self.plm.as_ref().is_some_and(|c| c.url() == url && *c.keep() == session.keep);
367 let status = match (&self.signed_out, session.status) {
369 (Some(why), crate::plm::connection::Status::Connected { url, .. }) => {
370 crate::plm::connection::Status::NotConnected { url, reason: Some(why.clone()) }
371 }
372 (_, status) => status,
373 };
374 match self.plm.as_mut().filter(|_| same) {
375 Some(plm) => plm.set_status(status),
377 None => self.plm = Some(PlmConnection::new(status, session.keep)),
378 }
379 }
380
381 fn plm_url_section(&mut self, ui: &mut egui::Ui, store: &dyn ModelStore) {
387 use crate::plm::config::{url_origin, Source};
388 use crate::plm::connection::{Outcome, Status};
389 let setting = store.plm_url_setting();
390 let editable = setting.is_some();
391 let shown = match &setting {
393 Some(setting) => setting.url.clone(),
394 None => self.plm.as_ref().map(|plm| plm.url().to_string()).filter(|url| !url.is_empty()),
395 };
396 let source = setting.as_ref().and_then(|s| s.source);
397 if self.url_buf.as_ref().is_none_or(|(_, from)| *from != shown) {
398 self.url_buf = Some((shown.clone().unwrap_or_default(), shown.clone()));
399 }
400
401 tree::node(
402 ui,
403 TreeRow {
404 guides: &[],
405 is_last: true,
406 expandable: false,
407 expanded: true,
408 root: true,
409 glyph: None,
410 label: "PLM server",
411 selected: false,
412 highlighted: false,
413 draggable: false,
414 tint: None,
415 },
416 |_| {},
417 );
418 let mut committed = false;
419 let mut rect = egui::Rect::NOTHING;
420 let (buf, _) = self.url_buf.as_mut().expect("seeded above");
421 tree::node(ui, TreeRow::leaf(&[], true, "Server URL"), |ui| {
422 ui.add_enabled_ui(editable, |ui| {
423 let width = form::text_input_width(ui);
424 let field = form::text_input(ui, buf, width);
425 committed = field.lost_focus();
426 rect = field.rect;
427 });
428 });
429 self.hits.insert("plm:url".into(), rect);
430
431 if committed && editable {
432 let typed = buf.trim().to_string();
433 if typed != shown.clone().unwrap_or_default() {
434 self.url_outcome = Some(if typed.is_empty() {
435 Outcome::Failed("an empty URL is not saved: Forget this machine's sign-in removes the server from this machine".into())
436 } else {
437 match store.save_plm_url(&typed) {
438 Err(why) => Outcome::Failed(format!("not saved: {why}")),
439 Ok(saved) => {
440 let mut said = format!("saved to plm.json: {}", saved.url);
441 if saved.token_dropped {
442 said += "; this machine's sign-in for the previous server is forgotten (a token is never sent to another server)";
443 }
444 match (source, self.plm.as_ref().map(|plm| &plm.status)) {
445 (Some(Source::Env | Source::Flag), _) => {
446 said += &format!(
447 "; this launch stays on {} ({} overrides plm.json), and a start without it uses {}",
448 shown.clone().unwrap_or_default(),
449 url_origin(source.expect("matched")),
450 saved.url
451 );
452 }
453 (_, Some(Status::Connected { url, .. })) if *url != saved.url => {
454 said += &format!("; this session stays on {url} until the next start");
455 }
456 _ => said += "; sign in below, then Connect now (or the next start) puts this session on it",
457 }
458 let from = store.plm_url_setting().and_then(|s| s.url);
461 self.url_buf = Some((saved.url.clone(), from));
462 Outcome::Done(said)
463 }
464 }
465 });
466 }
467 }
468
469 let note = match (&setting, source) {
470 (Some(_), Some(source @ (Source::Env | Source::Flag))) => format!(
471 "From {}, which overrides plm.json for this launch. A URL saved here is what a launch without it uses.",
472 url_origin(source)
473 ),
474 (Some(_), Some(Source::File)) => {
475 "From plm.json. Changing the server forgets this machine's sign-in: a token is never sent to a different server.".into()
476 }
477 (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(),
478 (None, _) if shown.is_some() => "The web app uses the PLM that serves this page.".into(),
479 (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(),
480 };
481 let said = ui.add(egui::Label::new(note).wrap());
482 self.hits.insert("plm:url-source".into(), said.rect);
483 if let Some(outcome) = &self.url_outcome {
484 let (text, color) = match outcome {
485 Outcome::Done(text) => (text.clone(), ui.visuals().text_color()),
486 Outcome::Failed(text) => (text.clone(), PROBLEM_AMBER),
487 };
488 let said = ui.add(egui::Label::new(egui::RichText::new(text).color(color)).wrap());
489 self.hits.insert("plm:url-outcome".into(), said.rect);
490 }
491 ui.separator();
492 }
493
494 fn plm_section(&mut self, ui: &mut egui::Ui) {
498 use crate::plm::connection::{Keep, Outcome, Status};
499 let Some(plm) = self.plm.as_mut() else { return };
500 if plm.poll() || plm.busy() {
501 ui.ctx().request_repaint();
502 }
503 if plm.take_reload() {
504 reload_page();
505 }
506 let hits = &mut self.hits;
507 let status = match &plm.status {
508 Status::Connected { url, username } => format!("Connected to {url} as {username}."),
509 Status::NotConnected { url, reason: None } => format!("Not connected to {url}."),
510 Status::NotConnected {
511 url,
512 reason: Some(why),
513 } => format!("Not connected to {url}: {why}"),
514 };
515 let shown = ui.add(egui::Label::new(status).wrap());
516 hits.insert("plm:status".into(), shown.rect);
517 ui.separator();
518 if plm.url().is_empty() {
521 return;
522 }
523
524 let native = matches!(plm.keep(), Keep::Files(_));
525 let idle = !plm.busy() && !self.reconnecting;
526 if native {
527 browser_sign_in(ui, plm, hits, idle);
528 ui.separator();
529 let here = egui::CollapsingHeader::new("Sign in here instead")
532 .id_salt("plm-sign-in-here")
533 .default_open(false)
534 .show(ui, |ui| {
535 ui.label("Paste an API token (from the PLM's web page):");
536 let token = ui.add(
537 egui::TextEdit::singleline(&mut plm.token_input)
538 .password(true)
539 .hint_text("plm_…"),
540 );
541 hits.insert("plm:token".into(), token.rect);
542 let use_token = ui.add_enabled(
543 idle && !plm.token_input.trim().is_empty(),
544 egui::Button::new("Use token"),
545 );
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 ui.add(egui::TextEdit::singleline(&mut plm.username).hint_text("username"));
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_enabled(can_sign_in, egui::Button::new("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_enabled(idle && blocked.is_none(), egui::Button::new("Connect now"));
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));
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_enabled(idle, egui::Button::new("Check connection"));
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_enabled(idle, egui::Button::new("Forget this machine's sign-in"));
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),
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));
744 }
745 }
746 let reset = ui.button("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.button("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.button("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_enabled(idle, egui::Button::new("Sign in with your browser"));
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.button("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.button("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));
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];