Skip to main content

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