Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

eframe web: detect and report panics during startup #2992

Merged
Prev Previous commit
Next Next commit
Add example of how to call into your app from JS
  • Loading branch information
emilk committed May 16, 2023
commit 5a60c6b279d0ecbc18ffb93fa1ce30fa6059ee72
13 changes: 12 additions & 1 deletion crates/eframe/src/web/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ impl AppRunner {
.as_any_mut()
.expect("Your app must implement `as_any_mut`, but it doesn't")
.downcast_mut::<ConcreteApp>()
.unwrap()
.expect("app_mut got the wrong type of App")
}

pub fn auto_save_if_needed(&mut self) {
Expand Down Expand Up @@ -510,6 +510,17 @@ impl AppRunnerRef {
}
}

/// Get mutable access to the concrete [`App`] we enclose.
///
/// This will panic if your app does not implement [`App::as_any_mut`],
/// and return `None` if this runner has panicked.
pub fn app_mut<ConcreteApp: 'static + App>(
&self,
) -> Option<std::cell::RefMut<'_, ConcreteApp>> {
self.try_lock()
.map(|lock| std::cell::RefMut::map(lock, |runner| runner.app_mut::<ConcreteApp>()))
}

/// Convenience function to reduce boilerplate and ensure that all event handlers
/// are dealt with in the same way
pub fn add_event_listener<E: wasm_bindgen::JsCast>(
Expand Down
12 changes: 11 additions & 1 deletion crates/egui_demo_app/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl WebHandle {
#[allow(clippy::new_without_default)]
#[wasm_bindgen(constructor)]
pub fn new() -> Self {
// Redirect tracing to console.log and friends:
// Redirect [`log`] message to `console.log` and friends:
eframe::web::WebLogger::init(log::LevelFilter::Debug).ok();

// Install a panic handler right away so we can catch any panics
Expand Down Expand Up @@ -57,6 +57,16 @@ impl WebHandle {
}
}

/// Example on how to call into your app from JavaScript.
#[wasm_bindgen]
pub fn example(&self) {
if let Some(runner) = &*self.runner.lock() {
if let Some(_app) = runner.app_mut::<WrapApp>() {
// _app.example();
}
}
}

#[wasm_bindgen]
pub fn has_panicked(&self) -> bool {
self.panic_handler.has_panicked()
Expand Down