frust-shell-desktop 0.6.2

Desktop shell for Frust: winit window and event loop, input, rendering and the extension seam used by the per-OS desktop shells.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
//! The OS-neutral half of the desktop platform-view host: this crate's owner of
//! `frust-shell-common`'s [`PlatformViewState`] differ, driven from the winit
//! frame loop and delivered to whatever per-OS shell is installed through
//! [`DesktopExtensions::on_platform_view_commands`].
//!
//! The mobile shells' equivalents (`frust-shell-android`'s
//! `platform_view_commands`, `frust-shell-ios`'s `platform_view_commands_json`)
//! serve their backlog to a *polling* host across an FFI boundary. Desktop has
//! no FFI boundary and no poller: the per-OS half is an in-process trait
//! implementation on the same thread, so the backlog is **pushed** to it once
//! per frame and acknowledged immediately. That collapses the mobile
//! poll/acknowledge round trip into one call and is the whole reason this module
//! is ~a screen of glue rather than a wire format.
//!
//! # What is deliberately absent
//!
//! - **Logical→physical conversion.** iOS's `to_pv_command` multiplies every
//!   rect by the scale factor because its Swift host places views in physical
//!   px. Desktop does not convert: AppKit (the first consumer) places `NSView`s
//!   in logical points, which is exactly the space
//!   [`ViewCommand`] already carries. The hook still receives the window's
//!   `scale_factor()` so a host that *does* need physical px can scale at its
//!   own boundary, keeping the conversion where the requirement is rather than
//!   in shared code that would have to undo it.
//! - **Input shields.** [`PlatformViewState::ingest`] takes the pass's
//!   auto-collected shield rects; desktop passes `&[]`. Shields only mean
//!   anything to a host forwarding pointer input into a hosted view, which no
//!   desktop host does — the frust surface consumes everything, as on the
//!   mobile v1 path. When a desktop host grows input forwarding, this is the one
//!   line that changes.
//! - **The scroll-sync tail.** Android's `sync_tail` derives a hold from
//!   Choreographer frame-timeline samples; desktop's winit loop has no
//!   equivalent timeline signal, so there is nothing to derive one from.
//! - **[`FramePairing`](frust_shell_common::platform_view::FramePairing), the
//!   present-sync release gate.** See the timing section below.
//!
//! # Timing: commands are applied one frame ahead of presentation
//!
//! A batch is handed to the host immediately after the finished scene is
//! submitted to the frame executor, on the UI thread, i.e. *before* that scene
//! is presented. A hosted view therefore reaches its new geometry up to one
//! frame ahead of the frust content it is pinned to — visible as a hosted view
//! leading its surroundings while a scroll animates, harmless while it is
//! static.
//!
//! Closing that gap is what [`FramePairing`](frust_shell_common::platform_view::FramePairing)
//! plus [`PlatformViewState::commands_up_to`] exist for, and both mobile shells
//! use them. Desktop cannot yet: the gate needs the id of the frame the render
//! side actually **presented**, and this crate's executor publishes only a
//! presented *count* (`FrameExecutor::presented_frames`) with no frame id
//! travelling with a submission — pairing would mean a new id channel through
//! the render split, beyond this seam. Deferred deliberately, with the lead
//! bounded at ≤1 frame by construction (the batch describes the very scene being
//! submitted, never an older one); it belongs in `docs/LIMITATIONS.md` as
//! `desktop-platform-view-frame-lead` once a per-OS host makes it observable.
//!
//! # Suspend / re-create pairing
//!
//! [`DesktopPlatformViews::suspend`] tells the host to drop every hosted view,
//! so every command still queued at that moment describes a view that no longer
//! exists; it is acknowledged away rather than delivered later. The differ's
//! own live-slot map survives, which is what makes the return trip cheap — but
//! it also means the host has nothing to apply an `Update` *to* until it has
//! been told to re-create those views. Hence the contract this module relies on,
//! and `app_handler` upholds: every path back from a suspend brings the surface
//! up again, and every surface bring-up calls
//! [`DesktopPlatformViews::on_surface_recreated`], whose replay re-creates each
//! live slot before the next ingest can emit a bare `Update` for it.
//!
//! # Overlays
//!
//! With overlay surfaces on (`FRUST_OVERLAYS`, macOS only — see
//! [`crate::extensions::overlays_enabled`]) the ingest is the overlay-aware
//! one: the differ also gets the painted scene's commands and the logical
//! viewport, cuts the frame at its visible slots and announces one
//! `ViewCommand::Overlay` per cut in the same batch the host receives. The
//! ranges are folded here as they are pushed ([`DesktopPlatformViews::overlay_cuts`])
//! and travel with the very scene they were cut from to the render side, so a
//! frame's ranges are never paired with another frame's commands. Off, the
//! plain ingest keeps the command stream exactly as it was.

