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};
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                elwt.exit();
106            }
107
108            WindowEvent::Resized(size) if size.width > 0 && size.height > 0 => {
109                // Coalesced, applied at the top of the next paint: winit can
110                // deliver `Resized` from a modal drag-resize loop, and
111                // reconfiguring the surface between acquire and present is a
112                // validation error.
113                self.pending_resize = Some((size.width, size.height));
114                self.maximized = self.window.is_maximized();
115                // winit's `Resized` reports PHYSICAL px. That is the canonical
116                // stored unit — it must round-trip through `PhysicalSize` on
117                // restore, never `LogicalSize`, or the size ratchets up by the
118                // DPI scale factor every launch.
119                self.windowed_size.note_resize(
120                    (size.width, size.height),
121                    self.maximized,
122                    self.window.fullscreen().is_some(),
123                );
124                self.notify_geometry();
125                self.window.request_redraw();
126            }
127
128            WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
129                agg_gui::set_device_scale(scale_factor);
130                self.notify_geometry();
131                self.window.request_redraw();
132            }
133
134            WindowEvent::CursorMoved { position, .. } => {
135                self.cursor = (position.x, position.y);
136                self.input_since_frame = true;
137                self.app.on_mouse_move(self.cursor.0, self.cursor.1);
138                winit_adapter::apply_cursor(&self.window, agg_gui::current_cursor_icon());
139            }
140
141            WindowEvent::CursorLeft { .. } => {
142                self.app.on_mouse_leave();
143            }
144
145            WindowEvent::ModifiersChanged(state) => {
146                self.mods = winit_adapter::modifiers(state.state());
147            }
148
149            WindowEvent::MouseInput { state, button, .. } => {
150                let btn = winit_adapter::mouse_button(button);
151                self.input_since_frame = true;
152                let (x, y) = self.cursor;
153                match state {
154                    ElementState::Pressed => {
155                        self.mouse_buttons_down = self.mouse_buttons_down.saturating_add(1);
156                        self.app.on_mouse_down(x, y, btn, self.mods);
157                    }
158                    ElementState::Released => {
159                        self.mouse_buttons_down = self.mouse_buttons_down.saturating_sub(1);
160                        self.app.on_mouse_up(x, y, btn, self.mods);
161                    }
162                }
163            }
164
165            WindowEvent::MouseWheel { delta, .. } => {
166                self.input_since_frame = true;
167                let (dx, dy) = wheel_delta(delta, shift_held(self.mods));
168                let (x, y) = self.cursor;
169                self.app.on_mouse_wheel_xy_mods(x, y, dx, dy, self.mods);
170            }
171
172            WindowEvent::KeyboardInput {
173                event: key_event, ..
174            } => {
175                self.input_since_frame = true;
176                let Some(key) = winit_adapter::key_event(&key_event, self.mods) else {
177                    return;
178                };
179                match key_event.state {
180                    ElementState::Pressed => self.app.on_key_down(key, self.mods),
181                    // Key-up matters: chord state, drag modifiers and
182                    // held-key repeat all end here. A shell that only
183                    // dispatches key-down leaves the app with a stuck key.
184                    ElementState::Released => self.app.on_key_up(key, self.mods),
185                }
186            }
187
188            WindowEvent::Touch(touch) => {
189                self.input_since_frame = true;
190                dispatch_touch(&mut self.app, touch);
191                // Touch events arrive outside the mouse arms' redraw
192                // signalling — request a frame so gestures render live.
193                self.window.request_redraw();
194            }
195
196            WindowEvent::RedrawRequested => {
197                self.paint(elwt);
198            }
199
200            _ => {}
201        }
202    }
203
204    fn about_to_wait(&mut self, elwt: &ActiveEventLoop) {
205        // App-requested fullscreen toggles (`agg_gui::fullscreen`).
206        if agg_gui::fullscreen::take_request() {
207            let now_fullscreen = self.window.fullscreen().is_none();
208            self.window
209                .set_fullscreen(now_fullscreen.then_some(Fullscreen::Borderless(None)));
210            agg_gui::fullscreen::set_active(now_fullscreen);
211            self.notify_geometry();
212            self.window.request_redraw();
213        }
214
215        let capture_pending = self.screenshot.is_some() && !self.screenshot_done;
216        let continuous = self.policy == RedrawPolicy::Continuous;
217        let mut painted = false;
218        if capture_pending {
219            // A pending deterministic capture needs the frame count to advance
220            // on its own; `ControlFlow::Wait` would stall forever with no user
221            // input.
222            painted = self.paint(elwt);
223            if !self.screenshot_done && capture_exhausted(self.screenshot_last_paint.elapsed()) {
224                self.fail(
225                    ShellError::Screenshot(format!(
226                        "gave up after {:.0}s without a presentable surface",
227                        self.screenshot_last_paint.elapsed().as_secs_f64()
228                    )),
229                    elwt,
230                );
231            }
232        } else if continuous || self.app.wants_draw() {
233            painted = self.paint(elwt);
234        }
235
236        {
237            let mut exit = self.exit.get();
238            let mut control = ShellControl {
239                policy: &mut self.policy,
240                exit: &mut exit,
241                painted,
242                pointer_idle: self.mouse_buttons_down == 0,
243            };
244            self.host.on_idle(&mut self.app, &mut control);
245            self.exit.set(exit);
246        }
247
248        self.save_bounds_if_changed();
249
250        // `wants_draw()` covers due scheduled deadlines, so `Poll` when it (or
251        // continuous mode, or a pending capture) is true. Otherwise re-arm
252        // `WaitUntil` from the non-destructive peek — this runs every idle
253        // iteration and is idempotent, so an intervening non-repainting event
254        // cannot lose the scheduled wake.
255        //
256        // No `request_redraw` here: `Poll` brings us straight back to
257        // `AboutToWait`, which paints. Asking for a redraw as well would paint
258        // the same state twice per iteration while anything is animating.
259        let poll = capture_pending || self.policy == RedrawPolicy::Continuous;
260        if poll || self.app.wants_draw() {
261            elwt.set_control_flow(ControlFlow::Poll);
262        } else if let Some(t) = self.app.next_draw_deadline() {
263            elwt.set_control_flow(ControlFlow::WaitUntil(t));
264        } else {
265            elwt.set_control_flow(ControlFlow::Wait);
266        }
267
268        if self.exit.get().is_some() {
269            elwt.exit();
270        }
271    }
272
273    /// Paint one frame, recovering the device first if it was lost. Returns
274    /// whether a frame actually reached the compositor.
275    pub(crate) fn paint(&mut self, elwt: &ActiveEventLoop) -> bool {
276        if let Err(e) = self.recover_lost_device() {
277            self.fail(e, elwt);
278            return false;
279        }
280        let Some(gpu) = self.gpu.as_mut() else {
281            return false;
282        };
283        let capture = self
284            .screenshot
285            .as_ref()
286            .filter(|_| !self.screenshot_done)
287            .cloned();
288        let outcome = self.painter.paint(
289            gpu,
290            &self.window,
291            &mut self.app,
292            &mut self.host,
293            PaintRequest {
294                pending_resize: &mut self.pending_resize,
295                input_since_last_frame: self.input_since_frame,
296                capture: capture.as_ref(),
297            },
298        );
299        match outcome {
300            Ok(outcome) => {
301                if outcome.painted {
302                    self.input_since_frame = false;
303                    self.screenshot_last_paint = Instant::now();
304                }
305                if outcome.captured {
306                    self.screenshot_done = true;
307                    elwt.exit();
308                }
309                outcome.painted
310            }
311            Err(e) => {
312                self.fail(e, elwt);
313                false
314            }
315        }
316    }
317
318    /// Rebuild the device and surface after a device loss (TDR, driver reset,
319    /// GPU removal, RDP session change).
320    ///
321    /// wgpu reports the loss out-of-band — nothing in the per-frame API
322    /// returns an error — so without this the window paints nothing forever.
323    /// A lost device cannot be revived and every resource made from it is dead
324    /// with it, so the whole bundle is rebuilt and the host is told to drop
325    /// its own cached GPU resources.
326    fn recover_lost_device(&mut self) -> Result<(), ShellError> {
327        if !self.gpu.as_ref().is_some_and(|g| g.device_lost()) {
328            return Ok(());
329        }
330        log::warn!("agg-gui-shell: wgpu device lost — rebuilding device and surface");
331        // Drop the dead device and its surface BEFORE creating the
332        // replacement: two live surfaces for one window is not portable.
333        drop(self.gpu.take());
334        let size = self.window.inner_size();
335        let gpu = Gpu::new(
336            Arc::clone(&self.window),
337            (size.width.max(1), size.height.max(1)),
338            self.gpu_config,
339        )
340        .map_err(ShellError::Gpu)?;
341        self.painter.rebuild(&gpu);
342        self.host.on_gpu_rebuilt(&mut self.app, &gpu);
343        self.gpu = Some(gpu);
344        // The recovered surface starts blank; the app's next frame is a full
345        // repaint, not an incremental one.
346        agg_gui::animation::request_draw();
347        Ok(())
348    }
349
350    /// Record the first error and end the loop. Later errors are dropped: the
351    /// first one is the cause, and the shell is already shutting down.
352    fn fail(&mut self, error: ShellError, elwt: &ActiveEventLoop) {
353        if let Ok(mut slot) = self.error.try_borrow_mut() {
354            if slot.is_none() {
355                *slot = Some(error);
356            }
357        }
358        elwt.exit();
359    }
360
361    fn geometry(&self) -> WindowGeometry {
362        let size = self.window.inner_size();
363        WindowGeometry {
364            width: size.width,
365            height: size.height,
366            maximized: self.maximized,
367            fullscreen: self.window.fullscreen().is_some(),
368            scale_factor: self.window.scale_factor(),
369        }
370    }
371
372    fn notify_geometry(&mut self) {
373        let geometry = self.geometry();
374        self.host.on_geometry_changed(geometry);
375    }
376
377    fn current_bounds(&self) -> SavedBounds {
378        let (width, height) = self.windowed_size.size();
379        SavedBounds {
380            width,
381            height,
382            maximized: self.maximized,
383        }
384    }
385
386    /// Persist the window bounds when they changed and no mouse button is
387    /// held, so a drag-resize doesn't hit the store on every intermediate
388    /// size.
389    fn save_bounds_if_changed(&mut self) {
390        let Some(store) = self.bounds_store.as_ref() else {
391            return;
392        };
393        let bounds = self.current_bounds();
394        if self
395            .bounds_auto
396            .should_save(self.mouse_buttons_down == 0, bounds)
397        {
398            store.save(bounds);
399        }
400    }
401
402    /// Final flush, once, however the loop ended.
403    fn finish(&mut self) {
404        if self.finished {
405            return;
406        }
407        self.finished = true;
408        if let Some(store) = self.bounds_store.as_ref() {
409            // Unconditional, and BEFORE `on_exit`: the last change may have
410            // happened with a button still held (closing from a drag), which
411            // the idle gate skipped — and an app whose store only records the
412            // bounds writes them out from its own `on_exit` flush.
413            store.save(self.current_bounds());
414        }
415        self.host.on_exit(&mut self.app);
416    }
417}
418
419/// Everything the shell knows once the window and GPU exist but before the app
420/// is built — what a builder closure needs to size its first layout or share
421/// the device with an app-owned renderer.
422pub struct ShellInit<'a> {
423    pub(crate) window: &'a Arc<Window>,
424    pub(crate) gpu: &'a Gpu,
425    pub(crate) restored_bounds: Option<SavedBounds>,
426}
427
428impl ShellInit<'_> {
429    /// The OS window. Handy for a title the app computes, or for platform
430    /// integration the shell doesn't wrap.
431    pub fn window(&self) -> &Arc<Window> {
432        self.window
433    }
434
435    /// The live device + surface bundle. An app with its own wgpu renderer
436    /// builds it from this device.
437    pub fn gpu(&self) -> &Gpu {
438        self.gpu
439    }
440
441    /// Surface size in physical pixels — already clamped to the GPU limit.
442    pub fn size(&self) -> (u32, u32) {
443        (self.gpu.config().width, self.gpu.config().height)
444    }
445
446    /// What the [`WindowBoundsStore`] returned, if anything. An app that
447    /// keeps other window state alongside the bounds can use this to tell a
448    /// restored launch from a first one.
449    pub fn restored_bounds(&self) -> Option<SavedBounds> {
450        self.restored_bounds
451    }
452
453    /// `agg_gui::device_scale()`, already applied from the window.
454    pub fn device_scale(&self) -> f64 {
455        agg_gui::device_scale()
456    }
457}