ailloli_ui_winit/
resize.rs

1//! Coalesces wgpu surface resize before redraw (handles defer/retry).
2
3use std::time::{Duration, Instant};
4
5use ailloli_ui_render_wgpu::{
6    PhysicalExtent, Renderer, RendererError, ResizeOutcome, SurfaceConfigDeferredReason,
7};
8use winit::dpi::PhysicalSize;
9use winit::window::Window;
10
11/// Delay before retrying a deferred surface resize.
12///
13/// # Examples
14///
15/// ```
16/// use std::time::Duration;
17/// assert_eq!(ailloli_ui_winit::resize::RESIZE_RETRY_DELAY, Duration::from_millis(1));
18/// ```
19pub const RESIZE_RETRY_DELAY: Duration = Duration::from_millis(1);
20
21/// Outcome of applying a pending resize to the GPU surface.
22///
23/// Durations are measured around the renderer resize/reconfigure call only and
24/// are truncated to whole microseconds.
25///
26/// # Examples
27///
28/// ```
29/// use ailloli_ui_render_wgpu::ResizeOutcome;
30/// use ailloli_ui_winit::resize::ResizeApply;
31/// use winit::dpi::PhysicalSize;
32/// let applied = ResizeApply {
33///     size: PhysicalSize::new(800, 600),
34///     outcome: ResizeOutcome::Applied,
35///     forced_surface_reconfigure: false,
36///     dur_us: 25,
37/// };
38/// assert_eq!(applied.size.width, 800);
39/// ```
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub struct ResizeApply {
42    /// Authoritative non-zero physical client extent passed to the renderer.
43    pub size: PhysicalSize<u32>,
44    /// Renderer decision for the resize or forced reconfiguration.
45    pub outcome: ResizeOutcome,
46    /// `true` when this configure was forced to recover an invalid surface,
47    /// including when `size` was unchanged.
48    pub forced_surface_reconfigure: bool,
49    /// Elapsed renderer operation time in whole microseconds.
50    pub dur_us: u128,
51}
52
53/// Result of scheduling recovery after a surface acquisition failure.
54///
55/// # Examples
56///
57/// ```
58/// use ailloli_ui_winit::resize::SurfaceRecoveryAction;
59/// let action = SurfaceRecoveryAction::ReconfigureScheduled;
60/// assert_ne!(action, SurfaceRecoveryAction::RecreatePresentation);
61/// ```
62#[derive(Debug, Clone, Copy, PartialEq, Eq)]
63pub enum SurfaceRecoveryAction {
64    /// Force one `Surface::configure` before the next render attempt.
65    ReconfigureScheduled,
66    /// A forced configure was already attempted without an intervening
67    /// successful frame; rebuild the native presentation instead.
68    RecreatePresentation,
69}
70
71/// State returned when preparing a redraw after a resize request.
72///
73/// # Examples
74///
75/// ```
76/// use ailloli_ui_winit::resize::ResizeRedrawAction;
77/// assert_eq!(ResizeRedrawAction::Ready, ResizeRedrawAction::Ready);
78/// ```
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum ResizeRedrawAction {
81    /// No pending resize; safe to draw.
82    Ready,
83    /// Waiting for retry delay after a deferred resize.
84    Waiting,
85    /// Resize applied successfully.
86    Applied(ResizeApply),
87    /// wgpu deferred surface configuration (will retry).
88    Deferred {
89        /// Latest requested physical surface extent in pixels.
90        size: PhysicalSize<u32>,
91        /// Renderer-reported reason configuration cannot proceed yet.
92        reason: SurfaceConfigDeferredReason,
93    },
94    /// Skipped because width or height is zero.
95    SkippedZero,
96}
97
98/// Tracks pending window size and schedules resize before the next frame.
99///
100/// The default controller is ready, has no retry deadline, and has not observed
101/// a zero native extent. Resize requests coalesce: the most recent non-zero
102/// physical size replaces the previous pending size.
103///
104/// # Examples
105///
106/// ```
107/// use ailloli_ui_winit::resize::ResizeController;
108/// let controller = ResizeController::default();
109/// assert!(controller.pending().is_none());
110/// assert!(!controller.zero_extent_unavailable());
111/// ```
112#[derive(Debug, Default)]
113pub struct ResizeController {
114    /// Latest non-zero physical extent waiting to be applied.
115    pending: Option<PhysicalSize<u32>>,
116    /// Earliest instant at which a deferred surface resize may be retried.
117    retry_at: Option<Instant>,
118    /// Whether the latest authoritative native extent had a zero component.
119    zero_extent_unavailable: bool,
120    /// Whether the next renderer operation must bypass the resize fast path.
121    force_surface_reconfigure: bool,
122    /// Whether a forced configure has occurred without a subsequent good frame.
123    surface_reconfigure_attempted: bool,
124}
125
126/// Minimal renderer seam used to test resize and forced-reconfigure choices.
127trait SurfaceResizeTarget {
128    /// Applies an ordinary resize, allowing an unchanged-size fast path.
129    ///
130    /// # Errors
131    ///
132    /// Returns a renderer attachment, format, or configuration error when the
133    /// target cannot apply the requested physical extent.
134    fn try_resize_target(&mut self, size: PhysicalExtent) -> Result<ResizeOutcome, RendererError>;
135
136    /// Forces surface configuration even when `size` has not changed.
137    ///
138    /// # Errors
139    ///
140    /// Returns a renderer attachment, format, or configuration error when the
141    /// target cannot force the requested physical extent.
142    fn try_reconfigure_surface_target(
143        &mut self,
144        size: PhysicalExtent,
145    ) -> Result<ResizeOutcome, RendererError>;
146}
147
148/// Connects the resize controller's testable seam to the production renderer.
149impl SurfaceResizeTarget for Renderer {
150    /// Delegates ordinary resize to [`Renderer::try_resize`].
151    ///
152    /// # Errors
153    ///
154    /// Propagates all errors from [`Renderer::try_resize`].
155    fn try_resize_target(&mut self, size: PhysicalExtent) -> Result<ResizeOutcome, RendererError> {
156        self.try_resize(size)
157    }
158
159    /// Delegates forced recovery to [`Renderer::try_reconfigure_surface`].
160    ///
161    /// # Errors
162    ///
163    /// Propagates all errors from [`Renderer::try_reconfigure_surface`].
164    fn try_reconfigure_surface_target(
165        &mut self,
166        size: PhysicalExtent,
167    ) -> Result<ResizeOutcome, RendererError> {
168        self.try_reconfigure_surface(size)
169    }
170}
171
172/// Coalescing, retry, zero-extent, and acquisition-recovery state transitions.
173impl ResizeController {
174    /// Retains a non-zero resize for the next redraw.
175    ///
176    /// A zero physical extent makes the presentation dormant immediately: no
177    /// retry deadline or pending redraw is retained until winit reports a
178    /// later non-zero size.
179    ///
180    /// Returns `true` when a non-zero request was queued and `false` when a zero
181    /// component made the surface unavailable. Queuing a non-zero request does
182    /// not clear the zero sentinel until the renderer successfully applies it.
183    ///
184    /// # Examples
185    ///
186    /// ```
187    /// use ailloli_ui_winit::resize::ResizeController;
188    /// use winit::dpi::PhysicalSize;
189    /// let mut controller = ResizeController::default();
190    /// assert!(controller.request(PhysicalSize::new(640, 480)));
191    /// assert_eq!(controller.pending(), Some(PhysicalSize::new(640, 480)));
192    /// assert!(!controller.request(PhysicalSize::new(0, 480)));
193    /// assert!(controller.pending().is_none());
194    /// ```
195    pub fn request(&mut self, size: PhysicalSize<u32>) -> bool {
196        self.retry_at = None;
197        if size.width == 0 || size.height == 0 {
198            self.pending = None;
199            self.zero_extent_unavailable = true;
200            return false;
201        }
202        self.pending = Some(size);
203        true
204    }
205
206    /// Queues the window's current physical client size.
207    ///
208    /// This has the same zero-extent and coalescing semantics as [`Self::request`].
209    ///
210    /// # Examples
211    ///
212    /// ```no_run
213    /// use ailloli_ui_winit::resize::ResizeController;
214    /// fn queue(controller: &mut ResizeController, window: &winit::window::Window) {
215    ///     let queued: bool = controller.request_window_size(window);
216    ///     let _ = queued;
217    /// }
218    /// ```
219    pub fn request_window_size(&mut self, window: &Window) -> bool {
220        self.request(window.inner_size())
221    }
222
223    /// Returns the latest queued non-zero physical extent, if any.
224    ///
225    /// # Examples
226    ///
227    /// ```
228    /// use ailloli_ui_winit::resize::ResizeController;
229    /// use winit::dpi::PhysicalSize;
230    /// let mut controller = ResizeController::default();
231    /// controller.request(PhysicalSize::new(320, 200));
232    /// assert_eq!(controller.pending(), Some(PhysicalSize::new(320, 200)));
233    /// ```
234    pub fn pending(&self) -> Option<PhysicalSize<u32>> {
235        self.pending
236    }
237
238    /// Returns the retry deadline after a renderer-deferred configure.
239    ///
240    /// `None` means no timed retry is armed; it does not imply that no ordinary
241    /// resize is pending.
242    ///
243    /// # Examples
244    ///
245    /// ```
246    /// let controller = ailloli_ui_winit::resize::ResizeController::default();
247    /// assert!(controller.retry_at().is_none());
248    /// ```
249    pub fn retry_at(&self) -> Option<Instant> {
250        self.retry_at
251    }
252
253    /// Reports whether a zero width or height currently prevents presentation.
254    ///
255    /// The flag remains set after a later non-zero request and clears only once
256    /// that request is successfully applied.
257    ///
258    /// # Examples
259    ///
260    /// ```
261    /// use ailloli_ui_winit::resize::ResizeController;
262    /// use winit::dpi::PhysicalSize;
263    /// let mut controller = ResizeController::default();
264    /// controller.request(PhysicalSize::new(100, 0));
265    /// assert!(controller.zero_extent_unavailable());
266    /// ```
267    pub fn zero_extent_unavailable(&self) -> bool {
268        self.zero_extent_unavailable
269    }
270
271    /// Schedules the first, cheap recovery step for a Lost/Outdated surface.
272    /// A repeated acquisition failure before a successful frame escalates to
273    /// full presentation recreation instead of looping on configure forever.
274    /// A zero extent preserves forced-reconfigure intent but cannot immediately
275    /// escalate because no native surface can safely be rebuilt at that size.
276    ///
277    /// # Examples
278    ///
279    /// ```no_run
280    /// use ailloli_ui_winit::resize::{ResizeController, SurfaceRecoveryAction};
281    /// fn recover(controller: &mut ResizeController, window: &winit::window::Window) {
282    ///     let action: SurfaceRecoveryAction = controller.request_surface_recovery(window);
283    ///     let _ = action;
284    /// }
285    /// ```
286    pub fn request_surface_recovery(&mut self, window: &Window) -> SurfaceRecoveryAction {
287        self.request_surface_recovery_for_size(window.inner_size())
288    }
289
290    /// Implements acquisition recovery for an already sampled physical extent.
291    fn request_surface_recovery_for_size(
292        &mut self,
293        size: PhysicalSize<u32>,
294    ) -> SurfaceRecoveryAction {
295        if size.width == 0 || size.height == 0 {
296            // A zero-sized native target cannot be recreated safely either;
297            // retain the recovery intent until a real extent arrives.
298            self.force_surface_reconfigure = true;
299            self.request(size);
300            return SurfaceRecoveryAction::ReconfigureScheduled;
301        }
302        if self.surface_reconfigure_attempted {
303            self.pending = None;
304            self.retry_at = None;
305            self.force_surface_reconfigure = false;
306            return SurfaceRecoveryAction::RecreatePresentation;
307        }
308
309        self.force_surface_reconfigure = true;
310        self.request(size);
311        SurfaceRecoveryAction::ReconfigureScheduled
312    }
313
314    /// Clears escalation state only after a frame was acquired and submitted.
315    ///
316    /// # Examples
317    ///
318    /// ```
319    /// let mut controller = ailloli_ui_winit::resize::ResizeController::default();
320    /// controller.mark_render_succeeded();
321    /// assert!(!controller.zero_extent_unavailable());
322    /// ```
323    pub fn mark_render_succeeded(&mut self) {
324        self.force_surface_reconfigure = false;
325        self.surface_reconfigure_attempted = false;
326    }
327
328    /// Applies a pending resize if due; call before rendering each frame.
329    ///
330    /// The window's current physical size is authoritative, preventing a stale
331    /// non-zero queued size from configuring a surface after minimization.
332    ///
333    /// # Errors
334    ///
335    /// Propagates renderer resize or forced-reconfiguration failures.
336    ///
337    /// # Examples
338    ///
339    /// ```no_run
340    /// use ailloli_ui_winit::resize::{ResizeController, ResizeRedrawAction};
341    /// fn prepare(
342    ///     controller: &mut ResizeController,
343    ///     window: &winit::window::Window,
344    ///     renderer: &mut ailloli_ui_render_wgpu::Renderer,
345    /// ) {
346    ///     let action: ResizeRedrawAction = controller.prepare_redraw(window, renderer).unwrap();
347    ///     let _ = action;
348    /// }
349    /// ```
350    pub fn prepare_redraw(
351        &mut self,
352        window: &Window,
353        renderer: &mut Renderer,
354    ) -> Result<ResizeRedrawAction, RendererError> {
355        self.prepare_redraw_for_size(window.inner_size(), renderer)
356    }
357
358    /// Applies a due request against the authoritative current physical size.
359    ///
360    /// # Errors
361    ///
362    /// Propagates renderer resize or forced-reconfiguration errors from
363    /// [`Self::apply_pending_update`].
364    fn prepare_redraw_for_size<T: SurfaceResizeTarget>(
365        &mut self,
366        current_size: PhysicalSize<u32>,
367        renderer: &mut T,
368    ) -> Result<ResizeRedrawAction, RendererError> {
369        let resize_is_ready = self
370            .retry_at
371            .is_none_or(|ready_at| ready_at <= Instant::now());
372        if self.pending.is_some() && !resize_is_ready {
373            return Ok(ResizeRedrawAction::Waiting);
374        }
375
376        let Some(_requested_size) = self.pending.take() else {
377            return Ok(if self.zero_extent_unavailable {
378                ResizeRedrawAction::SkippedZero
379            } else {
380                ResizeRedrawAction::Ready
381            });
382        };
383
384        // The current physical size is authoritative. In particular, a stale
385        // non-zero request must never configure a surface after the host has
386        // already collapsed the window to zero.
387        self.apply_pending_update(current_size, renderer)
388    }
389
390    /// Performs the renderer operation and updates retry/recovery state.
391    ///
392    /// # Errors
393    ///
394    /// Propagates the selected target's ordinary resize or forced surface
395    /// reconfiguration error. State after the call reflects that no successful
396    /// outcome was applied.
397    fn apply_pending_update<T: SurfaceResizeTarget>(
398        &mut self,
399        size: PhysicalSize<u32>,
400        renderer: &mut T,
401    ) -> Result<ResizeRedrawAction, RendererError> {
402        if size.width == 0 || size.height == 0 {
403            self.pending = None;
404            self.retry_at = None;
405            self.zero_extent_unavailable = true;
406            return Ok(ResizeRedrawAction::SkippedZero);
407        }
408
409        let forced_surface_reconfigure = self.force_surface_reconfigure;
410
411        let start = Instant::now();
412        let physical_extent = PhysicalExtent::new(size.width, size.height);
413        let outcome = if forced_surface_reconfigure {
414            renderer.try_reconfigure_surface_target(physical_extent)?
415        } else {
416            renderer.try_resize_target(physical_extent)?
417        };
418        match outcome {
419            ResizeOutcome::Deferred(reason) => {
420                self.defer(size);
421                Ok(ResizeRedrawAction::Deferred { size, reason })
422            }
423            ResizeOutcome::SkippedZero => {
424                self.retry_at = None;
425                self.zero_extent_unavailable = true;
426                Ok(ResizeRedrawAction::SkippedZero)
427            }
428            outcome => {
429                self.retry_at = None;
430                self.zero_extent_unavailable = false;
431                self.force_surface_reconfigure = false;
432                if forced_surface_reconfigure {
433                    self.surface_reconfigure_attempted = true;
434                }
435                Ok(ResizeRedrawAction::Applied(ResizeApply {
436                    size,
437                    outcome,
438                    forced_surface_reconfigure,
439                    dur_us: start.elapsed().as_micros(),
440                }))
441            }
442        }
443    }
444
445    /// Forces a delayed surface reconfigure at the window's current size.
446    ///
447    /// A zero component cancels the deadline and leaves the controller dormant
448    /// until another non-zero resize request arrives.
449    ///
450    /// # Examples
451    ///
452    /// ```no_run
453    /// use ailloli_ui_winit::resize::ResizeController;
454    /// fn defer(controller: &mut ResizeController, window: &winit::window::Window) {
455    ///     controller.defer_for_surface(window);
456    /// }
457    /// ```
458    pub fn defer_for_surface(&mut self, window: &Window) {
459        self.force_surface_reconfigure = true;
460        self.defer(window.inner_size());
461    }
462
463    /// Stores a non-zero retry size and arms the one-millisecond deadline.
464    fn defer(&mut self, size: PhysicalSize<u32>) {
465        if size.width == 0 || size.height == 0 {
466            self.pending = None;
467            self.retry_at = None;
468            self.zero_extent_unavailable = true;
469            return;
470        }
471        self.pending = Some(size);
472        self.retry_at = Some(Instant::now() + RESIZE_RETRY_DELAY);
473    }
474
475    /// Consumes a due retry deadline or reports an ordinary pending resize.
476    ///
477    /// Returns `false` while a timed retry is still in the future. Once due,
478    /// the deadline is cleared and exactly one `true` is returned; the pending
479    /// size remains for [`Self::prepare_redraw`].
480    ///
481    /// # Examples
482    ///
483    /// ```
484    /// use ailloli_ui_winit::resize::ResizeController;
485    /// use winit::dpi::PhysicalSize;
486    /// let mut controller = ResizeController::default();
487    /// assert!(!controller.take_due_redraw_request());
488    /// controller.request(PhysicalSize::new(10, 10));
489    /// assert!(controller.take_due_redraw_request());
490    /// ```
491    pub fn take_due_redraw_request(&mut self) -> bool {
492        if let Some(ready_at) = self.retry_at {
493            if ready_at <= Instant::now() {
494                self.retry_at = None;
495                return true;
496            }
497            return false;
498        }
499        self.pending.is_some()
500    }
501
502    /// Reports whether retained runtime work may request an immediate redraw.
503    ///
504    /// Zero extent and an armed surface retry suspend host sweeps without
505    /// consuming retained dirty work. A later non-zero native resize is
506    /// immediately eligible so it can recover a zero-extent presentation.
507    pub(crate) fn accepts_retained_redraw_request(&self) -> bool {
508        self.retry_at.is_none() && (!self.zero_extent_unavailable || self.pending.is_some())
509    }
510
511    /// Reports whether a non-zero resize is waiting to recover a dormant surface.
512    pub(crate) fn has_pending_nonzero_request(&self) -> bool {
513        self.pending.is_some()
514    }
515}
516
517#[cfg(test)]
518/// Resize coalescing, zero-extent dormancy, retry, and recovery escalation scenarios.
519mod tests {
520    use super::*;
521
522    #[derive(Debug)]
523    /// Deterministic renderer seam recording ordinary and forced resize calls.
524    struct FakeSurfaceTarget {
525        resize_calls: usize,
526        reconfigure_calls: usize,
527        outcome: ResizeOutcome,
528    }
529
530    /// Creates a target whose operations immediately report `Applied`.
531    impl FakeSurfaceTarget {
532        /// Initializes zero call counters and an immediate `Applied` outcome.
533        fn applied() -> Self {
534            Self {
535                resize_calls: 0,
536                reconfigure_calls: 0,
537                outcome: ResizeOutcome::Applied,
538            }
539        }
540    }
541
542    /// Records which surface operation the controller selected.
543    impl SurfaceResizeTarget for FakeSurfaceTarget {
544        /// Records an ordinary call and returns the configured deterministic outcome.
545        ///
546        /// # Errors
547        ///
548        /// This test target is infallible and never returns an error.
549        fn try_resize_target(
550            &mut self,
551            size: PhysicalExtent,
552        ) -> Result<ResizeOutcome, RendererError> {
553            self.resize_calls += 1;
554            Ok(if size.is_zero() {
555                ResizeOutcome::SkippedZero
556            } else {
557                self.outcome
558            })
559        }
560
561        /// Records a forced call and returns the configured deterministic outcome.
562        ///
563        /// # Errors
564        ///
565        /// This test target is infallible and never returns an error.
566        fn try_reconfigure_surface_target(
567            &mut self,
568            size: PhysicalExtent,
569        ) -> Result<ResizeOutcome, RendererError> {
570            self.reconfigure_calls += 1;
571            Ok(if size.is_zero() {
572                ResizeOutcome::SkippedZero
573            } else {
574                self.outcome
575            })
576        }
577    }
578
579    #[test]
580    fn lost_at_same_size_forces_surface_reconfigure_instead_of_resize_fast_path() {
581        let size = PhysicalSize::new(800, 600);
582        let mut controller = ResizeController::default();
583        let mut target = FakeSurfaceTarget::applied();
584
585        assert_eq!(
586            controller.request_surface_recovery_for_size(size),
587            SurfaceRecoveryAction::ReconfigureScheduled
588        );
589        let action = controller
590            .apply_pending_update(size, &mut target)
591            .expect("forced reconfigure");
592
593        assert_eq!(target.resize_calls, 0);
594        assert_eq!(target.reconfigure_calls, 1);
595        assert!(matches!(
596            action,
597            ResizeRedrawAction::Applied(ResizeApply {
598                forced_surface_reconfigure: true,
599                ..
600            })
601        ));
602    }
603
604    #[test]
605    fn repeated_lost_after_forced_reconfigure_escalates_to_recreation() {
606        let size = PhysicalSize::new(800, 600);
607        let mut controller = ResizeController::default();
608        let mut target = FakeSurfaceTarget::applied();
609
610        assert_eq!(
611            controller.request_surface_recovery_for_size(size),
612            SurfaceRecoveryAction::ReconfigureScheduled
613        );
614        controller
615            .apply_pending_update(size, &mut target)
616            .expect("forced reconfigure");
617
618        assert_eq!(
619            controller.request_surface_recovery_for_size(size),
620            SurfaceRecoveryAction::RecreatePresentation
621        );
622    }
623
624    #[test]
625    fn successful_frame_resets_surface_recovery_escalation() {
626        let size = PhysicalSize::new(800, 600);
627        let mut controller = ResizeController::default();
628        let mut target = FakeSurfaceTarget::applied();
629
630        controller.request_surface_recovery_for_size(size);
631        controller
632            .apply_pending_update(size, &mut target)
633            .expect("forced reconfigure");
634        controller.mark_render_succeeded();
635
636        assert_eq!(
637            controller.request_surface_recovery_for_size(size),
638            SurfaceRecoveryAction::ReconfigureScheduled
639        );
640    }
641
642    #[test]
643    fn repeated_surface_failure_at_zero_waits_instead_of_recreating() {
644        let size = PhysicalSize::new(800, 600);
645        let mut controller = ResizeController::default();
646        let mut target = FakeSurfaceTarget::applied();
647
648        controller.request_surface_recovery_for_size(size);
649        controller
650            .apply_pending_update(size, &mut target)
651            .expect("first forced reconfigure");
652
653        assert_eq!(
654            controller.request_surface_recovery_for_size(PhysicalSize::new(0, 600)),
655            SurfaceRecoveryAction::ReconfigureScheduled
656        );
657        assert!(controller.zero_extent_unavailable());
658        assert_eq!(controller.pending(), None);
659        assert_eq!(controller.retry_at(), None);
660        assert!(!controller.take_due_redraw_request());
661        assert_eq!(target.reconfigure_calls, 1);
662    }
663
664    #[test]
665    fn zero_extent_defers_without_losing_forced_reconfigure_intent() {
666        let mut controller = ResizeController::default();
667        let mut target = FakeSurfaceTarget::applied();
668
669        controller.request_surface_recovery_for_size(PhysicalSize::new(0, 0));
670        assert_eq!(
671            controller
672                .apply_pending_update(PhysicalSize::new(0, 0), &mut target)
673                .expect("zero extent is not fatal"),
674            ResizeRedrawAction::SkippedZero
675        );
676        assert_eq!(target.resize_calls, 0);
677        assert_eq!(target.reconfigure_calls, 0);
678
679        controller.request(PhysicalSize::new(800, 600));
680        let action = controller
681            .apply_pending_update(PhysicalSize::new(800, 600), &mut target)
682            .expect("non-zero recovery");
683        assert_eq!(target.resize_calls, 0);
684        assert_eq!(target.reconfigure_calls, 1);
685        assert!(matches!(
686            action,
687            ResizeRedrawAction::Applied(ResizeApply {
688                forced_surface_reconfigure: true,
689                ..
690            })
691        ));
692    }
693
694    #[test]
695    fn zero_zero_nonzero_stays_dormant_without_a_redraw_loop() {
696        let mut controller = ResizeController::default();
697        let mut target = FakeSurfaceTarget::applied();
698
699        assert!(!controller.request(PhysicalSize::new(0, 600)));
700        assert!(controller.zero_extent_unavailable());
701        assert_eq!(controller.pending(), None);
702        assert_eq!(controller.retry_at(), None);
703        assert!(!controller.take_due_redraw_request());
704        assert_eq!(
705            controller
706                .prepare_redraw_for_size(PhysicalSize::new(0, 600), &mut target)
707                .expect("zero extent remains dormant"),
708            ResizeRedrawAction::SkippedZero
709        );
710
711        assert!(!controller.request(PhysicalSize::new(800, 0)));
712        assert!(controller.zero_extent_unavailable());
713        assert_eq!(controller.pending(), None);
714        assert_eq!(controller.retry_at(), None);
715        assert!(!controller.take_due_redraw_request());
716        assert_eq!(target.resize_calls, 0);
717        assert_eq!(target.reconfigure_calls, 0);
718
719        assert!(controller.request(PhysicalSize::new(800, 600)));
720        assert!(controller.zero_extent_unavailable());
721        assert_eq!(controller.pending(), Some(PhysicalSize::new(800, 600)));
722        assert!(controller.take_due_redraw_request());
723        assert!(matches!(
724            controller
725                .prepare_redraw_for_size(PhysicalSize::new(800, 600), &mut target)
726                .expect("non-zero extent becomes drawable"),
727            ResizeRedrawAction::Applied(_)
728        ));
729        assert!(!controller.zero_extent_unavailable());
730        assert_eq!(controller.pending(), None);
731        assert_eq!(controller.retry_at(), None);
732        assert!(!controller.take_due_redraw_request());
733        assert_eq!(target.resize_calls, 1);
734        assert_eq!(target.reconfigure_calls, 0);
735    }
736
737    #[test]
738    fn retained_redraw_gate_suspends_zero_and_retry_without_losing_recovery() {
739        let mut controller = ResizeController::default();
740
741        assert!(controller.accepts_retained_redraw_request());
742        assert!(!controller.request(PhysicalSize::new(0, 600)));
743        assert!(!controller.accepts_retained_redraw_request());
744
745        assert!(controller.request(PhysicalSize::new(800, 600)));
746        assert!(controller.has_pending_nonzero_request());
747        assert!(controller.accepts_retained_redraw_request());
748
749        controller.defer(PhysicalSize::new(800, 600));
750        assert!(!controller.accepts_retained_redraw_request());
751        controller.retry_at = Some(Instant::now() - Duration::from_millis(1));
752        assert!(!controller.accepts_retained_redraw_request());
753        assert!(controller.take_due_redraw_request());
754        assert!(controller.accepts_retained_redraw_request());
755    }
756}