use std::any::Any;
use std::cell::{Cell, RefCell};
use std::panic::{self as std_panic, AssertUnwindSafe};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Once;
use crate::host::{Host, LogLevel};
thread_local! {
static CATCHING: Cell<u32> = const { Cell::new(0) };
static MESSAGE: RefCell<Option<String>> = const { RefCell::new(None) };
}
static HOOK: Once = Once::new();
pub(crate) fn install_hook() {
HOOK.call_once(|| {
let previous = std_panic::take_hook();
std_panic::set_hook(Box::new(move |info| {
let text = match info.location() {
Some(at) => format!(
"{} at {}:{}",
payload_text(info.payload()),
at.file(),
at.line()
),
None => payload_text(info.payload()),
};
if CATCHING.try_with(Cell::get).unwrap_or(0) > 0 {
let _ = MESSAGE.try_with(|message| *message.borrow_mut() = Some(text));
} else {
if let Some(host) = Host::current() {
host.log(LogLevel::Error, format_args!("panic: {text}"));
}
previous(info);
}
}));
});
}
fn payload_text(payload: &(dyn Any + Send)) -> String {
if let Some(text) = payload.downcast_ref::<&str>() {
(*text).to_owned()
} else if let Some(text) = payload.downcast_ref::<String>() {
text.clone()
} else {
"a panic without a message".to_owned()
}
}
pub(crate) fn catch<R>(body: impl FnOnce() -> R) -> Result<R, String> {
catch_raw(body).map_err(|payload| {
let text = MESSAGE
.with(|message| message.borrow_mut().take())
.unwrap_or_else(|| payload_text(&*payload));
let _ = std_panic::catch_unwind(AssertUnwindSafe(move || drop(payload)));
text
})
}
pub(crate) fn catch_raw<R>(body: impl FnOnce() -> R) -> std::thread::Result<R> {
CATCHING.with(|n| n.set(n.get() + 1));
let result = std_panic::catch_unwind(AssertUnwindSafe(body));
CATCHING.with(|n| n.set(n.get() - 1));
result
}
pub(crate) fn run_callback<R>(
what: &str,
logged: &AtomicBool,
fallback: R,
body: impl FnOnce() -> R,
) -> R {
match catch(body) {
Ok(value) => value,
Err(text) => {
if !logged.swap(true, Ordering::AcqRel) {
let _ = catch(|| {
if let Some(host) = Host::current() {
host.log(
LogLevel::Error,
format_args!(
"{what}: the callback panicked ({text}); the game carries on, and later panics of this callback are not logged"
),
);
}
});
}
fallback
}
}
}
pub fn catch_panic<R>(what: &str, fallback: R, body: impl FnOnce() -> R) -> R {
match catch(body) {
Ok(value) => value,
Err(text) => {
let _ = catch(|| {
if let Some(host) = Host::current() {
host.log(
LogLevel::Error,
format_args!("{what} panicked ({text}); carrying on"),
);
}
});
fallback
}
}
}