use std::collections::BTreeMap;
use std::ops::Range;
use std::sync::Arc;

use frust_core::RenderRoot;
use frust_core::view::View;
use frust_core::widget::PlatformViewFrame;
use frust_scene::Command;
use frust_shell_common::platform_view::{PlatformViewState, ViewCommand};
use kurbo::Rect;
use winit::window::Window;

use crate::extensions::DesktopExtensions;

/// One overlay's cut for one frame: its id and the half-open command range of
/// that frame's scene it draws.
pub(crate) type OverlayCutSpec = (u64, Range<usize>);

/// The overlays' current command ranges, folded from the differ's
/// `Overlay`/`DisposeOverlay` commands as they are pushed — the differ
/// announces a range only when it changes, so each painted frame snapshots
/// the fold.
#[derive(Debug, Default)]
struct OverlayRanges {
    ranges: BTreeMap<u64, Range<usize>>,
    /// The differ generation folded through.
    folded_generation: u64,
}

impl OverlayRanges {
    /// Fold every command `state` pushed since the last fold. Everything at or
    /// below the folded generation is already in; a generation older than it
    /// (a fresh differ) restarts the fold.
    fn fold(&mut self, state: &PlatformViewState) {
        let (generation, backlog) = state.commands();
        if generation < self.folded_generation {
            *self = Self::default();
        }
        if generation == self.folded_generation {
            return;
        }
        let (_, seen) = state.commands_up_to(self.folded_generation);
        for command in &backlog[seen.len()..] {
            match command {
                ViewCommand::Overlay {
                    overlay_id,
                    command_range,
                    ..
                } => {
                    self.ranges.insert(*overlay_id, command_range.clone());
                }
                ViewCommand::DisposeOverlay { overlay_id } => {
                    self.ranges.remove(overlay_id);
                }
                _ => {}
            }
        }
        self.folded_generation = generation;
    }

    /// The ranges as they stand, ordered by range (then id).
    fn cuts(&self) -> Vec<OverlayCutSpec> {
        let mut cuts: Vec<OverlayCutSpec> = self
            .ranges
            .iter()
            .map(|(&id, range)| (id, range.clone()))
            .collect();
        cuts.sort_by_key(|(id, range)| (range.start, range.end, *id));
        cuts
    }
}

/// The desktop shell's platform-view host: the shared differ plus the frame-loop
/// sequencing around it (ingest after paint, push after submit, acknowledge, and
/// the two lifecycle resets).
///
/// Owned by the winit `ApplicationHandler`, one per app. Costs nothing until a
/// `platform_view` widget actually paints: an empty ingest produces no commands,
/// and a drain with an empty backlog never reaches the extension hook.
#[derive(Debug, Default)]
pub(crate) struct DesktopPlatformViews {
    state: PlatformViewState,
    /// The overlays' folded ranges (module docs' *Overlays*); stays empty with
    /// overlays off.
    overlays: OverlayRanges,
}

impl DesktopPlatformViews {
    /// A host with no live slots and an empty backlog.
    pub(crate) fn new() -> Self {
        Self {
            state: PlatformViewState::new(),
            overlays: OverlayRanges::default(),
        }
    }

    /// Feed the frame that was just painted: retire the slots whose widgets were
    /// torn down, then ingest the pass's published frames. Returns whether this
    /// produced any commands.
    ///
    /// Must be called **immediately after** [`RenderRoot::paint`] and before the
    /// next rebuild: [`RenderRoot::platform_view_frames`] reflects only the most
    /// recent paint pass, and [`RenderRoot::take_retired_platform_views`] is a
    /// destructive drain, so an id missed here is only recovered by the differ's
    /// slower missing-streak backstop.
    ///
    /// Retire runs first so a slot that was torn down and a *new* slot that
    /// reused nothing of it cannot interleave: the `Dispose` is already in the
    /// batch before the ingest that might re-create the same id.
    ///
    /// `commands` is the scene that paint just recorded and `viewport` the
    /// window's logical bounds — read only with overlays on, where the ingest
    /// cuts the frame at its slots (module docs' *Overlays*); the cuts are
    /// then [`Self::overlay_cuts`].
    pub(crate) fn after_paint<State, V>(
        &mut self,
        root: &mut RenderRoot<State, V>,
        commands: &[Command],
        viewport: Rect,
    ) -> bool
    where
        State: 'static,
        V: View<State>,
    {
        let retired = root.take_retired_platform_views();
        if crate::extensions::overlays_enabled() {
            // Announced from the first frame rather than where the switch is
            // first read, which can run before the logger exists.
            static ANNOUNCED: std::sync::Once = std::sync::Once::new();
            ANNOUNCED.call_once(|| {
                log::info!("frust-overlay: overlay surfaces on (one per differ cut, Mode A)");
            });
            self.ingest_scene(&retired, root.platform_view_frames(), commands, viewport)
        } else {
            self.ingest(&retired, root.platform_view_frames())
        }
    }

