1mod detail;
69pub mod focus;
70pub mod quick;
71mod shell;
72pub mod store;
73mod sync;
74pub mod transfer;
75mod window;
76pub mod wizard;
77
78use std::collections::BTreeMap;
79use std::sync::{Arc, Mutex};
80
81use egui::Ui;
82use egui_pop_core::lock;
83use egui_pop_core::strings::StrKey;
84use egui_pop_model::admin::generate::{self, Entry};
85use egui_pop_model::admin::hooks::{Hook, Hooks};
86use egui_pop_model::admin::layers::Layers;
87use egui_pop_model::admin::{Manifest, Tree, ValueScope};
88use egui_pop_model::commands::{CommandSpec, Origin};
89use egui_pop_model::diagnostics::Diagnostics;
90use egui_pop_model::ids::{BlockId, CommandId, OwnerId, PluginId, SettingId};
91use egui_pop_model::values::{Change, Descriptor, Set, Value};
92use serde_json::{Value as Json, json};
93
94use crate::app::AppHandle;
95use crate::history::StoreScope;
96use crate::services::ServiceToken;
97use crate::zones::{self, Block};
98use crate::{Ctx, Plugin, PluginError};
99
100pub use egui_pop_model::admin as model;
101pub use wizard::{
102 CMD_WIZARD_BACK, CMD_WIZARD_CANCEL, CMD_WIZARD_FINISH, CMD_WIZARD_GO, CMD_WIZARD_NEXT,
103 CMD_WIZARD_OPEN, CMD_WIZARD_SET, CMD_WIZARD_SKIP,
104};
105
106pub const CMD_OPEN: CommandId = CommandId::from_static("admin.open");
108pub const CMD_CLOSE: CommandId = CommandId::from_static("admin.close");
110pub const WINDOW_LISTENER: &str = "pop.admin.window";
114pub const OWNER: &str = "egui_pop.admin";
116pub const CMD_POP_OUT: CommandId = CommandId::from_static("admin.popOut");
118pub const CMD_SET: CommandId = CommandId::from_static("admin.set");
120pub const CMD_RESET: CommandId = CommandId::from_static("admin.reset");
122
123pub const WINDOW: SettingId = SettingId::from_static("admin.window");
125
126pub const APP_WINDOW: &str = "settings";
130
131pub const ADMIN: ServiceToken<Admin> = ServiceToken::new("admin");
133
134#[derive(Clone, Copy, Debug, PartialEq, Eq)]
139pub struct ExtraScope {
140 pub scope: ValueScope,
141 pub label: StrKey,
144 pub about: StrKey,
147}
148
149impl ExtraScope {
150 pub const fn new(name: &'static str, label: StrKey, about: StrKey) -> ExtraScope {
151 ExtraScope {
152 scope: ValueScope::new(name),
153 label,
154 about,
155 }
156 }
157}
158
159pub const SURFACE: &str = "adminWindow";
162
163pub type WidgetKindFn = Arc<dyn Fn(&mut Ui, &AppHandle, &Json) + Send + Sync>;
166
167pub type WidgetSearchFn =
173 Arc<dyn Fn(&egui::Context, &AppHandle, &Json, &str) -> Vec<(String, String)> + Send + Sync>;
174
175#[derive(Debug, Default)]
176struct State {
177 open: bool,
178 scope: Option<String>,
179 section: Option<String>,
180 key: Option<String>,
182 row: Option<String>,
185 mark: Option<String>,
188 filter: String,
189 target: BTreeMap<String, ValueScope>,
191}
192
193#[derive(Default)]
198pub struct Admin {
199 state: Mutex<State>,
200 layers: Mutex<Layers>,
201 manifests: Mutex<Vec<Manifest>>,
202 hooks: Mutex<Hooks>,
203 widgets: Mutex<BTreeMap<String, WidgetKindFn>>,
204 searches: Mutex<BTreeMap<String, WidgetSearchFn>>,
205 diagnostics: Mutex<Diagnostics>,
206 reads: Mutex<Reads>,
207 kernel: Mutex<Option<Arc<crate::reads::ReadKernel>>>,
210 wizard: Mutex<Option<wizard::Running>>,
212 page_drawn: std::sync::atomic::AtomicBool,
215 finished: Mutex<Option<Json>>,
217 browsing: Mutex<Option<(String, crate::host::Pending)>>,
219 extra: Mutex<Vec<ExtraScope>>,
221 transfer: transfer::State,
223 sync: Mutex<sync::Synced>,
226 shared: Arc<sync::Shared>,
228 legacy: std::sync::atomic::AtomicBool,
231 recent: Mutex<Vec<(String, f64)>>,
234 quick: Mutex<BTreeMap<egui::ViewportId, quick::Open>>,
236 foci: Mutex<focus::Foci>,
238 texts: Mutex<Vec<StrKey>>,
240}
241
242#[derive(Debug, Default)]
248struct Reads {
249 answers: BTreeMap<String, Result<Json, String>>,
250 stale: BTreeMap<String, Result<Json, String>>,
253 asked: BTreeMap<String, (CommandId, Json, usize)>,
256 seq: Option<crate::host::Seq>,
258}
259
260fn read_key(command: &str, args: &Json) -> String {
261 format!("{command} {args}")
262}
263
264impl std::fmt::Debug for Admin {
265 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
266 f.debug_struct("Admin")
267 .field("state", &self.state)
268 .field("layers", &self.layers)
269 .finish_non_exhaustive()
270 }
271}
272
273impl Admin {
274 fn new() -> Admin {
275 Admin {
276 layers: Mutex::new(Layers::new()),
277 ..Admin::default()
278 }
279 }
280
281 pub fn is_open(&self) -> bool {
282 lock(&self.state).open
283 }
284
285 pub fn open(&self, app: &AppHandle, place: Option<&str>) -> Result<(), String> {
289 let asked = app.window_of_group(app.current_window_group());
290 self.asked_in(app, &asked);
291 if let Some(link) = place.filter(|p| !p.is_empty()) {
292 let tree = self.tree(app);
293 let p = tree
294 .resolve(link)
295 .ok_or_else(|| format!("no place `{link}` in the settings"))?;
296 let mut s = lock(&self.state);
297 s.scope = Some(p.scope);
298 s.section = p.section;
299 s.row = None;
300 s.mark.clone_from(&p.key);
301 s.key = p.key;
302 s.filter.clear();
303 }
304 lock(&self.state).open = true;
305 self.refresh();
306 window::settle(app, self, true);
308 Ok(())
309 }
310
311 pub(crate) fn note_page_drawn(&self) {
313 self.page_drawn
314 .store(true, std::sync::atomic::Ordering::Relaxed);
315 }
316
317 pub(crate) fn take_page_drawn(&self) -> bool {
319 self.page_drawn
320 .swap(false, std::sync::atomic::Ordering::Relaxed)
321 }
322
323 pub fn close(&self, app: &AppHandle) {
327 if window::held(app) {
328 window::close(app);
329 }
330 self.close_state();
331 }
332
333 fn close_state(&self) {
336 let mut run = lock(&self.wizard);
338 if run.as_ref().is_some_and(|r| r.sheet.is_none()) {
339 run.take();
340 }
341 drop(run);
342 let mut s = lock(&self.state);
343 s.open = false;
344 s.filter.clear();
345 s.mark = None;
346 }
347
348 pub fn shown(&self) -> (Option<String>, Option<String>, String) {
350 let s = lock(&self.state);
351 (s.scope.clone(), s.section.clone(), s.filter.clone())
352 }
353
354 pub fn manifest(&self, manifest: Manifest) {
357 lock(&self.manifests).push(manifest);
358 }
359
360 pub fn texts(&self, keys: &[StrKey]) {
367 let mut t = lock(&self.texts);
368 for k in keys {
369 if !t.contains(k) {
370 t.push(*k);
371 }
372 }
373 }
374
375 pub(crate) fn text_key(&self, text: &str) -> Option<StrKey> {
377 lock(&self.texts)
378 .iter()
379 .find(|k| k.fallback == text)
380 .copied()
381 }
382
383 pub fn hook(&self, name: &str, hook: Hook) -> bool {
385 lock(&self.hooks).register(name, hook)
386 }
387
388 pub fn widget_kind(
393 &self,
394 id: &str,
395 draw: impl Fn(&mut Ui, &AppHandle, &Json) + Send + Sync + 'static,
396 ) {
397 lock(&self.widgets).insert(id.into(), Arc::new(draw));
398 }
399
400 pub(crate) fn widget(&self, id: &str) -> Option<WidgetKindFn> {
401 lock(&self.widgets).get(id).cloned()
402 }
403
404 pub fn widget_search(
409 &self,
410 kind: &str,
411 search: impl Fn(&egui::Context, &AppHandle, &Json, &str) -> Vec<(String, String)>
412 + Send
413 + Sync
414 + 'static,
415 ) {
416 lock(&self.searches).insert(kind.into(), Arc::new(search));
417 }
418
419 pub(crate) fn search_of(&self, kind: &str) -> Option<WidgetSearchFn> {
420 lock(&self.searches).get(kind).cloned()
421 }
422
423 pub fn marked(&self) -> Option<String> {
426 lock(&self.state).mark.clone()
427 }
428
429 pub fn take_key(&self, key: &str) -> bool {
432 let mut s = lock(&self.state);
433 if s.key.as_deref() == Some(key) {
434 s.key = None;
435 true
436 } else {
437 false
438 }
439 }
440
441 pub(crate) fn key_is(&self, key: &str) -> bool {
443 lock(&self.state).key.as_deref() == Some(key)
444 }
445
446 pub(crate) fn hooks(&self) -> std::sync::MutexGuard<'_, Hooks> {
447 lock(&self.hooks)
448 }
449
450 pub fn diagnostics(&self) -> Diagnostics {
452 lock(&self.diagnostics).clone()
453 }
454
455 pub fn tree(&self, app: &AppHandle) -> Tree {
458 let entries = app.settings();
459 let mut manifests = lock(&self.manifests).clone();
460 if app
463 .service(&crate::settings_window::SETTINGS_WINDOW)
464 .is_some()
465 {
466 manifests.insert(0, crate::settings_window::admin_manifest(app));
467 }
468 let placed: std::collections::BTreeSet<&str> =
469 manifests.iter().flat_map(|m| m.bound_settings()).collect();
470 let mut tree = Tree::default();
471 tree.merge(generate::settings(
472 entries
473 .iter()
474 .filter(|e| !placed.contains(e.id.as_str()))
475 .map(|e| Entry {
476 id: e.id.as_str(),
477 section: &e.section,
478 }),
479 ));
480 let mut d = Diagnostics::new();
481 let mut scopes: Vec<String> = tree.scopes.iter().map(|s| s.meta.id.clone()).collect();
482 for m in &manifests {
483 scopes.extend(m.scopes.iter().map(|s| s.meta.id.clone()));
484 }
485 let exists = |id: &str| entries.iter().any(|e| e.id.as_str() == id);
486 for mut m in manifests {
487 if m.version > model::FORMAT {
488 d.warn(
489 "admin-newer",
490 None,
491 "manifest",
492 format!(
493 "manifest format {} is newer than {}: left out",
494 m.version,
495 model::FORMAT
496 ),
497 );
498 continue;
499 }
500 for x in m.check(&scopes, &exists).all() {
501 d.push_quiet(x.clone());
502 }
503 tree.merge(m);
504 }
505 let mut m = transfer::manifest(self, app, &tree);
508 for x in m.check(&scopes, &exists).all() {
509 d.push_quiet(x.clone());
510 }
511 tree.merge(m);
512 let mut last = lock(&self.diagnostics);
515 for x in tree.order_diagnostics() {
516 if last.all().contains(x) {
517 d.push_quiet(x.clone());
518 } else {
519 d.push(x.clone());
520 }
521 }
522 *last = d;
523 drop(last);
524 tree
525 }
526
527 pub fn layers(&self) -> Layers {
529 lock(&self.layers).clone()
530 }
531
532 pub fn declare_scope(&self, extra: ExtraScope) {
537 let mut d = lock(&self.extra);
538 match d.iter_mut().find(|x| x.scope == extra.scope) {
539 Some(x) => *x = extra,
540 None => d.push(extra),
541 }
542 lock(&self.layers).declare(extra.scope);
543 }
544
545 pub fn extra_scopes(&self) -> Vec<ExtraScope> {
547 lock(&self.extra).clone()
548 }
549
550 pub fn extra_scope(&self, scope: ValueScope) -> Option<ExtraScope> {
552 lock(&self.extra).iter().find(|x| x.scope == scope).copied()
553 }
554
555 pub fn offer(&self, scope: ValueScope, on: bool) {
558 let was = self.offered().contains(&scope);
559 lock(&self.layers).offer(scope, on);
560 if was != on {
561 self.reload(scope);
563 }
564 }
565
566 pub fn offered(&self) -> Vec<ValueScope> {
568 lock(&self.layers).offered().to_vec()
569 }
570
571 #[deprecated(note = "attach a `store::SettingsStore` with `Admin::attach_store`")]
575 pub fn load_layer(&self, app: &AppHandle, scope: ValueScope, values: BTreeMap<String, Json>) {
576 self.legacy
577 .store(true, std::sync::atomic::Ordering::Relaxed);
578 self.put_layer(app, scope, values);
579 }
580
581 #[deprecated(note = "attach a `store::SettingsStore` with `Admin::attach_store`")]
583 pub fn export_layer(&self, scope: ValueScope) -> BTreeMap<String, Json> {
584 self.legacy
585 .store(true, std::sync::atomic::Ordering::Relaxed);
586 self.layer_values(scope)
587 }
588
589 fn put_layer(&self, app: &AppHandle, scope: ValueScope, values: BTreeMap<String, Json>) {
591 let store = app.store();
592 let values = values
593 .into_iter()
594 .map(|(k, v)| (SettingId::new(&k).map_or(k, |id| id.path()), v))
595 .collect();
596 let writes = {
597 let s = lock(&store);
598 lock(&self.layers).load(scope, values, &|p| s.get(p).map(|e| e.value.to_json()))
599 };
600 for (path, v) in writes {
601 write(app, &path, &v);
602 }
603 }
604
605 fn layer_values(&self, scope: ValueScope) -> BTreeMap<String, Json> {
607 lock(&self.layers)
608 .export(scope)
609 .into_iter()
610 .map(|(p, v)| (p.strip_prefix("settings/").unwrap_or(&p).to_string(), v))
611 .collect()
612 }
613
614 pub fn set_run(&self, app: &AppHandle, id: &SettingId, value: Json) -> Result<(), String> {
617 let path = id.path();
618 let now = current(app, &path)?;
619 let w = lock(&self.layers).set_run(&path, value, &now);
620 if let Some(v) = w {
621 write(app, &path, &v);
622 }
623 Ok(())
624 }
625
626 pub fn set_in(
630 &self,
631 app: &AppHandle,
632 scope: ValueScope,
633 id: &SettingId,
634 value: Json,
635 ) -> Result<(), String> {
636 let path = id.path();
637 let now = current(app, &path)?;
638 if !scope.editable() {
639 return Err("the command line's values are not edited here".into());
640 }
641 if scope != ValueScope::App && !self.offered().contains(&scope) {
642 return Err(format!("no {} is open", scope.name()));
643 }
644 if scope != ValueScope::App && !self.allows(app, id, scope) {
645 return Err(format!("`{id}` is not set for a {}", scope.name()));
646 }
647 let _writing = crate::bus::settings::writing(scope.name(), None);
649 let (w, plain) = {
650 let mut l = lock(&self.layers);
651 let plain = scope == ValueScope::App && l.origin(&path) == ValueScope::App;
652 (l.set(scope, &path, value, &now), plain)
653 };
654 let set = match (w, plain) {
655 (Some(v), true) => {
656 let ty = descriptor(app, &path)?.ty;
657 let v = Value::from_json(ty, &v)?;
658 lock(&app.store())
659 .set(Set::new(&path, Change::To(v), Origin::User).by(&OwnerId::FRAMEWORK))
660 .map(|_| ())
661 .map_err(|e| format!("{e:?}"))
662 }
663 (Some(v), false) => {
664 write(app, &path, &v);
665 Ok(())
666 }
667 (None, _) => Ok(()),
668 };
669 if set.is_ok() && *id == WINDOW {
672 window::settle(app, self, false);
673 }
674 set
675 }
676
677 pub fn allows(&self, app: &AppHandle, id: &SettingId, scope: ValueScope) -> bool {
680 if scope == ValueScope::App {
681 return true;
682 }
683 if descriptor(app, &id.path()).is_ok_and(|d| d.scopes.contains(&scope)) {
684 return true;
685 }
686 self.tree(app)
687 .fields()
688 .into_iter()
689 .any(|(_, f)| f.setting_id() == Some(id.as_str()) && f.scopes.contains(&scope))
690 }
691
692 pub fn clear_in(
695 &self,
696 app: &AppHandle,
697 scope: ValueScope,
698 id: &SettingId,
699 ) -> Result<(), String> {
700 let path = id.path();
701 let now = current(app, &path)?;
702 let default = descriptor(app, &path)?.default.to_json();
703 let plain = scope == ValueScope::App && lock(&self.layers).origin(&path) == ValueScope::App;
704 if plain {
705 return lock(&app.store())
706 .set(Set::new(&path, Change::Reset, Origin::User).by(&OwnerId::FRAMEWORK))
707 .map(|_| ())
708 .map_err(|e| format!("{e:?}"));
709 }
710 let w = lock(&self.layers).clear(scope, &path, &now, &default);
711 if let Some(v) = w {
712 write(app, &path, &v);
713 }
714 Ok(())
715 }
716
717 pub fn read(
723 &self,
724 app: &AppHandle,
725 command: &str,
726 args: &Json,
727 ) -> Option<Result<Json, String>> {
728 let args = if args.is_null() {
729 json!({})
730 } else {
731 args.clone()
732 };
733 if let Some(k) = self.kernel_for(command) {
734 k.set_context(&app.egui());
735 return k.read(command, &args).answer();
736 }
737 let key = read_key(command, &args);
738 let mut r = lock(&self.reads);
739 if let Some(a) = r.answers.get(&key) {
740 return Some(a.clone());
741 }
742 if let Some((id, args, before)) = r.asked.get(&key).cloned() {
743 let runs = app.history();
747 if runs.len() < egui_pop_model::commands::HISTORY
749 && runs.iter().filter(|x| x.id == id).count() == before
750 {
751 return r.stale.get(&key).cloned();
752 }
753 let Some(run) = runs
754 .iter()
755 .rev()
756 .find(|x| x.id == id && x.args == args)
757 .or_else(|| runs.iter().rev().find(|x| x.id == id))
758 .cloned()
759 else {
760 return r.stale.get(&key).cloned();
761 };
762 r.asked.remove(&key);
763 r.stale.remove(&key);
764 r.answers.insert(key, run.result.clone());
765 return Some(run.result);
766 }
767 let answer = match CommandId::new(command) {
768 Err(e) => Err(format!("{e:?}")),
769 Ok(id) => match app.command(&id) {
770 None => Err(format!("no command `{command}`")),
771 Some(spec) if !spec.read_only => {
772 Err(format!("`{command}` is not read-only: it is not read here"))
773 }
774 Some(_) => {
775 let before = app.history().iter().filter(|x| x.id == id).count();
776 app.run(id.clone(), args.clone());
777 let stale = r.stale.get(&key).cloned();
778 r.asked.insert(key, (id, args, before));
779 return stale;
780 }
781 },
782 };
783 r.stale.remove(&key);
784 r.answers.insert(key, answer.clone());
785 Some(answer)
786 }
787
788 pub fn refreshing(&self, command: &str, args: &Json) -> bool {
792 let args = if args.is_null() {
793 json!({})
794 } else {
795 args.clone()
796 };
797 if let Some(k) = self.kernel_for(command) {
798 return k.peek(command, &args).state == crate::reads::ReadState::Refreshing;
799 }
800 let key = read_key(command, &args);
801 let r = lock(&self.reads);
802 r.stale.contains_key(&key) && !r.answers.contains_key(&key)
803 }
804
805 pub fn attach_reads(&self, kernel: Arc<crate::reads::ReadKernel>) {
811 *lock(&self.kernel) = Some(kernel);
812 }
813
814 pub fn reads(&self) -> Option<Arc<crate::reads::ReadKernel>> {
816 lock(&self.kernel).clone()
817 }
818
819 fn kernel_for(&self, command: &str) -> Option<Arc<crate::reads::ReadKernel>> {
820 lock(&self.kernel).clone().filter(|k| k.serves(command))
821 }
822
823 pub fn refresh(&self) {
827 let mut r = lock(&self.reads);
828 let answers = std::mem::take(&mut r.answers);
829 r.stale.extend(answers);
830 r.asked.clear();
831 drop(r);
832 if let Some(k) = self.reads() {
833 k.invalidate_all();
834 }
835 }
836
837 pub(crate) fn watch(&self, app: &AppHandle, patterns: &[String]) {
841 let since = lock(&self.reads).seq;
842 let events = app.events_since(since.unwrap_or(0));
843 let Some(last) = events.last().map(|e| e.seq) else {
844 return;
845 };
846 lock(&self.reads).seq = Some(last);
847 if since.is_none() {
848 return;
849 }
850 if let Some(k) = self.reads() {
851 for e in &events {
852 k.event(&e.name);
853 }
854 }
855 let matches = |name: &str| {
856 patterns.iter().any(|p| match p.strip_suffix('*') {
857 Some(prefix) => name.starts_with(prefix),
858 None => name == p,
859 })
860 };
861 let changed = events.iter().any(|e| {
862 matches(&e.name)
863 || (e.name == "command.done"
864 && e.data["command"]
865 .as_str()
866 .and_then(|c| CommandId::new(c).ok())
867 .and_then(|c| app.command(&c))
868 .is_some_and(|s| !s.read_only))
869 });
870 if changed {
871 self.refresh();
872 }
873 }
874
875 pub(crate) fn target(&self, path: &str) -> Option<ValueScope> {
877 lock(&self.state).target.get(path).copied()
878 }
879
880 pub(crate) fn set_target(&self, path: &str, scope: ValueScope) {
881 lock(&self.state).target.insert(path.into(), scope);
882 }
883
884 pub(crate) fn app_doc(&self, app: &AppHandle, values: &mut BTreeMap<String, Json>) {
887 let store = app.store();
888 let s = lock(&store);
889 lock(&self.layers).app_doc(values, &|p| {
890 s.get(p).map(|e| e.descriptor.default.to_json())
891 });
892 }
893}
894
895fn current(app: &AppHandle, path: &str) -> Result<Json, String> {
896 lock(&app.store())
897 .get(path)
898 .map(|e| e.value.to_json())
899 .ok_or_else(|| format!("no setting at `{path}`"))
900}
901
902fn descriptor(app: &AppHandle, path: &str) -> Result<Descriptor, String> {
903 lock(&app.store())
904 .get(path)
905 .map(|e| e.descriptor.clone())
906 .ok_or_else(|| format!("no setting at `{path}`"))
907}
908
909fn write(app: &AppHandle, path: &str, v: &Json) {
912 let store = app.store();
913 let mut s = lock(&store);
914 let Some(ty) = s.get(path).map(|e| e.descriptor.ty) else {
915 return;
916 };
917 if let Ok(v) = Value::from_json(ty, v) {
918 let _ = s.set(
919 Set::new(path, Change::To(v), Origin::User)
920 .force()
921 .untracked()
922 .by(&OwnerId::FRAMEWORK),
923 );
924 }
925}
926
927pub(crate) fn setting_row(ui: &mut Ui, app: &AppHandle, id: &SettingId) -> bool {
930 shell::setting_row(ui, app, id)
931}
932
933pub fn scope_named(name: &str) -> Option<ValueScope> {
935 (!name.is_empty()).then(|| ValueScope::named(name))
936}
937
938pub fn is_open(app: &AppHandle) -> bool {
940 app.service(&ADMIN).is_some_and(|a| a.is_open())
941}
942
943pub const NAV_WIDTH: &str = "settings/admin.nav_width";
946
947pub const NAV_WIDTH_DEFAULT: f32 = 220.0;
949
950pub fn nav_width(app: &AppHandle) -> f32 {
953 lock(&app.store())
954 .get(NAV_WIDTH)
955 .and_then(|e| e.value.as_f64())
956 .map_or(NAV_WIDTH_DEFAULT, |w| w as f32)
957}
958
959pub fn want_nav_width(app: &AppHandle, width: f32) {
961 let set = Set::new(
962 NAV_WIDTH,
963 Change::To(Value::Float(f64::from(width))),
964 Origin::User,
965 )
966 .by(&OwnerId::FRAMEWORK)
967 .untracked();
968 if let Err(e) = lock(&app.store()).set(set) {
969 log::warn!(target: "egui_pop", "{NAV_WIDTH}: {e:?}");
970 }
971}
972
973pub fn in_window(app: &AppHandle) -> bool {
976 !focus_screen(app) && app.setting::<bool>(&WINDOW).unwrap_or(false)
977}
978
979pub fn focus_screen(app: &AppHandle) -> bool {
982 app.service(&ADMIN).is_some_and(|a| a.focus_screen())
983}
984
985#[derive(Debug, Default)]
989pub struct AdminPlugin;
990
991fn admin(call: &crate::app::Call<'_>) -> Result<Arc<Admin>, String> {
992 call.app.service(&ADMIN).ok_or_else(|| "no admin".into())
993}
994
995fn key_arg(call: &crate::app::Call<'_>) -> Result<SettingId, String> {
996 let key = call
997 .args
998 .get("key")
999 .and_then(Json::as_str)
1000 .ok_or("`key` is missing")?;
1001 SettingId::new(key).map_err(|e| format!("{e:?}"))
1002}
1003
1004fn scope_arg(call: &crate::app::Call<'_>) -> Result<ValueScope, String> {
1005 let name = call
1006 .args
1007 .get("scope")
1008 .and_then(Json::as_str)
1009 .unwrap_or("app");
1010 scope_named(name).ok_or_else(|| format!("no value scope `{name}`"))
1011}
1012
1013impl Plugin for AdminPlugin {
1014 fn id(&self) -> PluginId {
1015 PluginId::from_static("egui_pop.admin")
1016 }
1017
1018 fn title(&self) -> String {
1019 "Settings app".into()
1020 }
1021
1022 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
1023 let service = Admin::new();
1024 crate::settings_window::register_kinds(&service);
1025 transfer::hooks(&service);
1026 ctx.service(&ADMIN, service)?;
1027 if let Some(admin) = ctx.app().service(&ADMIN) {
1028 window::listen(&ctx.app(), admin);
1029 }
1030 ctx.local_scope(
1031 SURFACE,
1032 StoreScope::new(egui_pop_model::history::SETTINGS, "Settings"),
1033 );
1034 ctx.setting(
1035 WINDOW,
1036 Descriptor::bool("Settings in their own window", false).description(
1037 "Opens the settings in a window of their own rather than over the main window.",
1038 ),
1039 )?;
1040 lock(&ctx.app().store())
1041 .declare(
1042 ctx.owner(),
1043 NAV_WIDTH,
1044 Descriptor::float(
1045 "Settings sections width",
1046 0.0,
1047 4096.0,
1048 f64::from(NAV_WIDTH_DEFAULT),
1049 ),
1050 )
1051 .map_err(|e| PluginError::Failed(format!("{NAV_WIDTH}: {e:?}")))?;
1052 ctx.command(
1053 CommandSpec::new(CMD_OPEN, "Settings", "File")
1054 .icon("settings")
1055 .description(
1056 "Every setting as full pages: families and their sections in a tree on the side, one search.",
1057 )
1058 .args(json!({ "path": "", "key": "", "mode": "", "wizard": "" })),
1059 |call| {
1060 let a = admin(call)?;
1061 if let Some(id) = call
1063 .args
1064 .get("wizard")
1065 .and_then(Json::as_str)
1066 .filter(|w| !w.is_empty())
1067 {
1068 return a.open_wizard(call.app, id, None, Default::default());
1069 }
1070 if let Some(mode) = call.args.get("mode").and_then(Json::as_str)
1071 && !mode.is_empty()
1072 {
1073 let window = match mode {
1074 "window" => true,
1075 "overlay" => false,
1076 other => return Err(format!("no mode `{other}`")),
1077 };
1078 a.set_in(call.app, ValueScope::App, &WINDOW, json!(window))?;
1079 }
1080 let place = ["path", "key"].iter().find_map(|k| {
1082 call.args
1083 .get(*k)
1084 .and_then(Json::as_str)
1085 .filter(|p| !p.is_empty())
1086 });
1087 a.open(call.app, place)?;
1088 let (scope, section, _) = a.shown();
1089 Ok(json!({ "open": true, "scope": scope, "section": section, "window": in_window(call.app) }))
1090 },
1091 )?;
1092 ctx.command(
1093 CommandSpec::new(CMD_CLOSE, "Close settings", "File").hidden(),
1094 |call| {
1095 admin(call)?.close(call.app);
1096 Ok(json!({ "open": false }))
1097 },
1098 )?;
1099 ctx.command(
1100 CommandSpec::new(CMD_POP_OUT, "Settings: pop out", "File")
1101 .description(
1102 "Moves the settings between the main window and a window of their own.",
1103 )
1104 .hidden(),
1105 |call| {
1106 let window = !in_window(call.app);
1107 admin(call)?.set_in(call.app, ValueScope::App, &WINDOW, json!(window))?;
1108 Ok(json!({ "window": window }))
1109 },
1110 )?;
1111 ctx.command(
1112 CommandSpec::new(CMD_SET, "Set a setting in a value scope", "File")
1113 .hidden()
1114 .args(json!({ "key": "", "scope": "app", "value": null })),
1115 |call| {
1116 let id = key_arg(call)?;
1117 let scope = scope_arg(call)?;
1118 let value = call
1119 .args
1120 .get("value")
1121 .cloned()
1122 .ok_or("`value` is missing")?;
1123 admin(call)?.set_in(call.app, scope, &id, value)?;
1124 Ok(json!({ "key": id.as_str(), "scope": scope.name() }))
1125 },
1126 )?;
1127 ctx.command(
1128 CommandSpec::new(CMD_RESET, "Reset a setting in a value scope", "File")
1129 .hidden()
1130 .args(json!({ "key": "", "scope": "app" })),
1131 |call| {
1132 let id = key_arg(call)?;
1133 let scope = scope_arg(call)?;
1134 admin(call)?.clear_in(call.app, scope, &id)?;
1135 Ok(json!({ "key": id.as_str(), "scope": scope.name() }))
1136 },
1137 )?;
1138 wizard::commands(ctx)?;
1139 transfer::commands(ctx)?;
1140 quick::commands(ctx)?;
1141 focus::commands(ctx)?;
1142 ctx.block(
1143 zones::OVERLAYS,
1144 Block::add(BlockId::from_static("egui_pop.admin"), 6, shell::show),
1145 );
1146 ctx.block(
1148 zones::WINDOW_OVERLAYS,
1149 Block::add(BlockId::from_static("egui_pop.admin.quick"), 1, quick::show),
1150 );
1151 let w = ctx.app().downgrade();
1152 ctx.collector(
1153 egui_pop_core::debug::FnCollector::new(
1154 "admin",
1155 "The administration app (Settings as full pages): open or not, the mode, the scope, section and search shown, the value scopes offered, the values set above the app layer and their origin, the resolved tree (scopes, sections, items) and the diagnostics of its manifests.",
1156 )
1157 .snapshot(move |_| match w.get() {
1158 Ok(app) => describe(&app),
1159 Err(_) => Json::Null,
1160 }),
1161 )?;
1162 Ok(())
1163 }
1164}
1165
1166fn describe(app: &AppHandle) -> Json {
1168 let Some(a) = app.service(&ADMIN) else {
1169 return Json::Null;
1170 };
1171 let tree = a.tree(app);
1172 let (scope, section, filter) = a.shown();
1173 let layers = a.layers();
1174 let mut origins = BTreeMap::new();
1175 for (_, f) in tree.fields() {
1176 if let Some(id) = f.setting_id() {
1177 let o = layers.origin(&format!("settings/{id}"));
1178 if o != ValueScope::App {
1179 origins.insert(id.to_string(), o.name());
1180 }
1181 }
1182 }
1183 json!({
1184 "open": a.is_open(),
1185 "window": in_window(app),
1186 "scope": scope,
1187 "section": section,
1188 "filter": filter,
1189 "marked": a.marked(),
1190 "offered": a.offered().iter().map(|s| s.name()).collect::<Vec<_>>(),
1191 "origins": origins,
1192 "tree": tree,
1193 "wizard": a.wizard_state(app),
1194 "quick": a.quick_settings(app),
1195 "focus": focus::state(app, &a),
1196 "recent": a.recent_settings(app, quick::now()),
1197 "lastFinished": a.last_finished(),
1198 "hooks": a.hooks().list().into_iter().map(|(n, k)| json!({"name": n, "kind": k})).collect::<Vec<_>>(),
1199 "diagnostics": a.diagnostics().all().iter().map(|d| json!({"code": d.code, "subject": d.subject, "message": d.message})).collect::<Vec<_>>(),
1200 })
1201}