From fe4f0bf57aaa99617dd30bf9fe37e7724c40e6e9 Mon Sep 17 00:00:00 2001 From: Wez Furlong Date: Thu, 19 Dec 2019 10:42:12 -0800 Subject: [PATCH] catch panic -> toast notification This is useful when launched from a gui launcher and the stderr is not conveniently visible. If a panic occurs, generate a toast notification with the panic message so that there is a breadcrumb to follow if the application does terminate in this way. Every so often I encounter this situation on my windows machine during a graphics card driver update, so this should help to run that down. --- src/main.rs | 45 ++++++++++++++++++++++++++++++++++++--------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1e4436ad7..d50b8a075 100644 --- a/src/main.rs +++ b/src/main.rs @@ -596,22 +596,49 @@ fn toast_notification(title: &str, message: &str) { #[cfg(windows)] { - use winrt_notification::Toast; + let title = title.to_owned(); + let message = message.to_owned(); - Toast::new(Toast::POWERSHELL_APP_ID) - .title(title) - .text1(message) - .duration(winrt_notification::Duration::Long) - .show() - .ok(); + // We need to be in a different thread from the caller + // in case we get called in the guts of a windows message + // loop dispatch and are unable to pump messages + std::thread::spawn(move || { + use winrt_notification::Toast; + + Toast::new(Toast::POWERSHELL_APP_ID) + .title(&title) + .text1(&message) + .duration(winrt_notification::Duration::Long) + .show() + .ok(); + }); } } +fn fatal_toast_notification(title: &str, message: &str) { + toast_notification(title, message); + // We need a short delay otherwise the notification + // will not show + #[cfg(windows)] + std::thread::sleep(std::time::Duration::new(2, 0)); +} + +fn notify_on_panic() { + let default_hook = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + if let Some(s) = info.payload().downcast_ref::<&str>() { + fatal_toast_notification("Wezterm panic", s); + } + default_hook(info); + })); +} + fn main() { + notify_on_panic(); if let Err(e) = run() { let err = format!("{:#}", e); - log::error!("{}", err); - toast_notification("Wezterm Error", &err); + log::error!("{}; terminating", err); + fatal_toast_notification("Wezterm Error", &err); std::process::exit(1); } }