blitz_shell/
application.rs1use 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 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 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 if let Some(window) = self.windows.get(&window_id) {
101 window.request_poll();
102 };
103 }
104 BlitzShellEvent::CloseWindow { window_id } => {
105 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 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 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 }
148 accesskit_xplat::WindowEvent::ActionRequested(_req) => {
149 }
151 }
152 }
153 }
154 BlitzShellEvent::Embedder(_) => {
155 }
157 BlitzShellEvent::Navigate(_opts) => {
158 }
160 BlitzShellEvent::NavigationLoad { .. } => {
161 }
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 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 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 }
226
227 fn suspended(&mut self, _event_loop: &dyn ActiveEventLoop) {
228 }
230
231 fn window_event(
232 &mut self,
233 event_loop: &dyn ActiveEventLoop,
234 window_id: WindowId,
235 event: WindowEvent,
236 ) {
237 if matches!(event, WindowEvent::CloseRequested) {
239 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 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 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 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}