Fix crash on request_animation_frame when destroying web runner (#4169)

Previously, any frames in flight (`requestAnimationFrame`) on web were
not being cancelled (`cancelAnimationFrame`) when `WebRunner::destroy`
was called. If a user called `destroy`, then immediately removed the
canvas from the DOM, eframe could panic with a "failed to find (canvas)
element by id" error message.

This PR changes two things:
- The canvas element is directly referenced everywhere it's needed
instead of being looked up by `canvas_id`[^1]
- The RAF handle is stored in `WebRunner` and `cancelAnimationFrame` is
called on it inside of `WebRunner::destroy`[^2]

[^1]: The WebGL/WGPU backends were already holding onto the canvas (and
associated GPU context), so the change is just converting all the
`get_element_by_id` lookups to retrieve the canvas from the web runner
handle.

[^2]: There is only ever one frame in flight, so we store it directly as
a scalar field.
This commit is contained in:
Jan Procházka
2024-03-14 10:26:34 +01:00
committed by GitHub
parent 00e8ce6d7e
commit c5eaba43cd
9 changed files with 73 additions and 61 deletions
+26 -2
View File
@@ -1,4 +1,7 @@
use std::{cell::RefCell, rc::Rc};
use std::{
cell::{Cell, RefCell},
rc::Rc,
};
use wasm_bindgen::prelude::*;
@@ -24,6 +27,9 @@ pub struct WebRunner {
/// They have to be in a separate `Rc` so that we don't need to pass them to
/// the panic handler, since they aren't `Send`.
events_to_unsubscribe: Rc<RefCell<Vec<EventToUnsubscribe>>>,
/// Used in `destroy` to cancel a pending frame.
request_animation_frame_id: Cell<Option<i32>>,
}
impl WebRunner {
@@ -41,6 +47,7 @@ impl WebRunner {
panic_handler,
runner: Rc::new(RefCell::new(None)),
events_to_unsubscribe: Rc::new(RefCell::new(Default::default())),
request_animation_frame_id: Cell::new(None),
}
}
@@ -71,7 +78,7 @@ impl WebRunner {
events::install_color_scheme_change_event(self)?;
}
events::request_animation_frame(self.clone())?;
self.request_animation_frame()?;
}
Ok(())
@@ -108,6 +115,11 @@ impl WebRunner {
pub fn destroy(&self) {
self.unsubscribe_from_all_events();
if let Some(id) = self.request_animation_frame_id.get() {
let window = web_sys::window().unwrap();
window.cancel_animation_frame(id).ok();
}
if let Some(runner) = self.runner.replace(None) {
runner.destroy();
}
@@ -179,6 +191,18 @@ impl WebRunner {
Ok(())
}
pub(crate) fn request_animation_frame(&self) -> Result<(), wasm_bindgen::JsValue> {
let window = web_sys::window().unwrap();
let closure = Closure::once({
let runner_ref = self.clone();
move || events::paint_and_schedule(&runner_ref)
});
let id = window.request_animation_frame(closure.as_ref().unchecked_ref())?;
self.request_animation_frame_id.set(Some(id));
closure.forget(); // We must forget it, or else the callback is canceled on drop
Ok(())
}
}
// ----------------------------------------------------------------------------