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 /// Deterministic capture, see [`ScreenshotConfig`].
124 pub screenshot: Option<ScreenshotConfig>,
125 /// Seed `agg_gui`'s tooltip timings from the OS (Windows:
126 /// `SPI_GETMOUSEHOVERTIME`). On by default; other platforms keep the
127 /// library defaults regardless.
128 pub os_tooltip_timings: bool,
129 /// Where the window size / maximized state is restored from and saved to.
130 /// `None` = no persistence.
131 pub bounds_store: Option<Box<dyn WindowBoundsStore>>,
132}
133
134impl Default for ShellConfig {
135 fn default() -> Self {
136 Self {
137 title: String::new(),
138 size: WindowSize::Logical(1280.0, 720.0),
139 min_size: None,
140 icon: None,
141 maximized: false,
142 fullscreen: false,
143 redraw_policy: RedrawPolicy::Reactive,
144 copy_src: CopySrc::Never,
145 present_mode: wgpu::PresentMode::AutoVsync,
146 device_label: "agg-gui-shell",
147 screenshot: None,
148 os_tooltip_timings: true,
149 bounds_store: None,
150 }
151 }
152}
153
154impl ShellConfig {
155 /// Default configuration under a window title.
156 pub fn new(title: impl Into<String>) -> Self {
157 Self {
158 title: title.into(),
159 ..Self::default()
160 }
161 }
162
163 /// Initial inner size in DPI-independent pixels.
164 pub fn with_logical_size(mut self, w: f64, h: f64) -> Self {
165 self.size = WindowSize::Logical(w, h);
166 self
167 }
168
169 /// Initial inner size in device pixels — the unit a restored size uses.
170 pub fn with_physical_size(mut self, w: u32, h: u32) -> Self {
171 self.size = WindowSize::Physical(w, h);
172 self
173 }
174
175 /// Refuse to let the user shrink the window below `(w, h)` logical pixels.
176 pub fn with_min_logical_size(mut self, w: f64, h: f64) -> Self {
177 self.min_size = Some(WindowSize::Logical(w, h));
178 self
179 }
180
181 /// Refuse to let the user shrink the window below `(w, h)` device pixels.
182 pub fn with_min_physical_size(mut self, w: u32, h: u32) -> Self {
183 self.min_size = Some(WindowSize::Physical(w, h));
184 self
185 }
186
187 /// Window icon from raw RGBA8 bytes (`width * height * 4`). An icon that
188 /// winit rejects is logged and dropped — an app should still open.
189 pub fn with_icon_rgba(mut self, rgba: impl Into<Vec<u8>>, width: u32, height: u32) -> Self {
190 self.icon = Some(WindowIcon {
191 rgba: rgba.into(),
192 width,
193 height,
194 });
195 self
196 }
197
198 pub fn with_maximized(mut self, maximized: bool) -> Self {
199 self.maximized = maximized;
200 self
201 }
202
203 pub fn with_fullscreen(mut self, fullscreen: bool) -> Self {
204 self.fullscreen = fullscreen;
205 self
206 }
207
208 pub fn with_redraw_policy(mut self, policy: RedrawPolicy) -> Self {
209 self.redraw_policy = policy;
210 self
211 }
212
213 pub fn with_copy_src(mut self, copy_src: CopySrc) -> Self {
214 self.copy_src = copy_src;
215 self
216 }
217
218 pub fn with_present_mode(mut self, present_mode: wgpu::PresentMode) -> Self {
219 self.present_mode = present_mode;
220 self
221 }
222
223 pub fn with_device_label(mut self, label: &'static str) -> Self {
224 self.device_label = label;
225 self
226 }
227
228 /// Headless-style capture: after `settle_frames` painted frames, read the
229 /// frame back, write it as a PNG to `path`, and leave the event loop.
230 /// The shell polls and paints every idle iteration until the capture
231 /// fires, so the frame count advances without any user input.
232 ///
233 /// The image is in PHYSICAL pixels — on a 2x display that is twice the
234 /// logical window size. A failed capture ends [`crate::run`] with
235 /// [`crate::ShellError::Screenshot`]; the shell never exits the process
236 /// itself.
237 pub fn with_screenshot(mut self, path: impl Into<PathBuf>, settle_frames: u32) -> Self {
238 self.screenshot = Some(ScreenshotConfig {
239 path: path.into(),
240 settle_frames,
241 });
242 self
243 }
244
245 pub fn with_os_tooltip_timings(mut self, enabled: bool) -> Self {
246 self.os_tooltip_timings = enabled;
247 self
248 }
249
250 /// Restore the window size / maximized state from `store` at startup and
251 /// save it back as it changes. See [`WindowBoundsStore`].
252 pub fn with_bounds_store(mut self, store: impl WindowBoundsStore + 'static) -> Self {
253 self.bounds_store = Some(Box::new(store));
254 self
255 }
256}
257
258#[cfg(test)]
259mod tests {
260 use super::*;
261
262 #[test]
263 fn builder_defaults_and_overrides() {
264 let cfg = ShellConfig::new("Title");
265 assert_eq!(cfg.title, "Title");
266 assert_eq!(cfg.size, WindowSize::Logical(1280.0, 720.0));
267 assert_eq!(cfg.redraw_policy, RedrawPolicy::Reactive);
268 assert!(cfg.os_tooltip_timings);
269
270 let cfg = cfg
271 .with_physical_size(1600, 900)
272 .with_min_logical_size(640.0, 480.0)
273 .with_redraw_policy(RedrawPolicy::Continuous)
274 .with_screenshot("out.png", 6);
275 assert_eq!(cfg.size, WindowSize::Physical(1600, 900));
276 assert_eq!(cfg.min_size, Some(WindowSize::Logical(640.0, 480.0)));
277 assert_eq!(cfg.redraw_policy, RedrawPolicy::Continuous);
278 assert_eq!(cfg.screenshot.map(|s| s.settle_frames), Some(6));
279 }
280
281 #[test]
282 fn min_size_can_be_given_in_either_unit() {
283 let cfg = ShellConfig::new("Title").with_min_physical_size(320, 240);
284 assert_eq!(cfg.min_size, Some(WindowSize::Physical(320, 240)));
285 }
286}