Skip to main content

egui_pop_core/
fault.rs

1//! Fault boundaries: a panel whose drawing code panics shows an error card
2//! instead of taking the application down. The panic is caught
3//! (`catch_unwind`), logged, and kept until the user retries.
4//!
5//! Where panics abort (`panic = "abort"`, or WebAssembly without unwinding)
6//! nothing can be caught; the boundary then changes nothing.
7//!
8//! ```
9//! use egui_pop_core::fault;
10//!
11//! fn panel(ui: &mut egui::Ui) {
12//!     fault::boundary(ui, "inspector", "Inspector", |ui| {
13//!         ui.label("Drawn by code that might panic");
14//!     });
15//! }
16//! ```
17
18use 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/// A caught panic.
29#[derive(Clone, Debug, PartialEq, Serialize)]
30pub struct Fault {
31    /// The boundary's name.
32    pub name: String,
33    pub message: String,
34    /// How many times in a row it failed: a retry that fails again adds
35    /// one, a pass that draws without a panic starts again from zero.
36    pub count: u32,
37}
38
39/// The fault a boundary shows, per boundary.
40const FAULT: Slot<Fault> = Slot::new("core.fault");
41/// Every boundary that failed.
42const FAILED: Slot<Vec<Id>> = Slot::new("core.fault.failed");
43/// How many times in a row a boundary failed, per boundary: kept across a
44/// retry, removed when the boundary draws without a panic.
45const STREAK: Slot<u32> = Slot::new("core.fault.streak");
46
47/// The panic's message.
48pub(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
58/// Draws `add` inside a boundary named `name`. Returns `None` while the
59/// boundary shows its error card.
60pub 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
69/// Draws `add` as [`boundary`] does, and hands a panic it catches to
70/// `failed`, once per failure: for the caller to say what failed in its
71/// own words (a panel's id, its owner) and to publish it.
72pub 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
119/// The faults currently shown, for the debug bridge.
120pub 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}