use std::any::Any;
use std::cell::Cell;
use std::panic;
use std::sync::Mutex;
thread_local! {
static LAYOUT_THREAD: Cell<bool> = const { Cell::new(false) };
}
static NOTED: Mutex<Option<String>> = Mutex::new(None);
pub(crate) fn keep_hook_off_layout_threads() {
let hook = panic::take_hook();
panic::set_hook(Box::new(move |info| {
if LAYOUT_THREAD.with(Cell::get) {
if let Ok(mut noted) = NOTED.lock() {
noted.get_or_insert_with(|| info.to_string());
}
} else {
hook(info);
}
}));
}
pub(super) fn as_layout_thread<R>(work: impl FnOnce() -> R) -> R {
LAYOUT_THREAD.with(|flag| flag.set(true));
work()
}
pub(super) fn carry_on(payload: Box<dyn Any + Send>) -> ! {
if LAYOUT_THREAD.with(Cell::get) {
panic::resume_unwind(payload);
}
let noted = NOTED.lock().ok().and_then(|mut noted| noted.take());
let message = noted.unwrap_or_else(|| {
let text = payload.downcast_ref::<&str>().copied();
text.or_else(|| payload.downcast_ref::<String>().map(String::as_str)).unwrap_or("panicked").to_owned()
});
#[allow(clippy::panic, reason = "the layout thread panicked; the app ends as on its own panic")]
{
panic!("layout thread {message}")
}
}