    /// [`Self::ingest`]'s overlay-aware twin: the same retire-then-ingest,
    /// through the differ's `ingest_scene`, then the overlay ranges folded.
    fn ingest_scene(
        &mut self,
        retired: &[u64],
        frames: &[PlatformViewFrame],
        commands: &[Command],
        viewport: Rect,
    ) -> bool {
        let mut produced = false;
        for &slot_id in retired {
            produced |= self.state.retire(slot_id);
        }
        produced |= self.state.ingest_scene(frames, &[], commands, viewport);
        self.overlays.fold(&self.state);
        produced
    }

    /// The cuts the frame just ingested is drawn with — every live overlay's
    /// current range, ascending — to travel with its scene to the render side.
    /// Empty with overlays off.
    pub(crate) fn overlay_cuts(&self) -> Vec<OverlayCutSpec> {
        self.overlays.cuts()
    }

    /// The window-free core of [`Self::after_paint`], split out so the command
    /// stream can be driven from hand-built [`PlatformViewFrame`]s in tests
    /// rather than through a live `RenderRoot` and a real paint pass.
    fn ingest(&mut self, retired: &[u64], frames: &[PlatformViewFrame]) -> bool {
        let mut produced = false;
        for &slot_id in retired {
            produced |= self.state.retire(slot_id);
        }
        // Desktop has no shield channel — see the module docs.
        produced |= self.state.ingest(frames, &[]);
        produced
    }

    /// Hand the pending batch to the per-OS host and acknowledge it.
    ///
    /// Called once per frame, right after the scene is submitted (see the module
    /// docs' timing section) — unconditionally, not only when
    /// [`Self::after_paint`] reported a change: a backlog can also come from
    /// [`Self::on_surface_recreated`]'s replay, which no ingest produced.
    ///
    /// Acknowledging immediately after the hook returns is sound because the
    /// hook *is* the host: it has applied the batch by the time it returns,
    /// unlike a mobile poller whose acknowledgement arrives a round trip later.
    /// `scale` is the window's current `scale_factor()`, passed through for a
    /// host that needs physical px (AppKit does not).
    pub(crate) fn drain<E: DesktopExtensions>(
        &mut self,
        ext: &mut E,
        window: &Arc<Window>,
        scale: f64,
    ) {
        let Some((generation, commands)) = self.pending() else {
            return;
        };
        ext.on_platform_view_commands(window, scale, commands);
        self.applied(generation);
    }

    /// The batch [`Self::drain`] would deliver — the not-yet-acknowledged
    /// backlog plus the generation to acknowledge once it is applied — or `None`
    /// when there is nothing pending.
    ///
    /// The window-free half of the drain, so a test can assert the exact command
    /// stream: the hook call itself needs a live `winit::Window`, which cannot be
    /// constructed without an event loop (the same limit that keeps
    /// `DesktopExtensions::on_window_created` out of that trait's own spy tests).
    fn pending(&self) -> Option<(u64, &[ViewCommand])> {
        let (generation, commands) = self.state.commands();
        (!commands.is_empty()).then_some((generation, commands))
    }

    /// Acknowledge everything through `generation`, compacting it out of the
    /// backlog — the host has applied it.
    fn applied(&mut self, generation: u64) {
        self.state.acknowledge(generation);
    }

    /// The window's surface was (re)created: replay `Create` + `Update` for
    /// every live slot on the next drain, so a host that lost its view hierarchy
    /// rebuilds it from that batch alone.
    ///
    /// Called on every surface bring-up, not only a recovery: on the first one
    /// there are no live slots and this produces nothing, which is what lets the
    /// call site stay a single unconditional line covering both the render
    /// thread's `SurfaceLost` recovery and the resume after a suspend (see the
    /// module docs' suspend/re-create pairing).
    pub(crate) fn on_surface_recreated(&mut self) {
        self.state.reset_for_surface_recreate();
    }

