agg_gui_shell/bounds.rs
1//! Window-bounds persistence: the restore-path sanitiser, the store trait an
2//! app implements to choose its own file/format, and the save gate.
3//!
4//! The shell restores the window size at startup and writes it back as it
5//! changes; *where* it lives (a dot-file, a settings blob, the registry) is the
6//! app's business, so the shell only talks to [`WindowBoundsStore`].
7//!
8//! The stored size is canonically **physical px**: winit's `Resized` reports
9//! physical pixels, so restoring must use `PhysicalSize` too (see
10//! [`crate::WindowSize`]). Restoring a physical size as a logical one
11//! re-multiplies it by the monitor scale factor on every launch — the
12//! DPI-ratchet bug that eventually asked for a surface larger than the GPU's
13//! `max_texture_dimension_2d` and crashed `Surface::configure`.
14//! [`sanitize_restored_window_size`] is what recovers an already-corrupted
15//! saved value.
16
17/// Fallback window size when there is no saved state and the caller gave no
18/// initial size (matches the historical first-launch default).
19const DEFAULT_W: u32 = 1280;
20const DEFAULT_H: u32 = 720;
21
22/// Floor for a restored window so a zeroed / tiny saved size can't create an
23/// effectively invisible window.
24const MIN_W: u32 = 200;
25const MIN_H: u32 = 150;
26
27/// Ceiling used when the primary monitor size is unknown. Matches the common
28/// wgpu `max_texture_dimension_2d` so a restore can't request a surface the
29/// GPU will reject.
30const FALLBACK_MAX_DIM: u32 = 8192;
31
32/// A persisted window geometry. Sizes are **physical pixels**.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct SavedBounds {
35 pub width: u32,
36 pub height: u32,
37 /// Whether the window was maximized. The size is then the last *windowed*
38 /// size, not the maximized rect — restoring the maximized rect as a
39 /// windowed size would fill the screen with a non-maximized window.
40 pub maximized: bool,
41}
42
43/// Where the shell restores window bounds from and saves them to.
44///
45/// Implement it on whatever already owns the app's settings; the shell calls
46/// [`load`](WindowBoundsStore::load) once before the window is created and
47/// [`save`](WindowBoundsStore::save) when the geometry changes (gated on no
48/// mouse button being held, so a drag-resize doesn't thrash the disk) and once
49/// more on exit.
50pub trait WindowBoundsStore {
51 /// Bounds from the last run, or `None` for a first launch.
52 fn load(&self) -> Option<SavedBounds>;
53 /// Persist `bounds`. Called from the event loop, so keep it cheap — an app
54 /// that already batches its own state can just record the value here and
55 /// let its own save path write it.
56 fn save(&self, bounds: SavedBounds);
57}
58
59/// Clamp a saved (physical-px) window size into a usable, GPU-safe range.
60///
61/// - `saved` `None` → the first-launch default `(1280, 720)`.
62/// - Each dimension is clamped up to the monitor's physical size when known,
63/// else to a conservative 8192 ceiling (the common wgpu
64/// `max_texture_dimension_2d`); this is what recovers an already-corrupted
65/// saved value (the DPI-ratchet bug that grew the stored size every launch).
66/// - Each dimension is floored to 200x150 so zero/tiny values still yield a
67/// visible window.
68pub fn sanitize_restored_window_size(
69 saved: Option<(u32, u32)>,
70 monitor: Option<(u32, u32)>,
71) -> (u32, u32) {
72 let (w, h) = match saved {
73 Some(s) => s,
74 None => return (DEFAULT_W, DEFAULT_H),
75 };
76 // Guard against a monitor smaller than the floor so the clamp range stays
77 // valid (`min <= max`).
78 let (max_w, max_h) = match monitor {
79 Some((mw, mh)) => (mw.max(MIN_W), mh.max(MIN_H)),
80 None => (FALLBACK_MAX_DIM, FALLBACK_MAX_DIM),
81 };
82 (w.clamp(MIN_W, max_w), h.clamp(MIN_H, max_h))
83}
84
85/// The last window size seen while the window was neither maximized nor
86/// fullscreen — the size [`SavedBounds`] carries, so a maximized session still
87/// restores to a windowed window of the right size.
88///
89/// A separate type because both halves of it are easy to get subtly wrong and
90/// neither is observable without a real window; keeping them pure makes them
91/// testable.
92#[derive(Clone, Copy, Debug)]
93pub(crate) struct WindowedSizeTracker {
94 size: (u32, u32),
95}
96
97impl WindowedSizeTracker {
98 /// Seed from the sanitised restored size when there is one, else from the
99 /// configured surface size.
100 ///
101 /// The restored size has to win even though the surface is already live: a
102 /// window created maximized from restored bounds reports the *work-area*
103 /// rect as its surface size, and [`note_resize`](Self::note_resize) never
104 /// corrects it (every resize while maximized is ignored by design), so
105 /// seeding from the surface would persist the maximized rect as the
106 /// windowed size — and the next launch would un-maximize into a
107 /// screen-sized window. Mirrors the pre-port behaviour, which seeded from
108 /// the sanitised saved size (`start_w`/`start_h` in demo-native's old
109 /// `main.rs`).
110 pub(crate) fn new(restored: Option<(u32, u32)>, configured: (u32, u32)) -> Self {
111 Self {
112 size: restored.unwrap_or(configured),
113 }
114 }
115
116 /// Record a resize. Ignored while the window is maximized or fullscreen:
117 /// those report the work-area / monitor rect, which is exactly what must
118 /// not be persisted as the windowed size. Borderless fullscreen is the
119 /// reason `fullscreen` is checked separately — on Windows it delivers
120 /// `Resized` with `is_maximized() == false`.
121 pub(crate) fn note_resize(&mut self, size: (u32, u32), maximized: bool, fullscreen: bool) {
122 if !maximized && !fullscreen {
123 self.size = size;
124 }
125 }
126
127 pub(crate) fn size(&self) -> (u32, u32) {
128 self.size
129 }
130}
131
132/// Diff-and-gate policy for writing bounds back, mirroring
133/// `agg_gui::persistence::AutoSave` for a value type rather than a blob:
134/// write only when the bounds actually changed AND no mouse button is held,
135/// so a drag-resize doesn't hit the store on every intermediate size.
136#[derive(Default)]
137pub(crate) struct BoundsAutoSave {
138 last_saved: Option<SavedBounds>,
139}
140
141impl BoundsAutoSave {
142 /// Seed with what was loaded at startup so the first tick doesn't write
143 /// the same value straight back.
144 pub(crate) fn seed(&mut self, bounds: Option<SavedBounds>) {
145 self.last_saved = bounds;
146 }
147
148 /// Should `current` be persisted now? Returns `true` at most once per
149 /// distinct value.
150 pub(crate) fn should_save(&mut self, idle: bool, current: SavedBounds) -> bool {
151 if !idle || self.last_saved == Some(current) {
152 return false;
153 }
154 self.last_saved = Some(current);
155 true
156 }
157}
158
159#[cfg(test)]
160mod tests {
161 use super::*;
162
163 #[test]
164 fn corrupted_saved_size_clamps_to_monitor() {
165 // The user's exact crash case: a DPI-ratcheted state file grew the
166 // stored size past the GPU max; it must clamp down to the monitor.
167 let out = sanitize_restored_window_size(Some((10224, 5925)), Some((3408, 1975)));
168 assert_eq!(out, (3408, 1975));
169 }
170
171 #[test]
172 fn no_saved_size_uses_default() {
173 assert_eq!(
174 sanitize_restored_window_size(None, Some((3408, 1975))),
175 (1280, 720)
176 );
177 assert_eq!(sanitize_restored_window_size(None, None), (1280, 720));
178 }
179
180 #[test]
181 fn in_bounds_size_is_unchanged() {
182 assert_eq!(
183 sanitize_restored_window_size(Some((1600, 900)), Some((3408, 1975))),
184 (1600, 900)
185 );
186 }
187
188 #[test]
189 fn no_monitor_clamps_to_fallback_max() {
190 // Only the width exceeds the fallback ceiling; height is already below.
191 assert_eq!(
192 sanitize_restored_window_size(Some((10224, 5925)), None),
193 (8192, 5925)
194 );
195 // A reasonable size with no monitor known passes through.
196 assert_eq!(
197 sanitize_restored_window_size(Some((1280, 720)), None),
198 (1280, 720)
199 );
200 }
201
202 #[test]
203 fn zero_or_tiny_size_is_floored() {
204 assert_eq!(
205 sanitize_restored_window_size(Some((0, 0)), Some((3408, 1975))),
206 (200, 150)
207 );
208 assert_eq!(
209 sanitize_restored_window_size(Some((10, 5)), None),
210 (200, 150)
211 );
212 }
213
214 #[test]
215 fn monitor_smaller_than_floor_keeps_range_valid() {
216 // Degenerate monitor smaller than the floor must not panic the clamp;
217 // the floor wins.
218 assert_eq!(
219 sanitize_restored_window_size(Some((100, 100)), Some((50, 40))),
220 (200, 150)
221 );
222 }
223
224 #[test]
225 fn bounds_are_saved_once_per_change_and_never_mid_drag() {
226 let b = |w, h| SavedBounds {
227 width: w,
228 height: h,
229 maximized: false,
230 };
231 let mut auto = BoundsAutoSave::default();
232 auto.seed(Some(b(1280, 720)));
233 // Unchanged from what was loaded: nothing to write.
234 assert!(!auto.should_save(true, b(1280, 720)));
235 // Changed, but a mouse button is down (drag-resize in flight).
236 assert!(!auto.should_save(false, b(1000, 700)));
237 // Same change once the drag ends: written exactly once.
238 assert!(auto.should_save(true, b(1000, 700)));
239 assert!(!auto.should_save(true, b(1000, 700)));
240 // Maximizing at the same size is still a change.
241 assert!(auto.should_save(
242 true,
243 SavedBounds {
244 width: 1000,
245 height: 700,
246 maximized: true
247 }
248 ));
249 }
250
251 #[test]
252 fn restoring_maximized_keeps_the_saved_windowed_size() {
253 // The bug: a window created maximized from restored bounds comes up
254 // with the WORK-AREA rect as its surface size. Seeding the tracker
255 // from that surface size persisted the maximized rect as the windowed
256 // size, so the next launch un-maximized into a screen-sized window.
257 let mut tracker = WindowedSizeTracker::new(Some((1280, 720)), (3408, 1895));
258 assert_eq!(tracker.size(), (1280, 720));
259 // Every resize that arrives while maximized is ignored, so nothing
260 // ever corrects a bad seed.
261 tracker.note_resize((3408, 1895), true, false);
262 assert_eq!(tracker.size(), (1280, 720));
263 }
264
265 #[test]
266 fn without_saved_bounds_the_tracker_starts_at_the_surface_size() {
267 let tracker = WindowedSizeTracker::new(None, (1600, 900));
268 assert_eq!(tracker.size(), (1600, 900));
269 }
270
271 #[test]
272 fn windowed_resizes_are_tracked() {
273 let mut tracker = WindowedSizeTracker::new(Some((1280, 720)), (1280, 720));
274 tracker.note_resize((1000, 800), false, false);
275 assert_eq!(tracker.size(), (1000, 800));
276 }
277
278 #[test]
279 fn fullscreen_resizes_do_not_clobber_the_windowed_size() {
280 // Borderless fullscreen on Windows delivers `Resized` with the monitor
281 // rect and `is_maximized() == false`, so the maximized guard alone let
282 // the monitor size through.
283 let mut tracker = WindowedSizeTracker::new(Some((1280, 720)), (1280, 720));
284 tracker.note_resize((3840, 2160), false, true);
285 assert_eq!(tracker.size(), (1280, 720));
286 // Leaving fullscreen reports the real windowed size again.
287 tracker.note_resize((1280, 720), false, false);
288 assert_eq!(tracker.size(), (1280, 720));
289 }
290
291 #[test]
292 fn first_save_happens_when_nothing_was_loaded() {
293 let mut auto = BoundsAutoSave::default();
294 auto.seed(None);
295 assert!(auto.should_save(
296 true,
297 SavedBounds {
298 width: 800,
299 height: 600,
300 maximized: false
301 }
302 ));
303 }
304}