1use std::panic::{AssertUnwindSafe, catch_unwind};
19
20use egui::{Id, RichText, Shadow, Ui};
21use serde::Serialize;
22
23use crate::kit::{Kit, State};
24use crate::state::Slot;
25use crate::strings::{self, FAULT_BODY, FAULT_TITLE, RETRY};
26use crate::theme::Tokens;
27
28#[derive(Clone, Debug, PartialEq, Serialize)]
30pub struct Fault {
31 pub name: String,
33 pub message: String,
34 pub count: u32,
37}
38
39const FAULT: Slot<Fault> = Slot::new("core.fault");
41const FAILED: Slot<Vec<Id>> = Slot::new("core.fault.failed");
43const STREAK: Slot<u32> = Slot::new("core.fault.streak");
46
47pub(crate) fn message(payload: &(dyn std::any::Any + Send)) -> String {
49 if let Some(s) = payload.downcast_ref::<&str>() {
50 (*s).to_string()
51 } else if let Some(s) = payload.downcast_ref::<String>() {
52 s.clone()
53 } else {
54 "a panic without a message".into()
55 }
56}
57
58pub fn boundary<R>(
61 ui: &mut Ui,
62 id: impl std::hash::Hash + std::fmt::Debug,
63 name: &str,
64 add: impl FnOnce(&mut Ui) -> R,
65) -> Option<R> {
66 boundary_reporting(ui, id, name, add, |_| {})
67}
68
69pub fn boundary_reporting<R>(
73 ui: &mut Ui,
74 id: impl std::hash::Hash + std::fmt::Debug,
75 name: &str,
76 add: impl FnOnce(&mut Ui) -> R,
77 failed: impl FnOnce(&Fault),
78) -> Option<R> {
79 let id = ui.scope_id().with(id);
80 let key = FAULT.keyed(id);
81 if let Some(fault) = key.get(ui.ctx()) {
82 card(ui, key, &fault);
83 return None;
84 }
85 let streak = STREAK.keyed(id);
86 let result = catch_unwind(AssertUnwindSafe(|| ui.scope(add).inner));
87 match result {
88 Ok(r) => {
89 if streak.exists(ui.ctx()) {
90 streak.remove(ui.ctx());
91 }
92 Some(r)
93 }
94 Err(payload) => {
95 let count = streak.update(ui.ctx(), |n| {
96 *n += 1;
97 *n
98 });
99 let fault = Fault {
100 name: name.into(),
101 message: message(&*payload),
102 count,
103 };
104 log::error!(target: "egui_pop", "`{name}` panicked: {}", fault.message);
105 failed(&fault);
106 key.set(ui.ctx(), fault.clone());
107 FAILED.update(ui.ctx(), |all| {
108 if !all.contains(&id) {
109 all.push(id);
110 }
111 });
112 card(ui, key, &fault);
113 ui.ctx().request_repaint();
114 None
115 }
116 }
117}
118
119pub fn faults(ctx: &egui::Context) -> Vec<Fault> {
121 FAILED
122 .get_or_default(ctx)
123 .into_iter()
124 .filter_map(|id| FAULT.keyed(id).get(ctx))
125 .collect()
126}
127
128fn card(ui: &mut Ui, key: Slot<Fault>, fault: &Fault) {
129 let t = Tokens::of(ui.ctx());
130 Kit::of(ui.ctx())
131 .fault_card
132 .show(ui, State::REST, Shadow::NONE, |ui| {
133 ui.label(
134 RichText::new(strings::tr_args(
135 ui.ctx(),
136 &FAULT_TITLE,
137 &[("name", &fault.name)],
138 ))
139 .color(t.status.danger)
140 .strong(),
141 );
142 ui.label(strings::tr(ui.ctx(), &FAULT_BODY));
143 ui.label(
144 RichText::new(&fault.message)
145 .monospace()
146 .color(t.text.muted),
147 );
148 if ui.button(strings::tr(ui.ctx(), &RETRY)).clicked() {
149 key.remove(ui.ctx());
150 }
151 });
152}