use ferrokit_core::kept::{UiCell, UiLocal};
use std::panic::AssertUnwindSafe;
use std::rc::Rc;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Failure {
pub place: &'static str,
pub message: String,
pub exception: bool,
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let what = if self.exception { "an Objective-C exception" } else { "a panic" };
write!(f, "{what} in {}: {}", self.place, self.message)
}
}
type Hook = Rc<dyn Fn(&Failure)>;
thread_local! {
static FAILURES: UiCell<Vec<Failure>> = const { UiCell::new(Vec::new()) };
static HOOK: UiCell<Option<Hook>> = const { UiCell::new(None) };
}
pub(crate) fn guard<R>(place: &'static str, fallback: R, f: impl FnOnce() -> R) -> R {
let caught = crate::crash::catching(|| std::panic::catch_unwind(AssertUnwindSafe(|| objc2::exception::catch(AssertUnwindSafe(f)))));
let failure = match caught {
Ok(Ok(r)) => return r,
Err(payload) => {
let message = payload.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| payload.downcast_ref::<String>().cloned()).unwrap_or_else(|| "(no message)".into());
Failure { place, message, exception: false }
}
Ok(Err(exception)) => {
let message = exception.as_deref().map_or_else(|| "(nil)".into(), |e| {
let (name, reason): (Option<objc2::rc::Retained<objc2_foundation::NSString>>, Option<objc2::rc::Retained<objc2_foundation::NSString>>) =
unsafe { (objc2::msg_send![e, name], objc2::msg_send![e, reason]) };
format!("{}: {}", name.map(|n| n.to_string()).unwrap_or_default(), reason.map(|r| r.to_string()).unwrap_or_default())
});
Failure { place, message, exception: true }
}
};
report(failure);
fallback
}
pub(crate) fn entry<R>(place: &'static str, fallback: R, f: impl FnOnce() -> R) -> R {
guard(place, fallback, || crate::signal::batch(f))
}
pub(crate) fn install() {
ferrokit_core::boundary::set_guard(|place, f| guard(place, (), f));
}
pub(crate) fn report(failure: Failure) {
eprintln!("ferrokit: {failure} (the app goes on)");
let _ = FAILURES.try_with(|f| {
let mut f = f.borrow_mut();
if f.len() >= 100 {
f.remove(0);
}
f.push(failure.clone());
});
let hook = HOOK.try_with(|h| h.borrow().clone()).ok().flatten();
if let Some(hook) = hook {
let _ = std::panic::catch_unwind(AssertUnwindSafe(|| hook(&failure)));
}
}
pub(crate) fn set_hook(f: impl Fn(&Failure) + 'static) {
HOOK.with_borrow_mut(|h| *h = Some(Rc::new(f)));
}
pub(crate) fn caught() -> Vec<Failure> {
FAILURES.with_borrow(Clone::clone)
}