agg_gui_shell/shell_loop.rs
1//! The event loop body: every winit event the shell reacts to, the reactive
2//! control-flow ladder, and device-loss recovery.
3//!
4//! [`crate::run`] builds a [`ShellLoop`] and hands it to `EventLoop::run`; all
5//! the per-event state (cursor position, modifiers, held buttons, coalesced
6//! resize, screenshot progress, window bounds) lives here rather than in a
7//! stack of captured locals.
8
9use std::cell::{Cell, RefCell};
10use std::rc::Rc;
11use std::sync::Arc;
12use std::time::Instant;
13
14use agg_gui::{winit_adapter, App, Modifiers};
15use agg_gui_wgpu::{Gpu, GpuConfig};
16use winit::event::{ElementState, Event, StartCause, WindowEvent};
17use winit::event_loop::{ActiveEventLoop, ControlFlow};
18use winit::window::{Fullscreen, Window};
19
20use crate::bounds::{BoundsAutoSave, SavedBounds, WindowBoundsStore, WindowedSizeTracker};
21use crate::config::{RedrawPolicy, ScreenshotConfig};
22use crate::host::{ExitAction, ShellControl, ShellHost, WindowGeometry};
23use crate::input::{dispatch_touch, shift_held, wheel_delta};
24use crate::paint::{PaintRequest, Painter};
25use crate::screenshot::capture_exhausted;
26use crate::waker::HostWakerGuard;
27use crate::ShellError;
28
29/// Owns everything the running shell touches. One instance is moved into the
30/// winit callback.
31pub(crate) struct ShellLoop<H: ShellHost> {
32 pub(crate) window: Arc<Window>,
33 /// `None` only during device-loss recovery, where the dead device and its
34 /// surface are dropped before the replacement is created — two live
35 /// surfaces on one window is not portable. Every user early-returns
36 /// instead of unwrapping.
37 pub(crate) gpu: Option<Gpu>,
38 pub(crate) gpu_config: GpuConfig,
39 pub(crate) painter: Painter,
40 pub(crate) app: App,
41 pub(crate) host: H,
42 pub(crate) policy: RedrawPolicy,
43 pub(crate) screenshot: Option<ScreenshotConfig>,
44 pub(crate) screenshot_done: bool,
45 /// When a pending capture last saw a painted frame — the wall-clock budget
46 /// that stops a surface which never becomes presentable from spinning
47 /// forever.
48 pub(crate) screenshot_last_paint: Instant,
49 pub(crate) cursor: (f64, f64),
50 pub(crate) mods: Modifiers,
51 pub(crate) mouse_buttons_down: u32,
52 pub(crate) input_since_frame: bool,
53 pub(crate) pending_resize: Option<(u32, u32)>,
54 pub(crate) bounds_store: Option<Box<dyn WindowBoundsStore>>,
55 pub(crate) bounds_auto: BoundsAutoSave,
56 /// Last size seen while the window was neither maximized nor fullscreen —
57 /// what gets persisted, so a restore doesn't reopen a windowed window at
58 /// the maximized rect.
59 pub(crate) windowed_size: WindowedSizeTracker,
60 pub(crate) maximized: bool,
61 pub(crate) exit: Rc<Cell<Option<ExitAction>>>,
62 pub(crate) error: Rc<RefCell<Option<ShellError>>>,
63 pub(crate) finished: bool,
64 /// Clears the `agg_gui` host waker when the loop is dropped, whichever way
65 /// the loop ended.
66 pub(crate) _waker_guard: HostWakerGuard,
67}
68
69impl<H: ShellHost> ShellLoop<H> {
70 pub(crate) fn handle(&mut self, event: Event<()>, elwt: &ActiveEventLoop) {
71 match event {
72 Event::WindowEvent { event, .. } => self.window_event(event, elwt),
73
74 // A scheduled `WaitUntil` deadline fired. Belt-and-braces only:
75 // the scheduled channel is read non-destructively
76 // (`peek_next_draw_deadline`) and a due deadline surfaces through
77 // `wants_draw()` on the next `AboutToWait`, so correctness does not
78 // depend on catching this event — it only trims latency.
79 Event::NewEvents(StartCause::ResumeTimeReached { .. }) => {
80 self.window.request_redraw();
81 }
82
83 // A background thread signalled agg-gui, which woke us through the
84 // installed host waker. Bump the invalidation epoch so the next
85 // paint re-runs layout: work that landed off-thread (a decoded
86 // image, a fetched document, a new video frame) is usually pulled
87 // in from `layout()`, which the layout-skip key would otherwise
88 // skip. Note `request_draw` does NOT re-enter the waker, so this
89 // cannot loop.
90 Event::UserEvent(()) => {
91 agg_gui::animation::request_draw();
92 }
93
94 Event::AboutToWait => self.about_to_wait(elwt),
95
96 Event::LoopExiting => self.finish(),
97
98 _ => {}
99 }
100 }
101
102 fn window_event(&mut self, event: WindowEvent, elwt: &ActiveEventLoop) {
103 match event {
104 WindowEvent::CloseRequested => {
105 // The host may veto (unsaved-changes gate) or defer the close
106 // — see `ShellHost::on_close_requested`.
107 if self.host.on_close_requested(&mut self.app) {
108 elwt.exit();
109 }
110 }
111
112 WindowEvent::Resized(size) if size.width > 0 && size.height > 0 => {
113 // Coalesced, applied at the top of the next paint: winit can
114 // deliver `Resized` from a modal drag-resize loop, and
115 // reconfiguring the surface between acquire and present is a
116 // validation error.
117 self.pending_resize = Some((size.width, size.height));
118 self.maximized = self.window.is_maximized();
119 // winit's `Resized` reports PHYSICAL px. That is the canonical
120 // stored unit — it must round-trip through `PhysicalSize` on
121 // restore, never `LogicalSize`, or the size ratchets up by the
122 // DPI scale factor every launch.
123 self.windowed_size.note_resize(
124 (size.width, size.height),
125 self.maximized,
126 self.window.fullscreen().is_some(),
127 );
128 self.notify_geometry();
129 self.window.request_redraw();
130 }
131
132 WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
133 agg_gui::set_device_scale(scale_factor);
134 self.notify_geometry();
135 self.window.request_redraw();
136 }
137
138 WindowEvent::CursorMoved { position, .. } => {
139 self.cursor = (position.x, position.y);
140 self.input_since_frame = true;
141 self.app.on_mouse_move(self.cursor.0, self.cursor.1);
142 winit_adapter::apply_cursor(&self.window, agg_gui::current_cursor_icon());
143 }
144
145 WindowEvent::CursorLeft { .. } => {
146 self.app.on_mouse_leave();
147 }
148
149 WindowEvent::ModifiersChanged(state) => {
150 self.mods = winit_adapter::modifiers(state.state());
151 }
152
153 WindowEvent::MouseInput { state, button, .. } => {
154 let btn = winit_adapter::mouse_button(button);
155 self.input_since_frame = true;
156 let (x, y) = self.cursor;
157 match state {
158 ElementState::Pressed => {
159 self.mouse_buttons_down = self.mouse_buttons_down.saturating_add(1);
160 self.app.on_mouse_down(x, y, btn, self.mods);
161 }
162 ElementState::Released => {
163 self.mouse_buttons_down = self.mouse_buttons_down.saturating_sub(1);
164 self.app.on_mouse_up(x, y, btn, self.mods);
165 }
166 }
167 }
168
169 WindowEvent::MouseWheel { delta, .. } => {
170 self.input_since_frame = true;
171 let (dx, dy) = wheel_delta(delta, shift_held(self.mods));
172 let (x, y) = self.cursor;
173 self.app.on_mouse_wheel_xy_mods(x, y, dx, dy, self.mods);
174 }
175
176 WindowEvent::KeyboardInput {
177 event: key_event, ..
178 } => {
179 self.input_since_frame = true;
180 let Some(key) = winit_adapter::key_event(&key_event, self.mods) else {
181 return;
182 };
183 match key_event.state {
184 ElementState::Pressed => self.app.on_key_down(key, self.mods),
185 // Key-up matters: chord state, drag modifiers and
186 // held-key repeat all end here. A shell that only
187 // dispatches key-down leaves the app with a stuck key.
188 ElementState::Released => self.app.on_key_up(key, self.mods),
189 }
190 }
191
192 WindowEvent::DroppedFile(path) => {
193 self.input_since_frame = true;
194 // winit emits one DroppedFile per file in a multi-file drop;
195 // forward each separately at the drop position.
196 //
197 // The tracked cursor is STALE here on Windows: the OS owns the
198 // pointer during an OLE drag, winit emits no CursorMoved for
199 // it, and its IDropTarget::Drop discards the drop point — so
200 // `self.cursor` still says wherever the mouse was before the
201 // drag began. Query the live cursor instead; fall back to the
202 // tracked position on other platforms.
203 let (x, y) = crate::input::live_cursor_in_window(&self.window)
204 .unwrap_or(self.cursor);
205 self.app.on_file_dropped(x, y, vec![path]);
206 }
207
208 WindowEvent::Touch(touch) => {
209 self.input_since_frame = true;
210 dispatch_touch(&mut self.app, touch);
211 // Touch events arrive outside the mouse arms' redraw
212 // signalling — request a frame so gestures render live.
213 self.window.request_redraw();
214 }
215
216 WindowEvent::RedrawRequested => {
217 self.paint(elwt);
218 }
219
220 _ => {}
221 }
222 }
223
224 fn about_to_wait(&mut self, elwt: &ActiveEventLoop) {
225 // App-requested fullscreen toggles (`agg_gui::fullscreen`).
226 if agg_gui::fullscreen::take_request() {
227 let now_fullscreen = self.window.fullscreen().is_none();
228 self.window
229 .set_fullscreen(now_fullscreen.then_some(Fullscreen::Borderless(None)));
230 agg_gui::fullscreen::set_active(now_fullscreen);
231 self.notify_geometry();
232 self.window.request_redraw();
233 }
234
235 let capture_pending = self.screenshot.is_some() && !self.screenshot_done;
236 let continuous = self.policy == RedrawPolicy::Continuous;
237 let mut painted = false;
238 if capture_pending {
239 // A pending deterministic capture needs the frame count to advance
240 // on its own; `ControlFlow::Wait` would stall forever with no user
241 // input.
242 painted = self.paint(elwt);
243 if !self.screenshot_done && capture_exhausted(self.screenshot_last_paint.elapsed()) {
244 self.fail(
245 ShellError::Screenshot(format!(
246 "gave up after {:.0}s without a presentable surface",
247 self.screenshot_last_paint.elapsed().as_secs_f64()
248 )),
249 elwt,
250 );
251 }
252 } else if continuous || self.app.wants_draw() {
253 painted = self.paint(elwt);
254 }
255
256 {
257 let mut exit = self.exit.get();
258 let mut control = ShellControl {
259 policy: &mut self.policy,
260 exit: &mut exit,
261 painted,
262 pointer_idle: self.mouse_buttons_down == 0,
263 };
264 self.host.on_idle(&mut self.app, &mut control);
265 self.exit.set(exit);
266 }
267
268 self.save_bounds_if_changed();
269
270 // `wants_draw()` covers due scheduled deadlines, so `Poll` when it (or
271 // continuous mode, or a pending capture) is true. Otherwise re-arm
272 // `WaitUntil` from the non-destructive peek — this runs every idle
273 // iteration and is idempotent, so an intervening non-repainting event
274 // cannot lose the scheduled wake.
275 //
276 // No `request_redraw` here: `Poll` brings us straight back to
277 // `AboutToWait`, which paints. Asking for a redraw as well would paint
278 // the same state twice per iteration while anything is animating.
279 let poll = capture_pending || self.policy == RedrawPolicy::Continuous;
280 if poll || self.app.wants_draw() {
281 elwt.set_control_flow(ControlFlow::Poll);
282 } else if let Some(t) = self.app.next_draw_deadline() {
283 elwt.set_control_flow(ControlFlow::WaitUntil(t));
284 } else {
285 elwt.set_control_flow(ControlFlow::Wait);
286 }
287
288 if self.exit.get().is_some() {
289 elwt.exit();
290 }
291 }
292
293 /// Paint one frame, recovering the device first if it was lost. Returns
294 /// whether a frame actually reached the compositor.
295 pub(crate) fn paint(&mut self, elwt: &ActiveEventLoop) -> bool {
296 if let Err(e) = self.recover_lost_device() {
297 self.fail(e, elwt);
298 return false;
299 }
300 let Some(gpu) = self.gpu.as_mut() else {
301 return false;
302 };
303 let capture = self
304 .screenshot
305 .as_ref()
306 .filter(|_| !self.screenshot_done)
307 .cloned();
308 let outcome = self.painter.paint(
309 gpu,
310 &self.window,
311 &mut self.app,
312 &mut self.host,
313 PaintRequest {
314 pending_resize: &mut self.pending_resize,
315 input_since_last_frame: self.input_since_frame,
316 capture: capture.as_ref(),
317 },
318 );
319 match outcome {
320 Ok(outcome) => {
321 if outcome.painted {
322 self.input_since_frame = false;
323 self.screenshot_last_paint = Instant::now();
324 }
325 if outcome.captured {
326 self.screenshot_done = true;
327 elwt.exit();
328 }
329 outcome.painted
330 }
331 Err(e) => {
332 self.fail(e, elwt);
333 false
334 }
335 }
336 }
337
338 /// Rebuild the device and surface after a device loss (TDR, driver reset,
339 /// GPU removal, RDP session change).
340 ///
341 /// wgpu reports the loss out-of-band — nothing in the per-frame API
342 /// returns an error — so without this the window paints nothing forever.
343 /// A lost device cannot be revived and every resource made from it is dead
344 /// with it, so the whole bundle is rebuilt and the host is told to drop
345 /// its own cached GPU resources.
346 ///
347 /// The C# port does the same thing in
348 /// `PlatformWin32/win32/WebGpuControl.cs::TryRecoverDevice` (agg-sharp), down
349 /// to the closing repaint request; it additionally guards against re-entering
350 /// recovery from a failure raised by recovery itself, which the `&mut self`
351 /// borrow here rules out for free.
352 fn recover_lost_device(&mut self) -> Result<(), ShellError> {
353 if !self.gpu.as_ref().is_some_and(|g| g.device_lost()) {
354 return Ok(());
355 }
356 log::warn!("agg-gui-shell: wgpu device lost — rebuilding device and surface");
357 // Drop the dead device and its surface BEFORE creating the
358 // replacement: two live surfaces for one window is not portable.
359 drop(self.gpu.take());
360 let size = self.window.inner_size();
361 let gpu = Gpu::new(
362 Arc::clone(&self.window),
363 (size.width.max(1), size.height.max(1)),
364 self.gpu_config,
365 )
366 .map_err(ShellError::Gpu)?;
367 self.painter.rebuild(&gpu);
368 self.host.on_gpu_rebuilt(&mut self.app, &gpu);
369 self.gpu = Some(gpu);
370 // The recovered surface starts blank; the app's next frame is a full
371 // repaint, not an incremental one.
372 agg_gui::animation::request_draw();
373 Ok(())
374 }
375
376 /// Record the first error and end the loop. Later errors are dropped: the
377 /// first one is the cause, and the shell is already shutting down.
378 fn fail(&mut self, error: ShellError, elwt: &ActiveEventLoop) {
379 if let Ok(mut slot) = self.error.try_borrow_mut() {
380 if slot.is_none() {
381 *slot = Some(error);
382 }
383 }
384 elwt.exit();
385 }
386
387 fn geometry(&self) -> WindowGeometry {
388 let size = self.window.inner_size();
389 WindowGeometry {
390 width: size.width,
391 height: size.height,
392 maximized: self.maximized,
393 fullscreen: self.window.fullscreen().is_some(),
394 scale_factor: self.window.scale_factor(),
395 }
396 }
397
398 fn notify_geometry(&mut self) {
399 let geometry = self.geometry();
400 self.host.on_geometry_changed(geometry);
401 }
402
403 fn current_bounds(&self) -> SavedBounds {
404 let (width, height) = self.windowed_size.size();
405 SavedBounds {
406 width,
407 height,
408 maximized: self.maximized,
409 }
410 }
411
412 /// Persist the window bounds when they changed and no mouse button is
413 /// held, so a drag-resize doesn't hit the store on every intermediate
414 /// size.
415 fn save_bounds_if_changed(&mut self) {
416 let Some(store) = self.bounds_store.as_ref() else {
417 return;
418 };
419 let bounds = self.current_bounds();
420 if self
421 .bounds_auto
422 .should_save(self.mouse_buttons_down == 0, bounds)
423 {
424 store.save(bounds);
425 }
426 }
427
428 /// Final flush, once, however the loop ended.
429 fn finish(&mut self) {
430 if self.finished {
431 return;
432 }
433 self.finished = true;
434 if let Some(store) = self.bounds_store.as_ref() {
435 // Unconditional, and BEFORE `on_exit`: the last change may have
436 // happened with a button still held (closing from a drag), which
437 // the idle gate skipped — and an app whose store only records the
438 // bounds writes them out from its own `on_exit` flush.
439 store.save(self.current_bounds());
440 }
441 self.host.on_exit(&mut self.app);
442 }
443}
444
445/// Everything the shell knows once the window and GPU exist but before the app
446/// is built — what a builder closure needs to size its first layout or share
447/// the device with an app-owned renderer.
448pub struct ShellInit<'a> {
449 pub(crate) window: &'a Arc<Window>,
450 pub(crate) gpu: &'a Gpu,
451 pub(crate) restored_bounds: Option<SavedBounds>,
452}
453
454impl ShellInit<'_> {
455 /// The OS window. Handy for a title the app computes, or for platform
456 /// integration the shell doesn't wrap.
457 pub fn window(&self) -> &Arc<Window> {
458 self.window
459 }
460
461 /// The live device + surface bundle. An app with its own wgpu renderer
462 /// builds it from this device.
463 pub fn gpu(&self) -> &Gpu {
464 self.gpu
465 }
466
467 /// Surface size in physical pixels — already clamped to the GPU limit.
468 pub fn size(&self) -> (u32, u32) {
469 (self.gpu.config().width, self.gpu.config().height)
470 }
471
472 /// What the [`WindowBoundsStore`] returned, if anything. An app that
473 /// keeps other window state alongside the bounds can use this to tell a
474 /// restored launch from a first one.
475 pub fn restored_bounds(&self) -> Option<SavedBounds> {
476 self.restored_bounds
477 }
478
479 /// `agg_gui::device_scale()`, already applied from the window.
480 pub fn device_scale(&self) -> f64 {
481 agg_gui::device_scale()
482 }
483}