Skip to main content

agg_gui_shell/
host.rs

1//! The app-side seam: [`ShellHost`], the per-frame/per-idle information the
2//! shell hands it, and the [`ShellControl`] handle it steers the loop with.
3//!
4//! [`crate::run`] owns the window, the GPU and the event loop; everything an
5//! app wants to do *around* those (custom frame rendering, state persistence,
6//! diagnostics, exit/relaunch) goes through this trait. Every method has a
7//! default, so a host with nothing to add is an empty impl.
8
9use std::time::Duration;
10
11use agg_gui::{App, Size};
12use agg_gui_wgpu::{Gpu, WgpuGfxCtx};
13
14/// What the shell knows about the frame it is about to paint.
15#[derive(Clone, Copy, Debug)]
16#[non_exhaustive]
17pub struct Frame {
18    /// Surface size in physical pixels — already clamped to the GPU limit, so
19    /// this is what layout and the renderer must use, not `Window::inner_size`.
20    pub width: u32,
21    pub height: u32,
22    /// `agg_gui::device_scale()` for this frame.
23    pub device_scale: f64,
24    /// Wall time the *previous* painted frame took (paint plus present).
25    /// Zero for the first frame. This is the number a frame-time graph plots.
26    pub duration: Duration,
27    /// Count of frames painted so far, this one included (1-based).
28    pub index: u64,
29    /// Whether anything that feeds layout changed since the last painted
30    /// frame — surface size, device scale, or the invalidation epoch. A host
31    /// that overrides [`ShellHost::paint`] should honour it rather than laying
32    /// out unconditionally.
33    pub needs_layout: bool,
34    /// Whether any input event arrived since the last painted frame. A
35    /// runaway-repaint detector uses this to tell "the user is doing
36    /// something" from "the app will not quiesce".
37    pub input_since_last_frame: bool,
38}
39
40impl Frame {
41    /// Surface size as the `Size` `App::layout` wants.
42    pub fn viewport(&self) -> Size {
43        Size::new(self.width as f64, self.height as f64)
44    }
45}
46
47/// Window geometry as the OS last reported it. Sizes are physical pixels.
48#[derive(Clone, Copy, Debug, PartialEq)]
49#[non_exhaustive]
50pub struct WindowGeometry {
51    pub width: u32,
52    pub height: u32,
53    pub maximized: bool,
54    pub fullscreen: bool,
55    pub scale_factor: f64,
56}
57
58/// How the event loop should end.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub(crate) enum ExitAction {
61    /// Close normally.
62    Exit,
63    /// Close, then start a fresh copy of this executable. The shell spawns it
64    /// only after the loop has exited and every store has been flushed, so the
65    /// child reads the state this run just wrote.
66    Relaunch,
67}
68
69/// Steering handle passed to [`ShellHost::on_idle`].
70pub struct ShellControl<'a> {
71    pub(crate) policy: &'a mut crate::RedrawPolicy,
72    pub(crate) exit: &'a mut Option<ExitAction>,
73    pub(crate) painted: bool,
74    pub(crate) pointer_idle: bool,
75}
76
77impl ShellControl<'_> {
78    /// Current redraw policy.
79    pub fn redraw_policy(&self) -> crate::RedrawPolicy {
80        *self.policy
81    }
82
83    /// Switch between reactive and continuous redraw at runtime.
84    pub fn set_redraw_policy(&mut self, policy: crate::RedrawPolicy) {
85        *self.policy = policy;
86    }
87
88    /// Whether a frame was painted in this loop iteration. `false` means the
89    /// loop is idling — nothing asked for a frame.
90    pub fn painted(&self) -> bool {
91        self.painted
92    }
93
94    /// Whether no mouse button is currently held. The gate an app's own
95    /// auto-save should use so a drag/resize doesn't thrash the disk; the
96    /// shell applies the same gate to its [`crate::WindowBoundsStore`].
97    pub fn pointer_idle(&self) -> bool {
98        self.pointer_idle
99    }
100
101    /// Close the window and leave the event loop after this iteration.
102    pub fn request_exit(&mut self) {
103        // A pending relaunch is the stronger request — do not downgrade it.
104        if self.exit.is_none() {
105            *self.exit = Some(ExitAction::Exit);
106        }
107    }
108
109    /// Leave the event loop and start a fresh copy of this executable.
110    ///
111    /// Used for settings that can only be applied at startup (MSAA sample
112    /// count, backend selection). The spawn happens after the loop exits and
113    /// after [`ShellHost::on_exit`] and the bounds store have run, so the
114    /// child sees the state this run just saved.
115    pub fn request_relaunch(&mut self) {
116        *self.exit = Some(ExitAction::Relaunch);
117    }
118}
119
120/// The app side of the shell.
121///
122/// The host owns whatever the app needs that is *not* the widget tree —
123/// persistence handles, diagnostic state, GPU-readback plumbing — and the
124/// shell calls into it around each frame and each idle iteration.
125pub trait ShellHost {
126    /// Runs at the start of every painted frame, before layout and paint.
127    /// The hook for per-frame app state: advancing a wall-clock cell, pushing
128    /// `frame.duration` into a history buffer, feeding a runaway detector.
129    fn on_frame(&mut self, _app: &mut App, _frame: &Frame) {}
130
131    /// Render the frame's contents.
132    ///
133    /// The default resets the context, lays out when `frame.needs_layout`, and
134    /// paints — which is all most apps want. Override to wrap layout/paint in
135    /// app-specific plumbing (a live inspector's edit queues, for example);
136    /// the shell has already begun the frame and will call `end_frame` and
137    /// `present` afterwards.
138    fn paint(&mut self, app: &mut App, ctx: &mut WgpuGfxCtx, frame: &Frame) {
139        default_paint(app, ctx, frame);
140    }
141
142    /// Runs after `WgpuGfxCtx::end_frame` and before `present`.
143    ///
144    /// The only place a GPU copy off the surface texture can happen: wgpu's
145    /// swap chain takes ownership of that texture at `present`. `frame` is the
146    /// same descriptor [`ShellHost::paint`] just saw — a read-back needs the
147    /// surface size, and a capture that only fires on some frames needs the
148    /// frame index.
149    fn after_paint(&mut self, _ctx: &mut WgpuGfxCtx, _frame: &Frame) {}
150
151    /// The OS window was resized, maximized, restored, or changed scale.
152    fn on_geometry_changed(&mut self, _geometry: WindowGeometry) {}
153
154    /// The user asked the OS window to close (title-bar ×, Alt+F4, taskbar
155    /// close). Return `true` to let the shell exit the loop; return `false`
156    /// to keep running.
157    ///
158    /// This is where an unsaved-changes gate lives: prompt here (a blocking
159    /// native dialog is fine — no frame is in flight), and either allow the
160    /// close, or return `false` and finish an asynchronous save from
161    /// [`ShellHost::on_idle`], calling [`ShellControl::request_exit`] once it
162    /// lands. Not called for [`ShellControl::request_exit`] /
163    /// `request_relaunch` (the app already decided) or when a configured
164    /// screenshot capture completes.
165    fn on_close_requested(&mut self, _app: &mut App) -> bool {
166        true
167    }
168
169    /// Runs once per idle iteration of the event loop, after any frame this
170    /// iteration painted. The hook for app-owned auto-save, deferred work that
171    /// must not run inside event dispatch, and exit/relaunch requests.
172    fn on_idle(&mut self, _app: &mut App, _control: &mut ShellControl<'_>) {}
173
174    /// The wgpu device was lost (TDR, driver reset, GPU removal, RDP session
175    /// change) and the shell has rebuilt it. **Every GPU resource created from
176    /// the old device is dead** — textures, buffers, pipelines cached by
177    /// custom-render widgets — so drop them here and let them be recreated
178    /// from `gpu` on the next frame.
179    fn on_gpu_rebuilt(&mut self, _app: &mut App, _gpu: &Gpu) {}
180
181    /// The loop is about to exit (window closed, exit requested, or a
182    /// screenshot run finished). Last chance to flush state.
183    fn on_exit(&mut self, _app: &mut App) {}
184}
185
186/// A host with nothing to add — `run(config, |_| Ok((app, NoHost)))`.
187pub struct NoHost;
188
189impl ShellHost for NoHost {}
190
191/// The default frame body: reset, lay out if anything that feeds layout
192/// changed, paint. Exposed so a host that overrides [`ShellHost::paint`] to
193/// add work *around* the frame can still delegate the frame itself.
194pub fn default_paint(app: &mut App, ctx: &mut WgpuGfxCtx, frame: &Frame) {
195    ctx.reset(frame.width as f32, frame.height as f32);
196    ctx.set_lcd_mode(agg_gui::font_settings::lcd_enabled());
197    if frame.needs_layout {
198        app.layout(frame.viewport());
199    }
200    app.paint(ctx);
201}