1use std::collections::{BTreeSet, VecDeque};
43use std::fmt;
44
45use egui::Context;
46use serde::Serialize;
47use serde_json::{Value as Json, json};
48
49use egui_pop_model::commands::Origin;
50
51use crate::binding::SharedStore;
52use crate::state::lock;
53use crate::{a11y, fault, field, focus, indicator, overlay, state, tab, theme};
54
55#[derive(Clone, Debug, PartialEq, Serialize)]
57pub struct ActionSpec {
58 pub name: String,
59 pub description: String,
60 pub mutates: bool,
62 pub agent: bool,
65 pub args: Json,
67}
68
69#[derive(Clone, Debug, Default, PartialEq, Serialize)]
73pub struct Schemas {
74 pub args: Option<Json>,
76 pub result: Option<Json>,
78}
79
80pub const PROTOCOL: u32 = 1;
84
85pub fn is_schema(j: &Json) -> bool {
89 const KEYWORDS: [&str; 22] = [
90 "$schema",
91 "$id",
92 "$ref",
93 "$defs",
94 "title",
95 "description",
96 "type",
97 "properties",
98 "required",
99 "additionalProperties",
100 "items",
101 "enum",
102 "const",
103 "default",
104 "minimum",
105 "maximum",
106 "minLength",
107 "maxLength",
108 "pattern",
109 "oneOf",
110 "anyOf",
111 "allOf",
112 ];
113 const TYPES: [&str; 7] = [
114 "object", "array", "string", "number", "integer", "boolean", "null",
115 ];
116 let Some(m) = j.as_object() else { return false };
117 let typed = match m.get("type") {
118 Some(Json::String(t)) => TYPES.contains(&t.as_str()),
119 Some(Json::Array(ts)) => ts
120 .iter()
121 .all(|t| t.as_str().is_some_and(|t| TYPES.contains(&t))),
122 Some(_) => false,
123 None => ["$schema", "properties", "oneOf", "anyOf", "allOf", "$ref"]
124 .iter()
125 .any(|k| m.contains_key(*k)),
126 };
127 typed && !m.is_empty() && m.keys().all(|k| KEYWORDS.contains(&k.as_str()))
128}
129
130#[derive(Clone, Debug, PartialEq, Serialize)]
132pub struct Feedback {
133 pub ok: bool,
134 pub collector: String,
135 pub action: String,
136 pub mutates: bool,
138 pub message: String,
140 pub data: Json,
142}
143
144pub trait Collector {
146 fn name(&self) -> &str;
147 fn description(&self) -> &str;
148 fn actions(&self) -> Vec<ActionSpec> {
149 Vec::new()
150 }
151 fn snapshot(&self, ctx: &Context) -> Json;
152 fn mutates(&self, action: &str, _args: &Json) -> Option<bool> {
156 self.actions()
157 .into_iter()
158 .find(|a| a.name == action)
159 .map(|a| a.mutates)
160 }
161 fn destructive(&self, _action: &str, _args: &Json) -> bool {
166 false
167 }
168 fn call(
172 &mut self,
173 _ctx: &Context,
174 action: &str,
175 _args: &Json,
176 _origin: &Origin,
177 ) -> Result<Json, String> {
178 Err(format!("no action `{action}`"))
179 }
180 fn schemas(&self, _action: &str) -> Schemas {
183 Schemas::default()
184 }
185}
186
187type SnapshotFn = Box<dyn Fn(&Context) -> Json>;
188type ActionFn = Box<dyn FnMut(&Context, &Json, &Origin) -> Result<Json, String>>;
189type MutatesFn = Box<dyn Fn(&Json) -> bool>;
190type DestructiveFn = Box<dyn Fn(&Json) -> bool>;
191
192pub struct FnCollector {
194 name: String,
195 description: String,
196 snapshot: SnapshotFn,
197 actions: Vec<(ActionSpec, ActionFn)>,
198 mutates_when: Vec<(String, MutatesFn)>,
200 schemas: Vec<(String, Schemas)>,
202 destructive: Vec<(String, DestructiveFn)>,
204}
205
206impl fmt::Debug for FnCollector {
207 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
208 f.debug_struct("FnCollector")
209 .field("name", &self.name)
210 .finish()
211 }
212}
213
214impl FnCollector {
215 pub fn new(name: &str, description: &str) -> Self {
216 Self {
217 name: name.into(),
218 description: description.into(),
219 snapshot: Box::new(|_| Json::Null),
220 actions: Vec::new(),
221 mutates_when: Vec::new(),
222 schemas: Vec::new(),
223 destructive: Vec::new(),
224 }
225 }
226
227 pub fn snapshot(mut self, f: impl Fn(&Context) -> Json + 'static) -> Self {
228 self.snapshot = Box::new(f);
229 self
230 }
231
232 pub fn action(
234 self,
235 name: &str,
236 description: &str,
237 mutates: bool,
238 mut f: impl FnMut(&Context, &Json) -> Result<Json, String> + 'static,
239 ) -> Self {
240 self.action_as(name, description, mutates, move |ctx, args, _| f(ctx, args))
241 }
242
243 pub fn action_as(
247 mut self,
248 name: &str,
249 description: &str,
250 mutates: bool,
251 f: impl FnMut(&Context, &Json, &Origin) -> Result<Json, String> + 'static,
252 ) -> Self {
253 self.actions.push((
254 ActionSpec {
255 name: name.into(),
256 description: description.into(),
257 mutates,
258 agent: !mutates,
259 args: Json::Null,
260 },
261 Box::new(f),
262 ));
263 self
264 }
265
266 pub fn agent(mut self, offered: bool) -> Self {
271 if let Some((spec, _)) = self.actions.last_mut() {
272 spec.agent = offered;
273 }
274 self
275 }
276
277 pub fn mutates_when(mut self, f: impl Fn(&Json) -> bool + 'static) -> Self {
281 if let Some((spec, _)) = self.actions.last() {
282 let name = spec.name.clone();
283 self.mutates_when.push((name, Box::new(f)));
284 }
285 self
286 }
287
288 pub fn destructive(self) -> Self {
292 self.destructive_when(|_| true)
293 }
294
295 pub fn destructive_when(mut self, f: impl Fn(&Json) -> bool + 'static) -> Self {
298 if let Some((spec, _)) = self.actions.last() {
299 let name = spec.name.clone();
300 self.destructive.retain(|(n, _)| *n != name);
301 self.destructive.push((name, Box::new(f)));
302 }
303 self
304 }
305
306 pub fn args(mut self, example: Json) -> Self {
308 if let Some((spec, _)) = self.actions.last_mut() {
309 spec.args = example;
310 }
311 self
312 }
313
314 fn schemas_mut(&mut self) -> Option<&mut Schemas> {
315 let name = self.actions.last()?.0.name.clone();
316 if !self.schemas.iter().any(|(n, _)| *n == name) {
317 self.schemas.push((name.clone(), Schemas::default()));
318 }
319 self.schemas
320 .iter_mut()
321 .find(|(n, _)| *n == name)
322 .map(|(_, s)| s)
323 }
324
325 pub fn schema(mut self, schema: Json) -> Self {
328 if let Some(s) = self.schemas_mut() {
329 s.args = Some(schema);
330 }
331 self
332 }
333
334 pub fn result_schema(mut self, schema: Json) -> Self {
336 if let Some(s) = self.schemas_mut() {
337 s.result = Some(schema);
338 }
339 self
340 }
341}
342
343impl Collector for FnCollector {
344 fn name(&self) -> &str {
345 &self.name
346 }
347
348 fn description(&self) -> &str {
349 &self.description
350 }
351
352 fn actions(&self) -> Vec<ActionSpec> {
353 self.actions.iter().map(|(s, _)| s.clone()).collect()
354 }
355
356 fn snapshot(&self, ctx: &Context) -> Json {
357 (self.snapshot)(ctx)
358 }
359
360 fn schemas(&self, action: &str) -> Schemas {
361 self.schemas
362 .iter()
363 .find(|(n, _)| n == action)
364 .map(|(_, s)| s.clone())
365 .unwrap_or_default()
366 }
367
368 fn mutates(&self, action: &str, args: &Json) -> Option<bool> {
369 let declared = self
370 .actions
371 .iter()
372 .find(|(s, _)| s.name == action)
373 .map(|(s, _)| s.mutates)?;
374 Some(
375 declared
376 && self
377 .mutates_when
378 .iter()
379 .find(|(n, _)| n == action)
380 .is_none_or(|(_, f)| f(args)),
381 )
382 }
383
384 fn destructive(&self, action: &str, args: &Json) -> bool {
385 self.destructive
386 .iter()
387 .find(|(n, _)| n == action)
388 .is_some_and(|(_, f)| f(args))
389 }
390
391 fn call(
392 &mut self,
393 ctx: &Context,
394 action: &str,
395 args: &Json,
396 origin: &Origin,
397 ) -> Result<Json, String> {
398 match self.actions.iter_mut().find(|(s, _)| s.name == action) {
399 Some((_, f)) => f(ctx, args, origin),
400 None => Err(format!("no action `{action}`")),
401 }
402 }
403}
404
405pub const KEPT: usize = 64;
407
408pub const AGENT: &str = "debug-bridge";
410
411pub fn agent() -> Origin {
413 Origin::Agent(AGENT.into())
414}
415
416#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
420#[serde(rename_all = "snake_case")]
421pub enum BridgeMode {
422 #[default]
424 On,
425 ReadOnly,
428 Off,
430}
431
432#[derive(Default)]
434pub struct DebugBridge {
435 collectors: Vec<Box<dyn Collector>>,
436 log: VecDeque<Feedback>,
437 offered: BTreeSet<String>,
440 mode: BridgeMode,
441}
442
443impl fmt::Debug for DebugBridge {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 f.debug_struct("DebugBridge")
446 .field("collectors", &self.names())
447 .finish()
448 }
449}
450
451impl DebugBridge {
452 pub fn new() -> Self {
453 Self::default()
454 }
455
456 pub fn with_core_collectors() -> Self {
459 let mut b = Self::new();
460 for c in core_collectors() {
461 b.register(c).expect("distinct names");
462 }
463 b
464 }
465
466 pub fn register(&mut self, c: impl Collector + 'static) -> Result<(), String> {
468 if self.collectors.iter().any(|x| x.name() == c.name()) {
469 return Err(format!("a collector `{}` is already registered", c.name()));
470 }
471 self.collectors.push(Box::new(c));
472 Ok(())
473 }
474
475 pub fn unregister(&mut self, name: &str) -> bool {
477 let before = self.collectors.len();
478 self.collectors.retain(|c| c.name() != name);
479 self.collectors.len() != before
480 }
481
482 pub fn names(&self) -> Vec<String> {
483 self.collectors
484 .iter()
485 .map(|c| c.name().to_string())
486 .collect()
487 }
488
489 pub fn offer_to_agents(&mut self, action: &str) {
493 self.offered.insert(action.into());
494 }
495
496 pub fn offered(&self) -> impl Iterator<Item = &str> {
498 self.offered.iter().map(String::as_str)
499 }
500
501 fn actions_of(&self, c: &dyn Collector) -> Vec<ActionSpec> {
503 let mut actions = c.actions();
504 for a in &mut actions {
505 if self.offered.contains(&format!("{}.{}", c.name(), a.name)) {
506 a.agent = true;
507 }
508 }
509 actions
510 }
511
512 pub fn action(&self, collector: &str, action: &str) -> Option<ActionSpec> {
515 let c = self.collectors.iter().find(|c| c.name() == collector)?;
516 self.actions_of(c.as_ref())
517 .into_iter()
518 .find(|a| a.name == action)
519 }
520
521 pub fn set_mode(&mut self, mode: BridgeMode) {
523 self.mode = mode;
524 }
525
526 pub fn mode(&self) -> BridgeMode {
527 self.mode
528 }
529
530 pub fn mutates(&self, collector: &str, action: &str, args: &Json) -> Option<bool> {
533 self.collectors
534 .iter()
535 .find(|c| c.name() == collector)?
536 .mutates(action, args)
537 }
538
539 pub fn destructive(&self, collector: &str, action: &str, args: &Json) -> bool {
543 self.collectors
544 .iter()
545 .find(|c| c.name() == collector)
546 .is_some_and(|c| c.destructive(action, args))
547 }
548
549 pub fn refusal(
554 &self,
555 collector: &str,
556 action: &str,
557 args: &Json,
558 origin: &Origin,
559 ) -> Option<String> {
560 let spec = self.action(collector, action)?;
561 if *origin == Origin::User {
562 return None;
563 }
564 if self.mode == BridgeMode::Off {
565 return Some("the debug bridge is off; only the user may call it".into());
566 }
567 if !spec.agent {
568 return Some("it is not offered to agents; only the user may call it".into());
569 }
570 if self.mode == BridgeMode::ReadOnly
571 && self.mutates(collector, action, args).unwrap_or(true)
572 {
573 return Some(
574 "the debug bridge is read-only and this call changes the application".into(),
575 );
576 }
577 None
578 }
579
580 pub fn record(&mut self, feedback: Feedback) {
583 if self.log.len() == KEPT {
584 self.log.pop_front();
585 }
586 self.log.push_back(feedback);
587 }
588
589 pub fn describe(&self) -> Json {
591 Json::Array(
592 self.collectors
593 .iter()
594 .map(|c| {
595 let actions: Vec<Json> = self
596 .actions_of(c.as_ref())
597 .into_iter()
598 .map(|a| {
599 let schemas = c.schemas(&a.name);
600 let mut j = json!(a);
601 if let Some(s) = schemas.args {
602 j["schema"] = s;
603 }
604 if let Some(s) = schemas.result {
605 j["result"] = s;
606 }
607 if c.destructive(&a.name, &Json::Null) {
609 j["destructive"] = json!(true);
610 }
611 j
612 })
613 .collect();
614 json!({
615 "name": c.name(),
616 "description": c.description(),
617 "actions": actions,
618 })
619 })
620 .collect(),
621 )
622 }
623
624 pub fn capabilities(&self) -> Vec<Json> {
631 let mut out = Vec::new();
632 for c in &self.collectors {
633 for a in self.actions_of(c.as_ref()) {
634 let schemas = c.schemas(&a.name);
635 let (args, example) = match schemas.args {
636 Some(s) => (s, a.args),
637 None if is_schema(&a.args) => (a.args, Json::Null),
638 None => (Json::Null, a.args),
639 };
640 out.push(json!({
641 "kind": "action",
642 "name": format!("{}.{}", c.name(), a.name),
643 "description": a.description,
644 "mutates": a.mutates,
645 "agent": a.agent,
646 "destructive": c.destructive(&a.name, &Json::Null),
647 "args": args,
648 "example": example,
649 "result": schemas.result,
650 "call": { "collector": c.name(), "action": a.name },
651 }));
652 }
653 }
654 out
655 }
656
657 pub fn snapshot(&self, ctx: &Context) -> Json {
659 let mut map = serde_json::Map::new();
660 for c in &self.collectors {
661 map.insert(c.name().into(), c.snapshot(ctx));
662 }
663 Json::Object(map)
664 }
665
666 pub fn snapshot_of(&self, ctx: &Context, name: &str) -> Option<Json> {
668 self.collectors
669 .iter()
670 .find(|c| c.name() == name)
671 .map(|c| c.snapshot(ctx))
672 }
673
674 pub fn call(&mut self, ctx: &Context, collector: &str, action: &str, args: &Json) -> Feedback {
678 self.call_as(ctx, collector, action, args, &agent())
679 }
680
681 pub fn call_as(
684 &mut self,
685 ctx: &Context,
686 collector: &str,
687 action: &str,
688 args: &Json,
689 origin: &Origin,
690 ) -> Feedback {
691 if let Some(reason) = self.refusal(collector, action, args, origin) {
692 let feedback = Feedback {
693 ok: false,
694 collector: collector.into(),
695 action: action.into(),
696 mutates: self.mutates(collector, action, args).unwrap_or(false),
697 message: format!("`{collector}.{action}` refused: {reason}"),
698 data: Json::Null,
699 };
700 self.record(feedback.clone());
701 return feedback;
702 }
703 let names = self.names();
704 let feedback = match self.collectors.iter_mut().find(|c| c.name() == collector) {
705 None => Feedback {
706 ok: false,
707 collector: collector.into(),
708 action: action.into(),
709 mutates: false,
710 message: format!(
711 "no collector `{collector}`; there are: {}",
712 names.join(", ")
713 ),
714 data: Json::Null,
715 },
716 Some(c) => {
717 let actions = c.actions();
718 match actions.iter().find(|a| a.name == action) {
719 None => Feedback {
720 ok: false,
721 collector: collector.into(),
722 action: action.into(),
723 mutates: false,
724 message: format!(
725 "`{collector}` has no action `{action}`; it has: {}",
726 actions
727 .iter()
728 .map(|a| a.name.as_str())
729 .collect::<Vec<_>>()
730 .join(", ")
731 ),
732 data: Json::Null,
733 },
734 Some(spec) => {
735 let mutates = c.mutates(action, args).unwrap_or(spec.mutates);
736 match c.call(ctx, action, args, origin) {
737 Ok(data) => Feedback {
738 ok: true,
739 collector: collector.into(),
740 action: action.into(),
741 mutates,
742 message: if mutates {
743 format!("`{collector}.{action}` done; the application changed")
744 } else {
745 format!("`{collector}.{action}` done; nothing changed")
746 },
747 data,
748 },
749 Err(e) => Feedback {
750 ok: false,
751 collector: collector.into(),
752 action: action.into(),
753 mutates,
754 message: format!("`{collector}.{action}` failed: {e}"),
755 data: Json::Null,
756 },
757 }
758 }
759 }
760 }
761 };
762 if feedback.mutates && feedback.ok {
763 ctx.request_repaint();
764 }
765 self.record(feedback.clone());
766 feedback
767 }
768
769 pub fn log(&self) -> impl Iterator<Item = &Feedback> {
771 self.log.iter()
772 }
773}
774
775pub fn core_collectors() -> Vec<FnCollector> {
777 vec![
778 FnCollector::new(
779 "screen",
780 "Each window's scale (native, interface zoom, pixels per point), its rectangles in points and pixels, maximized and full screen.",
781 )
782 .snapshot(|ctx| {
783 let zoom = ctx.zoom_factor();
785 let windows: Vec<Json> = ctx.input(|i| {
786 i.raw
787 .viewports
788 .iter()
789 .map(|(id, v)| {
790 let native = v.native_pixels_per_point.unwrap_or(1.0);
791 let ppp = native * zoom;
792 let rect = |r: Option<egui::Rect>| {
793 r.map(|r| {
794 json!({
795 "points": [r.min.x, r.min.y, r.width(), r.height()],
796 "pixels": [r.min.x * ppp, r.min.y * ppp, r.width() * ppp, r.height() * ppp],
797 })
798 })
799 };
800 json!({
801 "viewport": if *id == egui::ViewportId::ROOT { "root".to_string() } else { format!("{id:?}") },
802 "title": v.title,
803 "native": native,
804 "pixels_per_point": ppp,
805 "inner": rect(v.inner_rect),
806 "outer": rect(v.outer_rect),
807 "monitor": v.monitor_size.map(|s| [s.x, s.y]),
808 "maximized": v.maximized,
809 "fullscreen": v.fullscreen,
810 })
811 })
812 .collect()
813 });
814 json!({ "zoom": zoom, "windows": windows })
815 })
816 .action(
817 "set_interface_zoom",
818 "Sets egui's zoom factor (`factor`); an egui-pop application's interface zoom setting takes it back at the next frame, so prefer its `interface.zoom` step.",
819 true,
820 |ctx, args| {
821 let f = args.get("factor").and_then(Json::as_f64).ok_or("`factor` is missing")? as f32;
822 if !(0.25..=4.0).contains(&f) {
823 return Err(format!("{f} is outside 0.25 to 4"));
824 }
825 ctx.set_zoom_factor(f);
826 Ok(json!({ "zoom": f }))
827 },
828 )
829 .args(json!({ "factor": 1.25 })),
830 FnCollector::new(
831 "focus",
832 "The focused widget, the focus chain and the scopes drawn.",
833 )
834 .snapshot(|ctx| {
835 json!({
836 "focused": focus::focused(ctx).map(|id| format!("{id:?}")),
837 "chain": focus::chain_names(ctx),
838 "mode": crate::focus_mode::get(ctx).report(),
839 "scopes": focus::scopes(ctx),
840 "context": focus::when_context(ctx, &Default::default())
841 .iter()
842 .map(|(k, v, d)| json!({ "key": k, "value": v, "depth": d }))
843 .collect::<Vec<_>>(),
844 })
845 })
846 .action("clear", "Takes the keyboard focus away.", true, |ctx, _| {
847 let had = focus::focused(ctx).is_some();
848 ctx.memory_mut(|m| {
849 if let Some(id) = m.focused() {
850 m.surrender_focus(id);
851 }
852 });
853 Ok(json!({ "had_focus": had }))
854 }),
855 FnCollector::new(
856 "overlays",
857 "The overlay stack, bottom first, and the overlays closed lately.",
858 )
859 .snapshot(|ctx| {
860 json!({
861 "stack": overlay::stack(ctx),
862 "recently_closed": overlay::recently_closed(ctx),
863 })
864 })
865 .action(
866 "close_top",
867 "Closes the top overlay (as Escape would, even if it stays on Escape).",
868 true,
869 |ctx, _| {
870 let top = overlay::stack(ctx).last().cloned();
871 match top {
872 Some(o) => {
873 overlay::close(ctx, o.id);
874 Ok(json!({ "closed": o.label }))
875 }
876 None => Err("no overlay is open".into()),
877 }
878 },
879 ),
880 FnCollector::new(
881 "fields",
882 "Every input drawn in the last pass: its label, kind and state (modified, required, invalid with its message, disabled with its reason, read-only, pending), and the Tab scopes with their order.",
883 )
884 .snapshot(|ctx| {
885 json!({
886 "fields": field::describe(ctx),
887 "tab_scopes": tab::scopes(ctx),
888 })
889 }),
890 FnCollector::new("faults", "Panels and blocks showing an error card.")
891 .snapshot(|ctx| json!(fault::faults(ctx))),
892 FnCollector::new(
893 "announcements",
894 "What was announced to screen readers lately.",
895 )
896 .snapshot(|ctx| json!(a11y::announcements(ctx)))
897 .action(
898 "announce",
899 "Announces a text politely.",
900 true,
901 |ctx, args| {
902 let text = args
903 .get("text")
904 .and_then(Json::as_str)
905 .ok_or("`text` is missing")?;
906 a11y::announce(ctx, text, a11y::Politeness::Polite);
907 Ok(Json::Null)
908 },
909 )
910 .args(json!({ "text": "Hello" })),
911 FnCollector::new(
912 "indicators",
913 "The micro-indicators with an id drawn in the last pass: kind, state, value, text, tone, meaning, host, whether interactive, shown and pulsing.",
914 )
915 .snapshot(|ctx| json!(indicator::drawn(ctx))),
916 FnCollector::new(
917 "state",
918 "The state egui-pop keeps in egui's memory: every slot written (name, type, per context or per instance), how many entries it holds and a summary of its first values.",
919 )
920 .snapshot(|ctx| {
921 let slots = state::report(ctx, 3);
922 json!({
923 "entries": slots.iter().map(|s| s.entries).sum::<usize>(),
924 "slots": slots,
925 })
926 })
927 .action(
928 "slot",
929 "Every entry of a slot (`name`), summarised.",
930 false,
931 |ctx, args| {
932 let name = args
933 .get("name")
934 .and_then(Json::as_str)
935 .ok_or("`name` is missing")?;
936 let found: Vec<_> = state::report(ctx, usize::MAX)
937 .into_iter()
938 .filter(|s| s.name == name)
939 .collect();
940 if found.is_empty() {
941 return Err(format!("no slot `{name}` was written"));
942 }
943 Ok(json!(found))
944 },
945 )
946 .args(json!({ "name": "core.theme.tokens" })),
947 FnCollector::new(
948 "theme",
949 "The theme drawn now, its counterpart if installed with it, and its problems.",
950 )
951 .snapshot(|ctx| {
952 let mode = ctx.theme();
953 let v = theme::variants(ctx);
954 let t = v.get(mode).clone();
955 let r = t.resolved();
956 let other = match mode {
957 egui::Theme::Dark => &v.light,
958 egui::Theme::Light => &v.dark,
959 };
960 json!({
961 "spec": {
962 "base": r.spec().base,
963 "density": r.spec().density.name(),
964 "accent": r.spec().accent,
965 "reduced_motion": r.spec().reduced_motion,
966 "text_size": r.spec().text_size,
967 "font_ui": r.spec().font_ui,
968 "font_mono": r.spec().font_mono,
969 "scroll_bars": r.spec().scroll_bars.as_str(),
970 },
971 "dark": t.dark_mode(),
972 "counterpart": v.paired().then(|| other.resolved().spec().base.clone()),
973 "preference": format!("{:?}", ctx.options(|o| o.theme_preference)),
974 "problems": r.problems().iter().map(|p| p.to_string()).collect::<Vec<_>>(),
975 })
976 }),
977 crate::fonts::collector(),
978 crate::pointer::collector(),
979 ]
980}
981
982pub fn store_collector(store: SharedStore) -> FnCollector {
985 let (s1, s2, s3, s4) = (store.clone(), store.clone(), store.clone(), store);
986 FnCollector::new(
987 "store",
988 "The value store: every path, its value, its owner, who may write it and who changed it.",
989 )
990 .snapshot(move |_| {
991 let s = lock(&s1);
992 json!({
993 "seq": s.seq(),
994 "values": s.list("").iter().map(|(p, e)| json!({
995 "path": p,
996 "value": e.value.to_json(),
997 "default": e.descriptor.default.to_json(),
998 "owner": e.owner,
999 "writers": e.descriptor.writers,
1000 "writer": e.writer,
1001 "origin": e.origin,
1002 "held_by": s.held_by(p),
1003 })).collect::<Vec<_>>(),
1004 "undo": s.undo_steps().iter().map(|st| st.label.clone()).collect::<Vec<_>>(),
1005 "pending": s.pending(),
1006 "check": s.writer_check(),
1007 "stray": s.stray_writes(),
1008 })
1009 })
1010 .action(
1011 "get",
1012 "Reads a value with its descriptor.",
1013 false,
1014 move |_, args| {
1015 let path = args
1016 .get("path")
1017 .and_then(Json::as_str)
1018 .ok_or("`path` is missing")?;
1019 let s = lock(&s2);
1020 let e = s.get(path).ok_or_else(|| format!("no value at `{path}`"))?;
1021 Ok(json!({ "value": e.value.to_json(), "descriptor": e.descriptor }))
1022 },
1023 )
1024 .args(json!({ "path": "settings/x" }))
1025 .action_as(
1026 "set",
1027 "Writes a value (`path`, `value`) as its caller: the user through the framework, anyone else as itself, held to the value's writers (`Origin::writer`); for the user only unless offered (agents run the `value.set` command).",
1028 true,
1029 move |_, args, origin| {
1030 use egui_pop_model::values::{Change, Set, Value};
1031 let path = args
1032 .get("path")
1033 .and_then(Json::as_str)
1034 .ok_or("`path` is missing")?;
1035 let v = args.get("value").ok_or("`value` is missing")?;
1036 let mut s = lock(&s3);
1037 let ty = s
1038 .get(path)
1039 .ok_or_else(|| format!("no value at `{path}`"))?
1040 .descriptor
1041 .ty;
1042 let value = Value::from_json(ty, v)?;
1043 let a = s
1044 .set(
1045 Set::new(path, Change::To(value), origin.clone()).by(&origin.writer()),
1046 )
1047 .map_err(|r| r.to_string())?;
1048 Ok(json!({ "value": a.value.to_json(), "clamped": a.clamped, "changed": a.changed }))
1049 },
1050 )
1051 .args(json!({ "path": "settings/x", "value": 1 }))
1052 .action_as(
1053 "undo",
1054 "Undoes the last change of values as its caller, refused when it may not write one of them; for the user only unless offered (agents run the `value.undo` command).",
1055 true,
1056 move |_, _, origin| {
1057 let label = lock(&s4)
1058 .undo_by(origin, &origin.writer())
1059 .map_err(|r| r.to_string())?;
1060 Ok(json!({ "undone": label }))
1061 },
1062 )
1063}