Skip to main content

eframe/web/
web_runner.rs

1use core::cell::RefCell;
2use std::rc::Rc;
3
4use wasm_bindgen::prelude::*;
5
6use crate::{App, epi};
7
8use super::{
9    AppRunner, PanicHandler,
10    events::{self, ResizeObserverContext},
11    text_agent::TextAgent,
12};
13
14/// This is how `eframe` runs your web application
15///
16/// This is cheap to clone.
17///
18/// See [the crate level docs](crate) for an example.
19#[derive(Clone)]
20pub struct WebRunner {
21    /// Have we ever panicked?
22    panic_handler: PanicHandler,
23
24    /// If we ever panic during running, this `RefCell` is poisoned.
25    /// So before we use it, we need to check [`Self::panic_handler`].
26    app_runner: Rc<RefCell<Option<AppRunner>>>,
27
28    /// In case of a panic, unsubscribe these.
29    /// They have to be in a separate `Rc` so that we don't need to pass them to
30    /// the panic handler, since they aren't `Send`.
31    events_to_unsubscribe: Rc<RefCell<Vec<EventToUnsubscribe>>>,
32
33    /// Current animation frame in flight.
34    frame: Rc<RefCell<Option<AnimationFrameRequest>>>,
35
36    resize_observer: Rc<RefCell<Option<ResizeObserverContext>>>,
37}
38
39impl WebRunner {
40    /// Will install a panic handler that will catch and log any panics
41    #[expect(clippy::new_without_default)]
42    pub fn new() -> Self {
43        let panic_handler = PanicHandler::install();
44
45        Self {
46            panic_handler,
47            app_runner: Rc::new(RefCell::new(None)),
48            events_to_unsubscribe: Rc::new(RefCell::new(Default::default())),
49            frame: Default::default(),
50            resize_observer: Default::default(),
51        }
52    }
53
54    /// Create the application, install callbacks, and start running the app.
55    ///
56    /// # Errors
57    /// Failing to initialize graphics, or failure to create app.
58    pub async fn start(
59        &self,
60        canvas: web_sys::HtmlCanvasElement,
61        web_options: crate::WebOptions,
62        app_creator: epi::AppCreator<'static>,
63    ) -> Result<(), JsValue> {
64        self.destroy();
65
66        {
67            // Make sure the canvas can be given focus.
68            // https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
69            canvas.set_tab_index(0);
70
71            // Don't outline the canvas when it has focus:
72            canvas.style().set_property("outline", "none")?;
73        }
74
75        {
76            // First set up the app runner:
77            let text_agent = TextAgent::attach(self, &canvas)?;
78            let app_runner =
79                AppRunner::new(canvas.clone(), web_options, app_creator, text_agent).await?;
80            self.app_runner.replace(Some(app_runner));
81        }
82
83        {
84            let resize_observer = events::ResizeObserverContext::new(self)?;
85
86            // Properly size the canvas. Will also call `self.request_animation_frame()` (eventually)
87            resize_observer.observe(&canvas);
88
89            self.resize_observer.replace(Some(resize_observer));
90        }
91
92        events::install_event_handlers(self)?;
93
94        log::info!("event handlers installed.");
95
96        Ok(())
97    }
98
99    /// Has there been a panic?
100    pub fn has_panicked(&self) -> bool {
101        self.panic_handler.has_panicked()
102    }
103
104    /// What was the panic message and callstack?
105    pub fn panic_summary(&self) -> Option<super::PanicSummary> {
106        self.panic_handler.panic_summary()
107    }
108
109    fn unsubscribe_from_all_events(&self) {
110        let events_to_unsubscribe: Vec<_> =
111            core::mem::take(&mut *self.events_to_unsubscribe.borrow_mut());
112
113        if !events_to_unsubscribe.is_empty() {
114            log::debug!("Unsubscribing from {} events", events_to_unsubscribe.len());
115            for x in events_to_unsubscribe {
116                if let Err(err) = x.unsubscribe() {
117                    log::warn!(
118                        "Failed to unsubscribe from event: {}",
119                        super::string_from_js_value(&err)
120                    );
121                }
122            }
123        }
124
125        self.resize_observer.replace(None);
126    }
127
128    /// Shut down eframe and clean up resources.
129    pub fn destroy(&self) {
130        self.unsubscribe_from_all_events();
131
132        if let Some(frame) = self.frame.take() {
133            frame.cancel(&web_sys::window().unwrap());
134        }
135
136        if let Some(runner) = self.app_runner.replace(None) {
137            runner.destroy();
138        }
139    }
140
141    /// Returns `None` if there has been a panic, or if we have been destroyed.
142    /// In that case, just return to JS.
143    pub(crate) fn try_lock(&self) -> Option<core::cell::RefMut<'_, AppRunner>> {
144        if self.panic_handler.has_panicked() {
145            // Unsubscribe from all events so that we don't get any more callbacks
146            // that will try to access the poisoned runner.
147            self.unsubscribe_from_all_events();
148            None
149        } else {
150            let lock = self.app_runner.try_borrow_mut().ok()?;
151            core::cell::RefMut::filter_map(lock, |lock| -> Option<&mut AppRunner> { lock.as_mut() })
152                .ok()
153        }
154    }
155
156    /// Get mutable access to the concrete [`App`] we enclose.
157    ///
158    /// This will panic if your app does not implement [`App::as_any_mut`],
159    /// and return `None` if this  runner has panicked.
160    pub fn app_mut<ConcreteApp: 'static + App>(
161        &self,
162    ) -> Option<core::cell::RefMut<'_, ConcreteApp>> {
163        self.try_lock()
164            .map(|lock| core::cell::RefMut::map(lock, |runner| runner.app_mut::<ConcreteApp>()))
165    }
166
167    /// Convenience function to reduce boilerplate and ensure that all event handlers
168    /// are dealt with in the same way.
169    ///
170    /// All events added with this method will automatically be unsubscribed on panic,
171    /// or when [`Self::destroy`] is called.
172    pub fn add_event_listener<E: wasm_bindgen::JsCast>(
173        &self,
174        target: &web_sys::EventTarget,
175        event_name: &'static str,
176        mut closure: impl FnMut(E, &mut AppRunner) + 'static,
177    ) -> Result<(), wasm_bindgen::JsValue> {
178        let options = web_sys::AddEventListenerOptions::default();
179        self.add_event_listener_ex(
180            target,
181            event_name,
182            &options,
183            move |event, app_runner, _web_runner| closure(event, app_runner),
184        )
185    }
186
187    /// Convenience function to reduce boilerplate and ensure that all event handlers
188    /// are dealt with in the same way.
189    ///
190    /// All events added with this method will automatically be unsubscribed on panic,
191    /// or when [`Self::destroy`] is called.
192    pub fn add_event_listener_ex<E: wasm_bindgen::JsCast>(
193        &self,
194        target: &web_sys::EventTarget,
195        event_name: &'static str,
196        options: &web_sys::AddEventListenerOptions,
197        mut closure: impl FnMut(E, &mut AppRunner, &Self) + 'static,
198    ) -> Result<(), wasm_bindgen::JsValue> {
199        let web_runner = self.clone();
200
201        // Create a JS closure based on the FnMut provided
202        let closure = Closure::wrap(Box::new(move |event: web_sys::Event| {
203            // Only call the wrapped closure if the egui code has not panicked
204            if let Some(mut runner_lock) = web_runner.try_lock() {
205                // Cast the event to the expected event type
206                let event = event.unchecked_into::<E>();
207                closure(event, &mut runner_lock, &web_runner);
208            }
209        }) as Box<dyn FnMut(web_sys::Event)>);
210
211        // Add the event listener to the target
212        target.add_event_listener_with_callback_and_add_event_listener_options(
213            event_name,
214            closure.as_ref().unchecked_ref(),
215            options,
216        )?;
217
218        let handle = TargetEvent {
219            target: target.clone(),
220            event_name: event_name.to_owned(),
221            closure,
222        };
223
224        // Remember it so we unsubscribe on panic.
225        // Otherwise we get calls into `self.runner` after it has been poisoned by a panic.
226        self.events_to_unsubscribe
227            .borrow_mut()
228            .push(EventToUnsubscribe::TargetEvent(handle));
229
230        Ok(())
231    }
232
233    /// Request an animation frame from the browser in which we can perform a paint.
234    ///
235    /// It is safe to call `request_animation_frame` multiple times in quick succession,
236    /// this function guarantees that only one animation frame is scheduled at a time.
237    ///
238    /// A hidden browser tab (e.g. a backgrounded tab) does not receive
239    /// `requestAnimationFrame` callbacks, which would otherwise stop our paint loop
240    /// and prevent `App::update` from running in response to `request_repaint`.
241    /// To keep running in that case, we fall back to `setTimeout`, which keeps firing
242    /// while hidden (the browser throttles it to roughly once per second).
243    pub(crate) fn request_animation_frame(&self) -> Result<(), wasm_bindgen::JsValue> {
244        if self.frame.borrow().is_some() {
245            // there is already an animation frame in flight
246            return Ok(());
247        }
248
249        let window = web_sys::window().unwrap();
250        let closure = Closure::once({
251            let web_runner = self.clone();
252            move || {
253                // We can paint now, so clear the animation frame.
254                // This drops the `closure` and allows another
255                // animation frame to be scheduled
256                let _ = web_runner.frame.take();
257                events::paint_and_schedule(&web_runner)
258            }
259        });
260
261        let hidden = window.document().is_some_and(|document| document.hidden());
262
263        let request = if hidden {
264            // The tab is hidden: `requestAnimationFrame` would not fire, so use a timer instead.
265            let id = window.set_timeout_with_callback_and_timeout_and_arguments_0(
266                closure.as_ref().unchecked_ref(),
267                // Browsers clamp background timers to ~1s, so the exact value has little effect
268                // while hidden, but keeps us responsive right after the tab is hidden:
269                10,
270            )?;
271            AnimationFrameRequest {
272                id,
273                kind: AnimationFrameKind::Timeout,
274                _closure: closure,
275            }
276        } else {
277            let id = window.request_animation_frame(closure.as_ref().unchecked_ref())?;
278            AnimationFrameRequest {
279                id,
280                kind: AnimationFrameKind::AnimationFrame,
281                _closure: closure,
282            }
283        };
284
285        self.frame.borrow_mut().replace(request);
286
287        Ok(())
288    }
289
290    /// Cancel any in-flight frame request and schedule a fresh one.
291    ///
292    /// Called on `visibilitychange` so we switch between `requestAnimationFrame` (visible)
293    /// and `setTimeout` (hidden) scheduling. This is necessary because an in-flight
294    /// `requestAnimationFrame` is paused while the tab is hidden, which would otherwise
295    /// stall the paint loop and stop `App::update` from running while hidden.
296    pub(crate) fn reschedule_frame(&self) -> Result<(), wasm_bindgen::JsValue> {
297        if let Some(frame) = self.frame.borrow_mut().take() {
298            frame.cancel(&web_sys::window().unwrap());
299        }
300        self.request_animation_frame()
301    }
302}
303
304// ----------------------------------------------------------------------------
305
306// https://rustwasm.github.io/wasm-bindgen/api/wasm_bindgen/closure/struct.Closure.html#using-fnonce-and-closureonce-with-requestanimationframe
307struct AnimationFrameRequest {
308    /// Represents the ID of a frame in flight.
309    id: i32,
310
311    /// How the frame was scheduled, so we know how to cancel it.
312    kind: AnimationFrameKind,
313
314    /// The callback given to `request_animation_frame`, stored here both to prevent it
315    /// from being canceled, and from having to `.forget()` it.
316    _closure: Closure<dyn FnMut() -> Result<(), JsValue>>,
317}
318
319impl AnimationFrameRequest {
320    /// Cancel the in-flight frame request, using the API matching how it was scheduled.
321    fn cancel(&self, window: &web_sys::Window) {
322        match self.kind {
323            AnimationFrameKind::AnimationFrame => {
324                window.cancel_animation_frame(self.id).ok();
325            }
326            AnimationFrameKind::Timeout => {
327                window.clear_timeout_with_handle(self.id);
328            }
329        }
330    }
331}
332
333/// How an [`AnimationFrameRequest`] was scheduled.
334enum AnimationFrameKind {
335    /// Scheduled with `requestAnimationFrame` (visible tab).
336    AnimationFrame,
337
338    /// Scheduled with `setTimeout` (hidden tab).
339    Timeout,
340}
341
342struct TargetEvent {
343    target: web_sys::EventTarget,
344    event_name: String,
345    closure: Closure<dyn FnMut(web_sys::Event)>,
346}
347
348#[expect(unused)]
349struct IntervalHandle {
350    handle: i32,
351    closure: Closure<dyn FnMut()>,
352}
353
354enum EventToUnsubscribe {
355    TargetEvent(TargetEvent),
356
357    #[expect(unused)]
358    IntervalHandle(IntervalHandle),
359}
360
361impl EventToUnsubscribe {
362    pub fn unsubscribe(self) -> Result<(), JsValue> {
363        match self {
364            Self::TargetEvent(handle) => {
365                handle.target.remove_event_listener_with_callback(
366                    handle.event_name.as_str(),
367                    handle.closure.as_ref().unchecked_ref(),
368                )?;
369                Ok(())
370            }
371            Self::IntervalHandle(handle) => {
372                let window = web_sys::window().unwrap();
373                window.clear_interval_with_handle(handle.handle);
374                Ok(())
375            }
376        }
377    }
378}