    /// The window is going away (close, destroy, or a suspend that drops the
    /// surface): hide every live slot and tell the host to remove every hosted
    /// view.
    ///
    /// The queued backlog is acknowledged away rather than delivered: after the
    /// hook there is no hosted view left for any of it to apply to, and the
    /// dropped entries are superseded by
    /// [`Self::on_surface_recreated`]'s replay on the way back in. This mirrors
    /// the mobile shells dropping their frame pairing on the same signal —
    /// neither stage may outlive the views it refers to.
    ///
    /// Hiding (rather than disposing) keeps each slot tracked, so the return
    /// replay re-creates it with the geometry it last had; the ordinary paint
    /// that follows a resume then flips `visible` back on with a single
    /// `Update`.
    pub(crate) fn suspend<E: DesktopExtensions>(&mut self, ext: &mut E) {
        // Nothing the acknowledgement below compacts may go unfolded.
        self.overlays.fold(&self.state);
        self.state.suspend_all();
        ext.on_platform_views_suspended();
        let (generation, _) = self.state.commands();
        self.applied(generation);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use frust_shell_common::platform_view::DISPOSE_AFTER_MISSING_FRAMES;
    use kurbo::Rect;

    /// A spy over the window-free half of the platform-view seam. The command
    /// hook cannot be spied at all — it takes a `&Arc<Window>`, which needs a
    /// live event loop — so the batches it would receive are asserted through
    /// [`DesktopPlatformViews::pending`] instead, and this records only the
    /// suspend hook.
    #[derive(Debug, Default)]
    struct SpyExtensions {
        suspends: usize,
    }

    impl DesktopExtensions for SpyExtensions {
        fn on_platform_views_suspended(&mut self) {
            self.suspends += 1;
        }
    }

    /// One published frame for `slot_id` at `rect`, fully visible, with no
    /// params and no input forwarding — the shape a plain desktop slot paints.
    fn frame(slot_id: u64, rect: Rect) -> PlatformViewFrame {
        PlatformViewFrame {
            slot_id,
            view_type: "dev.frust.VideoPlayerFactory".to_string(),
            params_json: String::new(),
            params_generation: 0,
            rect,
            clip: None,
            visible: true,
            interactive: false,
            shields: Vec::new(),
            command_index: 0,
        }
    }

    /// The commands a drain would hand the host right now, owned so the caller
    /// can acknowledge in the same expression the real drain does.
    fn pending(host: &DesktopPlatformViews) -> Vec<ViewCommand> {
        host.pending()
            .map(|(_, commands)| commands.to_vec())
            .unwrap_or_default()
    }

    /// Drain without a window: take the batch, then acknowledge it exactly as
    /// [`DesktopPlatformViews::drain`] does once the hook returns.
    fn drain(host: &mut DesktopPlatformViews) -> Vec<ViewCommand> {
        let Some((generation, commands)) = host.pending() else {
            return Vec::new();
        };
        let batch = commands.to_vec();
        host.applied(generation);
        batch
    }

    #[test]
    fn a_new_slot_arrives_as_create_then_update_in_one_batch() {
        let mut host = DesktopPlatformViews::new();
        let rect = Rect::new(10.0, 20.0, 110.0, 140.0);

        assert!(host.ingest(&[], &[frame(7, rect)]));

        let batch = pending(&host);
        assert_eq!(batch.len(), 2, "create and update ship together: {batch:?}");
        assert!(matches!(
            &batch[0],
            ViewCommand::Create { slot_id: 7, view_type, interactive: false, .. }
                if view_type == "dev.frust.VideoPlayerFactory"
        ));
        assert_eq!(
            batch[1],
            ViewCommand::Update {
                slot_id: 7,
                rect,
                clip: None,
                visible: true,
                // Desktop passes no auto-collected shields, and the frame
                // declares none of its own.
                shields: Vec::new(),
                z_index: 0,
            }
        );
    }

    #[test]
    fn an_unchanged_repaint_produces_nothing() {
        let mut host = DesktopPlatformViews::new();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        host.ingest(&[], &[frame(1, rect)]);
        drain(&mut host);

        assert!(
            !host.ingest(&[], &[frame(1, rect)]),
            "a still frame must not cost the host a call"
        );
        assert!(host.pending().is_none());
    }

    #[test]
    fn a_moved_slot_produces_exactly_one_update() {
        let mut host = DesktopPlatformViews::new();
        host.ingest(&[], &[frame(1, Rect::new(0.0, 0.0, 100.0, 100.0))]);
        drain(&mut host);

        let moved = Rect::new(0.0, 40.0, 100.0, 140.0);
        assert!(host.ingest(&[], &[frame(1, moved)]));

        assert_eq!(
            pending(&host),
            vec![ViewCommand::Update {
                slot_id: 1,
                rect: moved,
                clip: None,
                visible: true,
                shields: Vec::new(),
                z_index: 0,
            }]
        );
    }

    #[test]
    fn a_slot_missing_from_two_passes_is_hidden_without_being_disposed() {
        let mut host = DesktopPlatformViews::new();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        host.ingest(&[], &[frame(1, rect)]);
        drain(&mut host);

        // One missing pass is still inside the streak: a culled-but-alive slot
        // must not flicker.
        assert!(!host.ingest(&[], &[]));
        assert!(host.pending().is_none());

        assert!(host.ingest(&[], &[]));
        assert_eq!(
            drain(&mut host),
            vec![ViewCommand::Update {
                slot_id: 1,
                rect,
                clip: None,
                visible: false,
                shields: Vec::new(),
                z_index: 0,
            }],
            "the hide reuses the slot's last known geometry"
        );

        // Still tracked: reappearing is an ordinary update, not a re-create.
        assert!(host.ingest(&[], &[frame(1, rect)]));
        assert_eq!(
            drain(&mut host),
            vec![ViewCommand::Update {
                slot_id: 1,
                rect,
                clip: None,
                visible: true,
                shields: Vec::new(),
                z_index: 0,
            }]
        );
    }

    #[test]
    fn a_slot_missing_for_the_whole_dispose_streak_is_disposed() {
        let mut host = DesktopPlatformViews::new();
        host.ingest(&[], &[frame(1, Rect::new(0.0, 0.0, 100.0, 100.0))]);
        drain(&mut host);

        for _ in 0..DISPOSE_AFTER_MISSING_FRAMES {
            host.ingest(&[], &[]);
        }
        let batch = drain(&mut host);
        assert!(
            batch.contains(&ViewCommand::Dispose { slot_id: 1 }),
            "the streak backstop must tear the view down: {batch:?}"
        );

        // Forgotten, so the same id reappearing is indistinguishable from new.
        host.ingest(&[], &[frame(1, Rect::new(0.0, 0.0, 100.0, 100.0))]);
        let batch = drain(&mut host);
        assert!(matches!(batch.first(), Some(ViewCommand::Create { .. })));
    }

    #[test]
    fn a_retired_slot_is_disposed_immediately() {
        let mut host = DesktopPlatformViews::new();
        host.ingest(&[], &[frame(1, Rect::new(0.0, 0.0, 100.0, 100.0))]);
        drain(&mut host);

        // The torn-down widget's id arrives with the pass it stopped painting
        // in, which is how the prompt path beats the missing streak.
        assert!(host.ingest(&[1], &[]));
        assert_eq!(drain(&mut host), vec![ViewCommand::Dispose { slot_id: 1 }]);
    }

    #[test]
    fn a_surface_recreate_replays_every_live_slot() {
        let mut host = DesktopPlatformViews::new();
        let first = Rect::new(0.0, 0.0, 100.0, 100.0);
        let second = Rect::new(0.0, 200.0, 100.0, 300.0);
        host.ingest(&[], &[frame(1, first), frame(2, second)]);
        drain(&mut host);

        host.on_surface_recreated();

        let batch = drain(&mut host);
        assert_eq!(batch.len(), 4, "create + update per live slot: {batch:?}");
        assert!(matches!(&batch[0], ViewCommand::Create { slot_id: 1, .. }));
        assert_eq!(
            batch[1],
            ViewCommand::Update {
                slot_id: 1,
                rect: first,
                clip: None,
                visible: true,
                shields: Vec::new(),
                z_index: 0,
            }
        );
        assert!(matches!(&batch[2], ViewCommand::Create { slot_id: 2, .. }));
        assert_eq!(
            batch[3],
            ViewCommand::Update {
                slot_id: 2,
                rect: second,
                clip: None,
                visible: true,
                shields: Vec::new(),
                z_index: 1,
            }
        );
    }

    #[test]
    fn suspend_fires_the_hook_and_leaves_nothing_queued() {
        let mut host = DesktopPlatformViews::new();
        let mut ext = SpyExtensions::default();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        host.ingest(&[], &[frame(1, rect)]);
        drain(&mut host);

        host.suspend(&mut ext);

        assert_eq!(ext.suspends, 1, "the host must be told to drop its views");
        assert!(
            host.pending().is_none(),
            "queued commands describe views the host has just removed"
        );

        // The slots stay tracked, so the way back in is the replay — a bare
        // `Update` for a view the host no longer has would be dropped on the
        // floor.
        host.on_surface_recreated();
        let batch = drain(&mut host);
        assert!(matches!(&batch[0], ViewCommand::Create { slot_id: 1, .. }));
        assert_eq!(
            batch[1],
            ViewCommand::Update {
                slot_id: 1,
                rect,
                clip: None,
                // Hidden by the suspend; the first paint after the resume flips
                // it back.
                visible: false,
                shields: Vec::new(),
                z_index: 0,
            }
        );
    }

    #[test]
    fn suspending_with_nothing_hosted_still_notifies_the_host() {
        let mut host = DesktopPlatformViews::new();
        let mut ext = SpyExtensions::default();

        host.suspend(&mut ext);

        assert_eq!(ext.suspends, 1);
        assert!(host.pending().is_none());
    }

    #[test]
    fn acknowledging_a_batch_stops_it_being_delivered_again() {
        let mut host = DesktopPlatformViews::new();
        let rect = Rect::new(0.0, 0.0, 100.0, 100.0);
        host.ingest(&[], &[frame(1, rect)]);

        let first = drain(&mut host);
        assert_eq!(first.len(), 2);
        assert!(
            host.pending().is_none(),
            "an acknowledged batch is compacted out of the backlog"
        );

        // An un-acknowledged batch, by contrast, is re-served verbatim — which
        // is what makes a missed drain harmless.
        host.ingest(&[], &[frame(1, Rect::new(0.0, 10.0, 100.0, 110.0))]);
        assert_eq!(pending(&host), pending(&host));
        assert_eq!(pending(&host).len(), 1);
    }

    // --- Overlays ------------------------------------------------------

    /// A painted scene of `drawing` fills ([`slot_at`] places a slot between
    /// them by command index).
    fn scene_with_slot(drawing: usize) -> frust_scene::Scene {
        let mut scene = frust_scene::Scene::new();
        let mut builder = frust_scene::SceneBuilder::new(&mut scene);
        for _ in 0..drawing {
            builder.fill_rect(
                Rect::new(0.0, 0.0, 10.0, 10.0),
                peniko::Brush::Solid(peniko::Color::BLACK),
            );
        }
        scene
    }

    fn slot_at(slot_id: u64, command_index: usize) -> PlatformViewFrame {
        PlatformViewFrame {
            command_index,
            ..frame(slot_id, Rect::new(0.0, 0.0, 100.0, 100.0))
        }
    }

    #[test]
    fn an_overlay_aware_ingest_announces_the_overlay_and_folds_its_range() {
        let mut host = DesktopPlatformViews::new();
        let scene = scene_with_slot(5);
        let viewport = Rect::new(0.0, 0.0, 800.0, 600.0);
        assert!(host.ingest_scene(&[], &[slot_at(1, 2)], scene.commands(), viewport));
        assert!(
            pending(&host)
                .iter()
                .any(|command| matches!(command, ViewCommand::Overlay { overlay_id: 1, .. })),
            "the batch the host receives carries the overlay"
        );
        assert_eq!(host.overlay_cuts(), vec![(1, 2..5)]);
        // Delivered and acknowledged: the fold keeps the range.
        drain(&mut host);
        assert!(!host.ingest_scene(&[], &[slot_at(1, 2)], scene.commands(), viewport));
        assert_eq!(host.overlay_cuts(), vec![(1, 2..5)]);

        // The slot torn down: its overlay goes first, and with it the cut.
        assert!(host.ingest_scene(&[1], &[], scene.commands(), viewport));
        assert!(host.overlay_cuts().is_empty());
        assert!(matches!(
            pending(&host).first(),
            Some(ViewCommand::DisposeOverlay { overlay_id: 1 })
        ));
    }

    #[test]
    fn the_plain_ingest_folds_no_overlay() {
        let mut host = DesktopPlatformViews::new();
        host.ingest(&[], &[slot_at(1, 2)]);
        assert!(host.overlay_cuts().is_empty());
        assert!(
            !pending(&host)
                .iter()
                .any(|command| matches!(command, ViewCommand::Overlay { .. }))
        );
    }
}