Skip to main content

blitz_shell/
application.rs

1use crate::event::{BlitzShellEvent, BlitzShellEventQueue, BlitzShellProxy};
2
3use anyrender::WindowRenderer;
4use std::collections::HashMap;
5use std::sync::Arc;
6use winit::application::ApplicationHandler;
7use winit::event::WindowEvent;
8use winit::event_loop::ActiveEventLoop;
9use winit::event_loop::ControlFlow;
10use winit::window::WindowId;
11
12#[cfg(target_os = "macos")]
13use winit::platform::macos::ApplicationHandlerExtMacOS;
14
15use crate::{View, WindowConfig};
16
17#[cfg(feature = "debug-control")]
18type DebugService<Rend> = fn(&mut View<Rend>, &mut blitz_script::DebugController) -> bool;
19
20pub struct BlitzApplication<Rend: WindowRenderer> {
21    pub windows: HashMap<WindowId, View<Rend>>,
22    pub pending_windows: Vec<WindowConfig<Rend>>,
23    pub proxy: BlitzShellProxy,
24    pub event_queue: BlitzShellEventQueue,
25    #[cfg(feature = "debug-control")]
26    debug_controller: Option<(blitz_script::DebugController, DebugService<Rend>)>,
27}
28
29impl<Rend: WindowRenderer> BlitzApplication<Rend> {
30    pub fn new(proxy: BlitzShellProxy, event_queue: BlitzShellEventQueue) -> Self {
31        BlitzApplication {
32            windows: HashMap::new(),
33            pending_windows: Vec::new(),
34            proxy,
35            event_queue,
36            #[cfg(feature = "debug-control")]
37            debug_controller: None,
38        }
39    }
40
41    pub fn add_window(&mut self, window_config: WindowConfig<Rend>) {
42        self.pending_windows.push(window_config);
43    }
44
45    #[cfg(feature = "debug-control")]
46    pub fn set_debug_controller_for<D: blitz_script::DebugDocument + 'static>(
47        &mut self,
48        controller: blitz_script::DebugController,
49    ) {
50        // The server thread wakes the loop when a request lands, the same way
51        // everything else here does. Before this the loop woke itself every
52        // 10ms to look: 100 wakeups a second at idle, up to 10ms of latency on
53        // each command, and a floor under every measurement taken with the
54        // driver attached, which is most of them.
55        let proxy = self.proxy.clone();
56        controller.set_waker(move || proxy.wake_up());
57        let service: DebugService<Rend> = |view, controller| {
58            let animation_time = view.current_animation_time();
59            let Some(document) = view.try_downcast_doc_mut::<D>() else {
60                return false;
61            };
62            controller.service_pending_at(document, animation_time);
63            true
64        };
65        self.debug_controller = Some((controller, service));
66    }
67
68    #[cfg(feature = "debug-control")]
69    fn service_debug_controller(&mut self, event_loop: &dyn ActiveEventLoop) {
70        let (Some((controller, service)), windows) =
71            (self.debug_controller.as_mut(), &mut self.windows)
72        else {
73            return;
74        };
75        let serviced = windows.values_mut().any(|view| service(view, controller));
76        if !serviced {
77            // No document to run against yet. The request stays queued, and
78            // whatever creates the window brings the loop round again.
79            return;
80        }
81        if controller.exit_requested() {
82            event_loop.exit();
83        }
84    }
85
86    fn window_mut_by_doc_id(&mut self, doc_id: usize) -> Option<&mut View<Rend>> {
87        self.windows.values_mut().find(|w| w.doc.id() == doc_id)
88    }
89
90    pub fn handle_blitz_shell_event(
91        &mut self,
92        event_loop: &dyn ActiveEventLoop,
93        event: BlitzShellEvent,
94    ) {
95        match event {
96            BlitzShellEvent::Poll { window_id } => {
97                // Kept for embedders that send it. The poll itself happens in
98                // `about_to_wait` with every other request, which runs before
99                // the loop sleeps, so this is not deferred past this turn.
100                if let Some(window) = self.windows.get(&window_id) {
101                    window.request_poll();
102                };
103            }
104            BlitzShellEvent::CloseWindow { window_id } => {
105                // Drop window before exiting event loop
106                // See https://github.com/rust-windowing/winit/issues/4135
107                let window = self.windows.remove(&window_id);
108                drop(window);
109                if self.windows.is_empty() {
110                    event_loop.exit();
111                }
112            }
113            BlitzShellEvent::ResumeReady { window_id } => {
114                // The renderer fires `on_ready` after it has sent on the
115                // channel, so `complete_resume` should always succeed here.
116                // If a stale event survives a suspend, dropping it is safe.
117                let _paint_committed = if let Some(window) = self.windows.get_mut(&window_id)
118                    && window.waker.is_none()
119                {
120                    let ok = window.complete_resume();
121                    debug_assert!(ok, "ResumeReady received but renderer not ready");
122                    ok
123                } else {
124                    false
125                };
126                #[cfg(feature = "debug-control")]
127                if _paint_committed && let Some((controller, _)) = self.debug_controller.as_mut() {
128                    controller.note_paint_committed();
129                }
130            }
131            BlitzShellEvent::RequestRedraw { doc_id } => {
132                // TODO: Handle multiple documents per window
133                if let Some(window) = self.window_mut_by_doc_id(doc_id) {
134                    window.request_redraw();
135                }
136            }
137
138            #[cfg(feature = "accessibility")]
139            BlitzShellEvent::Accessibility { window_id, data } => {
140                if let Some(window) = self.windows.get_mut(&window_id) {
141                    match &*data {
142                        accesskit_xplat::WindowEvent::InitialTreeRequested => {
143                            window.build_accessibility_tree();
144                        }
145                        accesskit_xplat::WindowEvent::AccessibilityDeactivated => {
146                            // TODO
147                        }
148                        accesskit_xplat::WindowEvent::ActionRequested(_req) => {
149                            // TODO
150                        }
151                    }
152                }
153            }
154            BlitzShellEvent::Embedder(_) => {
155                // Do nothing. Should be handled by embedders (if required).
156            }
157            BlitzShellEvent::Navigate(_opts) => {
158                // Do nothing. Should be handled by embedders (if required).
159            }
160            BlitzShellEvent::NavigationLoad { .. } => {
161                // Do nothing. Should be handled by embedders (if required).
162            }
163            #[cfg(target_arch = "wasm32")]
164            BlitzShellEvent::ResizeSettleCheck { window_id } => {
165                if let Some(window) = self.windows.get_mut(&window_id) {
166                    window.apply_pending_resize_if_settled();
167                }
168            }
169        }
170    }
171}
172
173impl<Rend: WindowRenderer> ApplicationHandler for BlitzApplication<Rend> {
174    fn can_create_surfaces(&mut self, event_loop: &dyn ActiveEventLoop) {
175        #[cfg(feature = "debug-control")]
176        let mut committed_frames = 0usize;
177        // Resume existing windows
178        for view in self.windows.values_mut() {
179            view.resume();
180            #[cfg(not(target_arch = "wasm32"))]
181            {
182                let ok = view.complete_resume();
183                debug_assert!(ok, "native renderer did not resume synchronously");
184                #[cfg(feature = "debug-control")]
185                if ok {
186                    committed_frames += 1;
187                }
188            }
189        }
190
191        // Initialise pending windows. The renderer's resume is non-blocking. On
192        // native it finishes inline; on wasm32 it spawns a future that will
193        // dispatch BlitzShellEvent::ResumeReady when init completes. Either way
194        // we insert the view immediately so the event handler can find it.
195        for window_config in self.pending_windows.drain(..) {
196            let mut view = View::init(window_config, event_loop, &self.proxy);
197            view.resume();
198            #[cfg(not(target_arch = "wasm32"))]
199            {
200                let ok = view.complete_resume();
201                debug_assert!(ok, "native renderer did not resume synchronously");
202                #[cfg(feature = "debug-control")]
203                if ok {
204                    committed_frames += 1;
205                }
206            }
207            self.windows.insert(view.window_id(), view);
208        }
209        #[cfg(feature = "debug-control")]
210        if let Some((controller, _)) = self.debug_controller.as_mut() {
211            for _ in 0..committed_frames {
212                controller.note_paint_committed();
213            }
214        }
215    }
216
217    fn destroy_surfaces(&mut self, _event_loop: &dyn ActiveEventLoop) {
218        for view in self.windows.values_mut() {
219            view.suspend();
220        }
221    }
222
223    fn resumed(&mut self, _event_loop: &dyn ActiveEventLoop) {
224        // TODO
225    }
226
227    fn suspended(&mut self, _event_loop: &dyn ActiveEventLoop) {
228        // TODO
229    }
230
231    fn window_event(
232        &mut self,
233        event_loop: &dyn ActiveEventLoop,
234        window_id: WindowId,
235        event: WindowEvent,
236    ) {
237        // Exit the app when window close is requested.
238        if matches!(event, WindowEvent::CloseRequested) {
239            // Drop window before exiting event loop
240            // See https://github.com/rust-windowing/winit/issues/4135
241            let window = self.windows.remove(&window_id);
242            drop(window);
243            if self.windows.is_empty() {
244                event_loop.exit();
245            }
246            return;
247        }
248
249        let _paint_committed = if let Some(window) = self.windows.get_mut(&window_id) {
250            let committed = window.handle_winit_event(event);
251            // Flag rather than a queued event and a wake: this runs on the
252            // event loop's own thread, `about_to_wait` follows before the loop
253            // sleeps, and a drag delivers hundreds of these a second.
254            window.request_poll();
255            committed
256        } else {
257            false
258        };
259        #[cfg(feature = "debug-control")]
260        if _paint_committed && let Some((controller, _)) = self.debug_controller.as_mut() {
261            controller.note_paint_committed();
262        }
263    }
264
265    fn proxy_wake_up(&mut self, event_loop: &dyn ActiveEventLoop) {
266        for event in self.event_queue.take_pending() {
267            let event =
268                Arc::try_unwrap(event).unwrap_or_else(|_| panic!("shell event has one consumer"));
269            self.handle_blitz_shell_event(event_loop, event);
270        }
271        #[cfg(feature = "debug-control")]
272        self.service_debug_controller(event_loop);
273    }
274
275    #[cfg(target_os = "macos")]
276    fn macos_handler(&mut self) -> Option<&mut dyn ApplicationHandlerExtMacOS> {
277        Some(self)
278    }
279
280    fn about_to_wait(&mut self, event_loop: &dyn ActiveEventLoop) {
281        let _ = event_loop;
282        #[cfg(feature = "debug-control")]
283        self.service_debug_controller(event_loop);
284
285        // Every poll asked for since the loop last slept, coalesced to one per
286        // window. Before the animation deadline below, because a poll is what
287        // schedules the next animation frame.
288        for window in self.windows.values_mut() {
289            window.poll_if_requested();
290        }
291
292        #[cfg(target_os = "ios")]
293        for view in self.windows.values_mut() {
294            if view.ios_request_redraw.get() {
295                view.window.request_redraw();
296            }
297        }
298
299        // Animation frames are paced here rather than requested at the end of
300        // the last one, which is what would run them at the display's rate. The
301        // earliest deadline across every window becomes the wait, so a window
302        // that is animating does not stop the others sleeping.
303        //
304        // Restored to `Wait` when nothing is animating, rather than left alone.
305        //
306        // `ControlFlow::Wait` is the default, but it is not what the loop is
307        // still set to once an animation has ended: the last frame's
308        // `WaitUntil` stays in force, its deadline is already in the past, and
309        // the loop then wakes immediately, forever, with nothing to do. It
310        // costs 76% of a core on an idle window, and it is invisible in a
311        // profile of the app because no frame of ours is on the stack: the
312        // whole main thread sits in `__CFRunLoopDoTimers` re-arming a timer.
313        //
314        // web_time, not std: on wasm they are genuinely distinct types, and
315        // both `poll_animation_frame` and winit's own `ControlFlow::WaitUntil`
316        // are in web_time's. On native web_time re-exports std's, which is why
317        // std compiled here and broke only the wasm job.
318        let now = web_time::Instant::now();
319        let next_frame = self
320            .windows
321            .values()
322            .filter_map(|view| view.poll_animation_frame(now))
323            .min();
324        if let Some(deadline) = next_frame {
325            event_loop.set_control_flow(ControlFlow::WaitUntil(deadline));
326        } else {
327            event_loop.set_control_flow(ControlFlow::Wait);
328        }
329    }
330}
331
332#[cfg(target_os = "macos")]
333impl<Rend: WindowRenderer> ApplicationHandlerExtMacOS for BlitzApplication<Rend> {
334    fn standard_key_binding(
335        &mut self,
336        _event_loop: &dyn ActiveEventLoop,
337        window_id: WindowId,
338        action: &str,
339    ) {
340        if let Some(window) = self.windows.get_mut(&window_id) {
341            window.handle_apple_standard_keybinding(action);
342            window.request_poll();
343        }
344    }
345}