Skip to main content

agg_gui_shell/
config.rs

1//! Window / surface configuration for [`crate::run`].
2//!
3//! Everything the shell needs to open the OS window and configure the swap
4//! chain before the app exists. Split out of `run.rs` so the event loop file
5//! stays about the loop; the persistence trait it references lives in
6//! [`crate::bounds`].
7
8use std::path::PathBuf;
9
10use agg_gui_wgpu::CopySrc;
11
12use crate::bounds::WindowBoundsStore;
13
14/// A size in either DPI-independent (logical) or device (physical) pixels.
15///
16/// Restored window sizes are saved in **physical** pixels and must be restored
17/// in the same unit: handing a saved physical size back as a logical one
18/// re-multiplies it by the monitor scale on every launch, which is the
19/// DPI-ratchet bug that eventually grows the surface past the GPU's maximum
20/// texture dimension. See [`crate::bounds::sanitize_restored_window_size`].
21#[derive(Clone, Copy, Debug, PartialEq)]
22pub enum WindowSize {
23    /// DPI-independent pixels — what a first-launch default should use.
24    Logical(f64, f64),
25    /// Device pixels — what a restored size uses.
26    Physical(u32, u32),
27}
28
29impl WindowSize {
30    pub(crate) fn to_winit(self) -> winit::dpi::Size {
31        match self {
32            Self::Logical(w, h) => winit::dpi::LogicalSize::new(w, h).into(),
33            Self::Physical(w, h) => winit::dpi::PhysicalSize::new(w, h).into(),
34        }
35    }
36}
37
38/// How hard the shell drives the event loop when the app is not asking for
39/// frames.
40#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
41pub enum RedrawPolicy {
42    /// Paint only when something asks for it: an input event, an
43    /// `agg_gui::animation` request, or a due scheduled deadline. The event
44    /// loop parks in `ControlFlow::Wait`/`WaitUntil` otherwise, so an idle app
45    /// costs no CPU.
46    #[default]
47    Reactive,
48    /// Paint every iteration regardless. What a frame-time graph or a
49    /// game-style app wants; costs a core.
50    Continuous,
51}
52
53/// An RGBA8 window icon, as the OS taskbar / title bar wants it.
54///
55/// Built through [`ShellConfig::with_icon_rgba`]; `#[non_exhaustive]` so it can
56/// grow (a separate small icon, a mask) without a breaking release.
57#[derive(Clone, Debug)]
58#[non_exhaustive]
59pub struct WindowIcon {
60    pub rgba: Vec<u8>,
61    pub width: u32,
62    pub height: u32,
63}
64
65/// Deterministic frame capture: after `settle_frames` painted frames, read the
66/// frame back, write it to `path` as a PNG, and leave the event loop.
67///
68/// Built through [`ShellConfig::with_screenshot`]; `#[non_exhaustive]` so it
69/// can grow (a capture region, a scale) without a breaking release.
70#[derive(Clone, Debug)]
71#[non_exhaustive]
72pub struct ScreenshotConfig {
73    pub path: PathBuf,
74    /// Frames to paint before capturing, clamped to at least 1. ~6 gives
75    /// fonts, layout and start-up animations time to settle.
76    pub settle_frames: u32,
77}
78
79/// Everything [`crate::run`] needs before the app exists.
80///
81/// Build one with [`ShellConfig::new`] and the `with_*` setters rather than a
82/// struct literal — the struct is `#[non_exhaustive]` so new knobs can be
83/// added without a breaking release.
84///
85/// ```no_run
86/// use agg_gui_shell::{RedrawPolicy, ShellConfig};
87/// let cfg = ShellConfig::new("My App")
88///     .with_logical_size(1280.0, 720.0)
89///     .with_min_logical_size(800.0, 600.0)
90///     .with_redraw_policy(RedrawPolicy::Reactive);
91/// ```
92#[non_exhaustive]
93pub struct ShellConfig {
94    /// OS window title. An owned `String` because a title is routinely built
95    /// at runtime (document name, version, profile).
96    pub title: String,
97    /// Initial inner size, used when no [`WindowBoundsStore`] returns a saved
98    /// size. Defaults to 1280x720 logical.
99    pub size: WindowSize,
100    /// Minimum inner size enforced by the window system. `None` =
101    /// unconstrained.
102    pub min_size: Option<WindowSize>,
103    /// Taskbar / title-bar icon.
104    pub icon: Option<WindowIcon>,
105    /// Start maximized. A [`WindowBoundsStore`] that returns a maximized
106    /// state overrides this.
107    pub maximized: bool,
108    /// Start in borderless fullscreen. The app can toggle later through
109    /// `agg_gui::fullscreen::request_toggle`.
110    pub fullscreen: bool,
111    /// Reactive (default) or continuous redraw. The host can change this at
112    /// runtime through [`crate::ShellControl::set_redraw_policy`].
113    pub redraw_policy: RedrawPolicy,
114    /// Surface read-back requirement, passed through to `agg_gui_wgpu::Gpu`.
115    /// Forced to [`CopySrc::Required`] when a screenshot is configured.
116    pub copy_src: CopySrc,
117    /// Swap-chain present mode, passed through to `agg_gui_wgpu::Gpu` (which
118    /// falls back to `Fifo` if the surface does not support it).
119    pub present_mode: wgpu::PresentMode,
120    /// `wgpu::DeviceDescriptor` label — shows up in backend validation
121    /// messages and GPU captures.
122    pub device_label: &'static str,
123    /// Device features requested when the adapter offers them, passed through
124    /// to `agg_gui_wgpu::GpuConfig` (which masks them against
125    /// `adapter.features()` so an adapter lacking one still yields a device).
126    pub optional_features: wgpu::Features,
127    /// Deterministic capture, see [`ScreenshotConfig`].
128    pub screenshot: Option<ScreenshotConfig>,
129    /// Seed `agg_gui`'s tooltip timings from the OS (Windows:
130    /// `SPI_GETMOUSEHOVERTIME`). On by default; other platforms keep the
131    /// library defaults regardless.
132    pub os_tooltip_timings: bool,
133    /// Where the window size / maximized state is restored from and saved to.
134    /// `None` = no persistence.
135    pub bounds_store: Option<Box<dyn WindowBoundsStore>>,
136}
137
138impl Default for ShellConfig {
139    fn default() -> Self {
140        Self {
141            title: String::new(),
142            size: WindowSize::Logical(1280.0, 720.0),
143            min_size: None,
144            icon: None,
145            maximized: false,
146            fullscreen: false,
147            redraw_policy: RedrawPolicy::Reactive,
148            copy_src: CopySrc::Never,
149            present_mode: wgpu::PresentMode::AutoVsync,
150            device_label: "agg-gui-shell",
151            optional_features: wgpu::Features::empty(),
152            screenshot: None,
153            os_tooltip_timings: true,
154            bounds_store: None,
155        }
156    }
157}
158
159impl ShellConfig {
160    /// Default configuration under a window title.
161    pub fn new(title: impl Into<String>) -> Self {
162        Self {
163            title: title.into(),
164            ..Self::default()
165        }
166    }
167
168    /// Initial inner size in DPI-independent pixels.
169    pub fn with_logical_size(mut self, w: f64, h: f64) -> Self {
170        self.size = WindowSize::Logical(w, h);
171        self
172    }
173
174    /// Initial inner size in device pixels — the unit a restored size uses.
175    pub fn with_physical_size(mut self, w: u32, h: u32) -> Self {
176        self.size = WindowSize::Physical(w, h);
177        self
178    }
179
180    /// Refuse to let the user shrink the window below `(w, h)` logical pixels.
181    pub fn with_min_logical_size(mut self, w: f64, h: f64) -> Self {
182        self.min_size = Some(WindowSize::Logical(w, h));
183        self
184    }
185
186    /// Refuse to let the user shrink the window below `(w, h)` device pixels.
187    pub fn with_min_physical_size(mut self, w: u32, h: u32) -> Self {
188        self.min_size = Some(WindowSize::Physical(w, h));
189        self
190    }
191
192    /// Window icon from raw RGBA8 bytes (`width * height * 4`). An icon that
193    /// winit rejects is logged and dropped — an app should still open.
194    pub fn with_icon_rgba(mut self, rgba: impl Into<Vec<u8>>, width: u32, height: u32) -> Self {
195        self.icon = Some(WindowIcon {
196            rgba: rgba.into(),
197            width,
198            height,
199        });
200        self
201    }
202
203    pub fn with_maximized(mut self, maximized: bool) -> Self {
204        self.maximized = maximized;
205        self
206    }
207
208    pub fn with_fullscreen(mut self, fullscreen: bool) -> Self {
209        self.fullscreen = fullscreen;
210        self
211    }
212
213    pub fn with_redraw_policy(mut self, policy: RedrawPolicy) -> Self {
214        self.redraw_policy = policy;
215        self
216    }
217
218    pub fn with_copy_src(mut self, copy_src: CopySrc) -> Self {
219        self.copy_src = copy_src;
220        self
221    }
222
223    pub fn with_present_mode(mut self, present_mode: wgpu::PresentMode) -> Self {
224        self.present_mode = present_mode;
225        self
226    }
227
228    pub fn with_device_label(mut self, label: &'static str) -> Self {
229        self.device_label = label;
230        self
231    }
232
233    /// Request these device features when — and only when — the adapter
234    /// offers them. See [`ShellConfig::optional_features`].
235    pub fn with_optional_features(mut self, features: wgpu::Features) -> Self {
236        self.optional_features = features;
237        self
238    }
239
240    /// Headless-style capture: after `settle_frames` painted frames, read the
241    /// frame back, write it as a PNG to `path`, and leave the event loop.
242    /// The shell polls and paints every idle iteration until the capture
243    /// fires, so the frame count advances without any user input.
244    ///
245    /// The image is in PHYSICAL pixels — on a 2x display that is twice the
246    /// logical window size. A failed capture ends [`crate::run`] with
247    /// [`crate::ShellError::Screenshot`]; the shell never exits the process
248    /// itself.
249    pub fn with_screenshot(mut self, path: impl Into<PathBuf>, settle_frames: u32) -> Self {
250        self.screenshot = Some(ScreenshotConfig {
251            path: path.into(),
252            settle_frames,
253        });
254        self
255    }
256
257    pub fn with_os_tooltip_timings(mut self, enabled: bool) -> Self {
258        self.os_tooltip_timings = enabled;
259        self
260    }
261
262    /// Restore the window size / maximized state from `store` at startup and
263    /// save it back as it changes. See [`WindowBoundsStore`].
264    pub fn with_bounds_store(mut self, store: impl WindowBoundsStore + 'static) -> Self {
265        self.bounds_store = Some(Box::new(store));
266        self
267    }
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    #[test]
275    fn builder_defaults_and_overrides() {
276        let cfg = ShellConfig::new("Title");
277        assert_eq!(cfg.title, "Title");
278        assert_eq!(cfg.size, WindowSize::Logical(1280.0, 720.0));
279        assert_eq!(cfg.redraw_policy, RedrawPolicy::Reactive);
280        assert!(cfg.os_tooltip_timings);
281
282        let cfg = cfg
283            .with_physical_size(1600, 900)
284            .with_min_logical_size(640.0, 480.0)
285            .with_redraw_policy(RedrawPolicy::Continuous)
286            .with_screenshot("out.png", 6);
287        assert_eq!(cfg.size, WindowSize::Physical(1600, 900));
288        assert_eq!(cfg.min_size, Some(WindowSize::Logical(640.0, 480.0)));
289        assert_eq!(cfg.redraw_policy, RedrawPolicy::Continuous);
290        assert_eq!(cfg.screenshot.map(|s| s.settle_frames), Some(6));
291    }
292
293    #[test]
294    fn min_size_can_be_given_in_either_unit() {
295        let cfg = ShellConfig::new("Title").with_min_physical_size(320, 240);
296        assert_eq!(cfg.min_size, Some(WindowSize::Physical(320, 240)));
297    }
298}