denise-winit 0.31.0

Desktop development and preview backend for Denise, on winit + softbuffer.
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
//! The event loop, and the windows it drives.
//!
//! One `Runner` owns every window the application has open: the one [`run_with`]
//! created and every [`WindowRequest`] the application has handed back since. They
//! are not otherwise special-cased — a secondary window has its own surface, its
//! own damage tracker, its own frame deadline and its own [`DeniseApp`], and the
//! loop treats it exactly like the first one. The main window is distinguished by
//! one rule and no others: **closing it ends the run**, and closing any other
//! window closes that window.
//!
//! [`run_with`]: crate::run_with

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{Duration, Instant};

use denise::{
    DamageTracker, ElementState, InputEvent, InputSource, MAX_DAMAGE_RECTS, Point, PointerButton,
    Rect, Size, Surface,
};
use winit::application::ApplicationHandler;
use winit::dpi::{LogicalSize, PhysicalPosition, PhysicalSize};
use winit::event::{MouseButton, MouseScrollDelta, StartCause, TouchPhase, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow};
use winit::keyboard::ModifiersState;
use winit::window::{Window, WindowId};

#[cfg(feature = "gpu")]
use crate::GpuSurface;
use crate::{
    Build, DeniseApp, Error, LINE_HEIGHT_PX, Modality, PlatformSurface, Present, Waker,
    WindowConfig, WindowRequest, keymap, owner,
};

/// One window, its surface, and the application drawing into it.
///
/// Everything here is per-window and none of it can be shared. `modifiers` and
/// `cursor` especially: modifier state belongs to whichever window has keyboard
/// focus, and a shared cursor position would hand a dialog the coordinates of a
/// pointer that is over the window behind it.
/// What a window draws with: the platform's CPU surface, or a swapchain.
///
/// Everything the runner asks of a surface besides `acquire`/`present` is the
/// same on both, and dispatches here; the paint step is where they differ.
enum Backend {
    /// Both boxed: each surface carries buffers and bookkeeping of its own
    /// size, and a window's state should not be sized for the larger one.
    Software(Box<PlatformSurface>),
    #[cfg(feature = "gpu")]
    Gpu(Box<GpuSurface>),
}

impl Backend {
    fn size(&self) -> Size {
        match self {
            Backend::Software(s) => s.size(),
            #[cfg(feature = "gpu")]
            Backend::Gpu(s) => s.size(),
        }
    }

    fn scale_factor(&self) -> f32 {
        match self {
            Backend::Software(s) => s.scale_factor(),
            #[cfg(feature = "gpu")]
            Backend::Gpu(s) => s.scale_factor(),
        }
    }

    fn window(&self) -> &Arc<Window> {
        match self {
            Backend::Software(s) => s.window(),
            #[cfg(feature = "gpu")]
            Backend::Gpu(s) => s.window(),
        }
    }

    fn resize(&mut self, size: Size, scale_factor: f32) {
        match self {
            Backend::Software(s) => s.resize(size, scale_factor),
            #[cfg(feature = "gpu")]
            Backend::Gpu(s) => s.resize(size, scale_factor),
        }
    }

    fn poll(&mut self, out: &mut Vec<InputEvent>) {
        match self {
            Backend::Software(s) => s.poll(out),
            #[cfg(feature = "gpu")]
            Backend::Gpu(s) => s.poll(out),
        }
    }

    fn push_event(&mut self, event: InputEvent) {
        match self {
            Backend::Software(s) => s.push_event(event),
            #[cfg(feature = "gpu")]
            Backend::Gpu(s) => s.push_event(event),
        }
    }
}

struct WindowState {
    window: Arc<Window>,
    surface: Backend,
    app: Box<dyn DeniseApp>,
    damage: DamageTracker,
    events: Vec<InputEvent>,
    modifiers: ModifiersState,
    cursor: Point,
    /// When the next frame is due, or `None` to wait for input.
    next_frame: Option<Instant>,
    /// The window this one was opened from, and `None` for the main window or a
    /// window the application asked to be [`Modality::Independent`].
    owner: Option<WindowId>,
    modality: Modality,
    /// How fast this window may draw. Per-window because a settings form has no
    /// reason to share the main window's cadence.
    frame_interval: Duration,
    /// What the title bar was last given, so `DeniseApp::title` answering the
    /// same thing every frame is a comparison rather than a call into the
    /// window system.
    title: String,
    /// The position and maximised state last reported as `SurfaceMoved`, so a
    /// window that is resized without moving does not say it moved.
    placed: Option<(Point, bool)>,
}

pub(crate) struct Runner {
    /// The main window's configuration, held until there is an event loop to
    /// create it in.
    pub(crate) config: WindowConfig,
    /// Consumed when the main window appears; `None` from then on.
    pub(crate) build: Option<Build>,
    windows: HashMap<WindowId, WindowState>,
    /// The window whose closing ends the run. `None` until it exists.
    main: Option<WindowId>,
    /// Requests made during a frame, created before the loop next waits.
    ///
    /// Windows cannot be created while a frame is in flight: the application asks
    /// during `update`, and `ActiveEventLoop` is not in reach there. So the ask is
    /// queued with the window that made it — which is the window that will own the
    /// result — and honoured in `about_to_wait`, a few microseconds later.
    pending: Vec<(WindowId, WindowRequest)>,
    pub(crate) error: Option<Error>,
    /// Handed to every application as its window opens.
    waker: Waker,
}

impl Runner {
    pub(crate) fn new(config: WindowConfig, build: Build, waker: Waker) -> Self {
        Self {
            waker,
            config,
            build: Some(build),
            windows: HashMap::new(),
            main: None,
            pending: Vec::new(),
            error: None,
        }
    }

    fn fail(&mut self, event_loop: &ActiveEventLoop, err: Error) {
        self.error = Some(err);
        event_loop.exit();
    }

    /// Creates a window, its surface and the application inside it.
    ///
    /// The application is built here rather than by the caller for the reason
    /// [`run_with`](crate::run_with) exists: the surface's size and the display's
    /// scale factor are two facts that do not exist until this moment, and a tree
    /// laid out in physical pixels without them comes out half size on a HiDPI
    /// display. A secondary window gets the same guarantee, and it is not
    /// academic — a settings form opens on whichever display its owner is on.
    fn spawn(
        &mut self,
        event_loop: &ActiveEventLoop,
        config: &WindowConfig,
        build: Build,
        owned_by: Option<WindowId>,
        modality: Modality,
    ) -> Result<WindowId, Error> {
        let mut attrs = Window::default_attributes()
            .with_title(config.title.clone())
            .with_resizable(config.resizable);

        // The monitor's own size, in physical pixels, when the application asked
        // for it. Physical because that is what a monitor reports and what the
        // surface will be; converting through logical to ask for the same number
        // back is a rounding error waiting to happen.
        let monitor = config
            .fill_monitor
            .then(|| {
                event_loop
                    .primary_monitor()
                    .or_else(|| event_loop.available_monitors().next())
            })
            .flatten();
        attrs = match monitor {
            Some(m) => {
                let s = m.size();
                attrs.with_inner_size(PhysicalSize::new(s.width, s.height))
            }
            // Logical, so the window covers the same apparent area whatever the
            // display's DPI. What comes back is physical and may be larger.
            None => attrs.with_inner_size(LogicalSize::new(config.size.width, config.size.height)),
        };

        // Where it was last time, when that is somewhere the user can still
        // reach: a window remembered onto a display that has since been
        // unplugged would open off the desk entirely.
        let place_at = config
            .position
            .filter(|at| reachable(monitor_bounds(event_loop), *at));
        if let Some(at) = place_at {
            attrs = attrs.with_position(PhysicalPosition::new(at.x, at.y));
        }
        if config.maximized {
            attrs = attrs.with_maximized(true);
        }
        #[cfg(any(
            target_os = "linux",
            target_os = "dragonfly",
            target_os = "freebsd",
            target_os = "netbsd",
            target_os = "openbsd"
        ))]
        if let Some(app_id) = &config.app_id {
            // One setting behind both: winit keeps a single name, which Wayland
            // sends as the app_id and X11 writes into WM_CLASS as both halves.
            attrs = winit::platform::wayland::WindowAttributesExtWayland::with_name(
                attrs,
                app_id.clone(),
                app_id.clone(),
            );
        }

        // The owner relationship is a creation-time fact on Windows, so it has to
        // be said here even though the platform that needs it most is not the one
        // this is usually compiled for.
        if modality != Modality::Independent
            && let Some(owner_state) = owned_by.and_then(|id| self.windows.get(&id))
        {
            attrs = owner::own(attrs, &owner_state.window);
        }

        let window = Arc::new(event_loop.create_window(attrs)?);

        // And again, because the two ways of saying where a window goes do not
        // mean the same thing on macOS: the attribute places the *content*
        // below the title bar, while `outer_position` — what `SurfaceMoved`
        // reports — is the frame's own corner, title bar included. A window
        // remembered through that pair climbs its own title bar's height every
        // time it is opened. This says it in the units it will be read back
        // in, so the round trip is exact.
        //
        // Not while maximised: the window manager has the frame then, and the
        // remembered corner is where the window goes when it is let go of.
        if let Some(at) = place_at.filter(|_| !config.maximized) {
            window.set_outer_position(PhysicalPosition::new(at.x, at.y));
        }
        let surface = match config.present {
            Present::Software => Backend::Software(Box::new(PlatformSurface::new(window.clone())?)),
            #[cfg(feature = "gpu")]
            Present::Gpu => Backend::Gpu(Box::new(GpuSurface::new(window.clone())?)),
            #[cfg(not(feature = "gpu"))]
            Present::Gpu => {
                return Err(Error::Gpu(
                    "denise-winit was built without the `gpu` feature".into(),
                ));
            }
            // Decided here, for this window, rather than by the application
            // after `run_with` returns: winit makes one event loop per process,
            // so a second attempt at the run is not a thing that can be made.
            // The window itself is kept; only what draws into it changes.
            #[cfg(feature = "gpu")]
            Present::GpuOrSoftware => match GpuSurface::new(window.clone()) {
                Ok(gpu) => Backend::Gpu(Box::new(gpu)),
                Err(Error::Gpu(reason) | Error::Present(reason)) => {
                    eprintln!(
                        "denise: cannot draw through the GPU ({reason}); drawing in software"
                    );
                    Backend::Software(Box::new(PlatformSurface::new(window.clone())?))
                }
                Err(err) => return Err(err),
            },
            #[cfg(not(feature = "gpu"))]
            Present::GpuOrSoftware => {
                Backend::Software(Box::new(PlatformSurface::new(window.clone())?))
            }
        };
        let id = window.id();

        if modality != Modality::Independent
            && let Some(owner_state) = owned_by.and_then(|id| self.windows.get(&id))
        {
            owner::adopt(&owner_state.window, &window);
            if modality == Modality::Modal {
                owner::set_enabled(&owner_state.window, false);
            }
        }

        let mut app = build(surface.size(), surface.scale_factor());
        app.set_waker(self.waker.clone());
        app.presenting(match surface {
            Backend::Software(_) => Present::Software,
            #[cfg(feature = "gpu")]
            Backend::Gpu(_) => Present::Gpu,
        });

        self.windows.insert(
            id,
            WindowState {
                damage: DamageTracker::new(surface.size()),
                // What `with_title` above already put in the bar, so the first
                // frame does not set it again.
                title: config.title.clone(),
                window,
                surface,
                app,
                events: Vec::new(),
                modifiers: ModifiersState::empty(),
                cursor: Point::ZERO,
                next_frame: Some(Instant::now()),
                owner: owned_by.filter(|_| modality != Modality::Independent),
                modality,
                frame_interval: config.frame_interval,
                placed: None,
            },
        );
        self.report_place(id);
        Ok(id)
    }

    /// Closes a window and everything opened from it, telling each application
    /// it is done as it goes.
    ///
    /// Depth first, so a modal over a settings form is gone before the form it
    /// belonged to — which is the order that leaves no window without an owner,
    /// however briefly.
    fn close(&mut self, id: WindowId) {
        let mut unblocked = Vec::new();

        let links: Vec<Link> = self.links().collect();
        for doomed in closing_order(&links, id) {
            let Some(mut closed) = self.windows.remove(&doomed) else {
                continue;
            };
            closed.app.exiting();
            if let (Modality::Modal, Some(owner_id)) = (closed.modality, closed.owner) {
                unblocked.push(owner_id);
            }
        }

        for owner_id in unblocked {
            // Two modals over the same owner is not a thing any application should
            // do, but re-enabling the owner while the second one is still up would
            // be a window that ignores the dialog in front of it — the exact bug
            // modality exists to prevent. So the owner comes back only when the
            // last of them has gone, and only if it is still here itself: closing
            // an owner is also what closed this modal.
            if self.blocker(owner_id).is_some() {
                continue;
            }
            if let Some(owner_state) = self.windows.get(&owner_id) {
                owner::set_enabled(&owner_state.window, true);
                owner_state.window.focus_window();
            }
        }
    }

    /// Every window's place in the ownership graph.
    fn links(&self) -> impl Iterator<Item = Link> + '_ {
        self.windows
            .iter()
            .map(|(id, state)| (*id, state.owner, state.modality))
    }

    /// The modal window blocking `id`, if one is open over it.
    ///
    /// On the input path — every pointer move consults it — so it walks the
    /// windows rather than collecting them. There are never many.
    fn blocker(&self, id: WindowId) -> Option<&WindowState> {
        let blocker = blocker_of(self.links(), id)?;
        self.windows.get(&blocker)
    }

    /// Tells a window's application where the window is, when that has changed
    /// since the last time it was told.
    ///
    /// Called when the window is created — an application wants to know where
    /// it ended up even if nobody ever moves it, and where it ended up is not
    /// always where it asked to be — and whenever it moves or changes size,
    /// because maximising is both at once and restoring is neither on its own.
    ///
    /// A backend that will not say where its windows are says nothing: asking
    /// Wayland for a window's position is an error there by design, and an
    /// application that never hears is no worse off than one on a system that
    /// never moves anything.
    fn report_place(&mut self, id: WindowId) {
        let Some(state) = self.windows.get_mut(&id) else {
            return;
        };
        let Ok(at) = state.window.outer_position() else {
            return;
        };
        let position = Point::new(at.x, at.y);
        let maximized = state.window.is_maximized();
        if state.placed == Some((position, maximized)) {
            return;
        }
        state.placed = Some((position, maximized));
        state.events.push(InputEvent::SurfaceMoved {
            position,
            maximized,
        });
    }

    fn on_resize(&mut self, id: WindowId, size: PhysicalSize<u32>) {
        let Some(state) = self.windows.get_mut(&id) else {
            return;
        };
        let size = Size::new(size.width, size.height);
        let scale = state.surface.window().scale_factor() as f32;
        state.surface.resize(size, scale);
        state.damage.resize(size);
        state.events.push(InputEvent::SurfaceResized {
            size,
            scale_factor: scale,
        });
        // Maximising is a move and a resize together, and on some window
        // managers only the resize arrives.
        self.report_place(id);
    }

    fn draw(&mut self, event_loop: &ActiveEventLoop, id: WindowId) {
        match self.draw_frame(id) {
            // A zero-sized or minimised window has nothing to draw; not an error.
            Ok(_) => {}
            Err(err) => return self.fail(event_loop, err),
        }

        let Some(state) = self.windows.get_mut(&id) else {
            return;
        };

        // Advance the cadence only when a frame was actually attempted. Doing this
        // from `about_to_wait` instead pushes the deadline further out on every
        // spurious wake-up, and the loop never draws again.
        //
        // How far it advances is the application's to say. `frame_interval` is
        // the floor — a cap on how fast, never a demand — and the answer is
        // taken after the frame, when whatever just animated has had its say.
        let now = Instant::now();
        let interval = state.frame_interval;
        state.next_frame = state
            .app
            .next_frame_in()
            .map(|asked| now + asked.max(interval));

        // A document's name belongs in the bar the moment it opens, not only at
        // start-up. Compared before it is set, because every platform's
        // `set_title` is a round trip.
        if let Some(wanted) = state.app.title()
            && wanted != state.title
        {
            state.window.set_title(wanted);
            state.title.clear();
            state.title.push_str(wanted);
        }

        if state.app.exit_requested() {
            // The main window ends the run; any other window ends only itself,
            // which is what makes a settings form closable without taking the
            // application down with it.
            if self.main == Some(id) {
                event_loop.exit();
            } else {
                self.close(id);
            }
        }
    }

    /// Runs one update/render/present cycle. `Ok(false)` means the surface was not
    /// in a drawable state and the frame was skipped.
    fn draw_frame(&mut self, id: WindowId) -> Result<bool, Error> {
        let requests = {
            let Some(state) = self.windows.get_mut(&id) else {
                return Ok(false);
            };
            state.surface.poll(&mut state.events);
            state.app.update(&state.events, &mut state.damage);
            state.events.clear();
            // Asked for on every frame, including the ones that draw nothing: a
            // window opened in response to a keypress that dirtied no pixels is
            // still a window the application asked for.
            state.app.take_windows()
        };
        self.pending
            .extend(requests.into_iter().map(|request| (id, request)));

        self.paint(id)
    }

    /// Paints and presents one window, if anything in it changed.
    fn paint(&mut self, id: WindowId) -> Result<bool, Error> {
        let Some(state) = self.windows.get_mut(&id) else {
            return Ok(false);
        };

        // Nothing changed: no buffer, no paint, no present, no frame at all.
        //
        // This is the whole promise of a damage tracker, and skipping it here
        // was costing more than everything else in the loop put together. A
        // present is not free anywhere, and on macOS it is not even
        // proportional to the damage: CoreAnimation re-uploads the entire
        // surface through `CGContextDrawImage` on every commit, whatever
        // rectangles softbuffer was handed. At 60 Hz on a 2560×1600 Retina
        // surface that is sixteen megabytes a frame — about a gigabyte a
        // second — to display a window in which nothing had happened.
        //
        // The shadow buffer is persistent, so a skipped frame leaves the
        // screen exactly as it was and the next real frame still only owes the
        // damage since this one.
        if state.damage.is_clean() {
            return Ok(false);
        }

        let WindowState {
            surface,
            app,
            damage,
            ..
        } = state;
        match surface {
            Backend::Software(surface) => {
                let mut frame = match surface.acquire() {
                    Ok(frame) => frame,
                    Err(denise::SurfaceError::NotReady) => return Ok(false),
                    Err(err) => return Err(err.into()),
                };

                // Widen this frame's damage to cover everything the acquired buffer missed,
                // then copy it out so the tracker can be advanced afterwards.
                let mut resolved = [Rect::ZERO; MAX_DAMAGE_RECTS];
                let count = {
                    let src = damage.resolve(frame.age());
                    resolved[..src.len()].copy_from_slice(src);
                    src.len()
                };
                let region = &resolved[..count];

                app.render(&mut frame, region);
                drop(frame);

                surface.present(region)?;
                damage.end_frame();
                Ok(true)
            }
            #[cfg(feature = "gpu")]
            Backend::Gpu(surface) => {
                // The same resolve the software path does, against the age of
                // the target this surface keeps between frames: `Frames(1)`
                // once there is one, so an incremental repaint is a repaint of
                // the damage rather than of the window.
                let age = surface.age();
                let mut resolved = [Rect::ZERO; MAX_DAMAGE_RECTS];
                let count = {
                    let src = damage.resolve(age);
                    resolved[..src.len()].copy_from_slice(src);
                    src.len()
                };
                let region = &resolved[..count];
                let mut supported = true;
                let drawn = surface.paint(region, |pen| {
                    supported = app.paint(pen, age, region);
                })?;
                if !supported {
                    return Err(Error::Gpu(
                        "this application draws into frames only; implement \
                         `DeniseApp::paint` to present through the GPU"
                            .into(),
                    ));
                }
                if drawn {
                    damage.end_frame();
                }
                Ok(drawn)
            }
        }
    }

    /// Creates every window asked for since the last wait.
    ///
    /// A request whose owner has closed in the meantime is dropped: the form it
    /// belonged to is gone, and a modal with nothing to be modal to is a window
    /// nobody can explain.
    fn open_pending(&mut self, event_loop: &ActiveEventLoop) {
        for (opener, request) in std::mem::take(&mut self.pending) {
            if !self.windows.contains_key(&opener) {
                continue;
            }
            let WindowRequest {
                config,
                modality,
                build,
            } = request;
            if let Err(err) = self.spawn(event_loop, &config, build, Some(opener), modality) {
                return self.fail(event_loop, err);
            }
        }
    }
}

impl ApplicationHandler for Runner {
    fn resumed(&mut self, event_loop: &ActiveEventLoop) {
        if self.main.is_some() {
            return;
        }
        let Some(build) = self.build.take() else {
            return;
        };
        let config = self.config.clone();
        match self.spawn(event_loop, &config, build, None, Modality::Independent) {
            Ok(id) => self.main = Some(id),
            Err(err) => self.fail(event_loop, err),
        }
    }

    /// A [`Waker`]'s message: every window is due a frame now, as it would be
    /// for input.
    fn user_event(&mut self, _event_loop: &ActiveEventLoop, (): ()) {
        let now = Instant::now();
        for state in self.windows.values_mut() {
            state.next_frame = Some(now);
        }
    }

    fn new_events(&mut self, _event_loop: &ActiveEventLoop, _cause: StartCause) {
        // Deliberately not keyed on `StartCause::ResumeTimeReached`. macOS cancels
        // the wait constantly for reasons of its own, and a loop that only draws on
        // a clean timeout never draws at all there. Compare against the deadline
        // instead: it is the same test, and it survives spurious wake-ups.
        let now = Instant::now();
        for state in self.windows.values() {
            if state.next_frame.is_some_and(|next| now >= next) {
                state.window.request_redraw();
            }
        }
    }

    fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
        if !self.windows.contains_key(&id) {
            return;
        }

        match event {
            WindowEvent::RedrawRequested => return self.draw(event_loop, id),

            WindowEvent::Resized(size) => return self.on_resize(id, size),

            WindowEvent::Moved(_) => return self.report_place(id),

            WindowEvent::ScaleFactorChanged { .. } => {
                let size = self.windows.get(&id).map(|s| s.window.inner_size());
                if let Some(size) = size {
                    self.on_resize(id, size);
                }
                return;
            }

            _ => {}
        }

        // A window with a modal open over it is not a window the user is talking
        // to. Windows has already stopped delivering most of this — a disabled
        // window gets no input at all — but macOS and Linux have not, and this is
        // where modality is actually enforced on them: the events are dropped, and
        // a press says where the user should be looking instead.
        //
        // Repainting is deliberately above this line. A blocked window still
        // resizes, still redraws and still animates; what it does not do is
        // listen.
        if let Some(blocker) = self.blocker(id) {
            let raise = matches!(
                event,
                WindowEvent::CloseRequested
                    | WindowEvent::MouseInput {
                        state: winit::event::ElementState::Pressed,
                        ..
                    }
            );
            if raise {
                blocker.window.focus_window();
            }
            return;
        }

        match event {
            // Handled before the surface is borrowed below, because answering it
            // needs the application: the event goes to the tree either way, and
            // the answer decides whether this is the last frame.
            WindowEvent::CloseRequested => {
                let Some(state) = self.windows.get_mut(&id) else {
                    return;
                };
                state.surface.push_event(InputEvent::CloseRequested);
                if !state.app.close_requested() {
                    return;
                }
                if self.main == Some(id) {
                    event_loop.exit();
                } else {
                    self.close(id);
                }
                return;
            }

            WindowEvent::ModifiersChanged(mods) => {
                if let Some(state) = self.windows.get_mut(&id) {
                    state.modifiers = mods.state();
                }
                return;
            }

            WindowEvent::CursorMoved { position, .. } => {
                if let Some(state) = self.windows.get_mut(&id) {
                    state.cursor = Point::new(position.x as i32, position.y as i32);
                }
            }

            _ => {}
        }

        let Some(state) = self.windows.get_mut(&id) else {
            return;
        };
        let modifiers = keymap::modifiers(state.modifiers);
        let cursor = state.cursor;
        let surface = &mut state.surface;

        match event {
            WindowEvent::CursorMoved { .. } => {
                surface.push_event(InputEvent::PointerMoved { position: cursor });
            }

            WindowEvent::CursorLeft { .. } => surface.push_event(InputEvent::PointerLeft),

            WindowEvent::MouseInput { state, button, .. } => {
                surface.push_event(InputEvent::PointerButton {
                    button: match button {
                        MouseButton::Left => PointerButton::Left,
                        MouseButton::Right => PointerButton::Right,
                        MouseButton::Middle => PointerButton::Middle,
                        MouseButton::Back => PointerButton::Other(3),
                        MouseButton::Forward => PointerButton::Other(4),
                        MouseButton::Other(n) => PointerButton::Other(n),
                    },
                    state: element_state(state),
                    position: cursor,
                    modifiers,
                });
            }

            WindowEvent::MouseWheel { delta, .. } => {
                let (dx, dy) = match delta {
                    MouseScrollDelta::LineDelta(x, y) => (x * LINE_HEIGHT_PX, y * LINE_HEIGHT_PX),
                    MouseScrollDelta::PixelDelta(p) => (p.x as f32, p.y as f32),
                };
                surface.push_event(InputEvent::PointerScroll {
                    // winit reports the *gesture* — positive is up and right —
                    // and Denise reports the content offset a scroll view adds,
                    // so both axes flip. Only `delta_y` used to, which left the
                    // horizontal wheel and every two-finger sideways swipe
                    // going the wrong way against a vertical one that felt
                    // right.
                    delta_x: -dx,
                    delta_y: -dy,
                    position: cursor,
                });
            }

            WindowEvent::KeyboardInput { event, .. } => {
                surface.push_event(InputEvent::Key {
                    code: keymap::key_code(event.physical_key),
                    state: element_state(event.state),
                    repeat: event.repeat,
                    modifiers,
                });
                // Composed text only, and only on press. This is where `æøå` and
                // dead-key output arrive; the physical key above cannot carry them.
                if event.state.is_pressed()
                    && let Some(text) = event.text
                {
                    for ch in text.chars().filter(|c| !c.is_control()) {
                        surface.push_event(InputEvent::Text { ch });
                    }
                }
            }

            WindowEvent::Touch(touch) => {
                let position = Point::new(touch.location.x as i32, touch.location.y as i32);
                let id = touch.id;
                surface.push_event(match touch.phase {
                    TouchPhase::Started => InputEvent::TouchDown { id, position },
                    TouchPhase::Moved => InputEvent::TouchMoved { id, position },
                    TouchPhase::Ended => InputEvent::TouchUp {
                        id,
                        position,
                        cancelled: false,
                    },
                    TouchPhase::Cancelled => InputEvent::TouchUp {
                        id,
                        position,
                        cancelled: true,
                    },
                });
            }

            _ => {}
        }

        // Input outranks the cadence. An application that said "wake me in a
        // second, nothing is moving" still expects its button to light up when
        // pressed, so anything that arrived here is drawn at the next
        // opportunity rather than at the deadline.
        state.next_frame = Some(Instant::now());
    }

    fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
        if self.error.is_some() {
            return;
        }
        self.open_pending(event_loop);

        // Every window that has gone leaves the run when the last one does. The
        // main window normally ends it first — this is for the application that
        // closed it from the inside and left a settings form up.
        if self.windows.is_empty() {
            event_loop.exit();
            return;
        }

        // Sleep until the *earliest* frame is due rather than spinning. An idle UI
        // should cost nothing, which is the property that has to hold on the real
        // target. `None` from every window is the strongest form of that: nothing
        // anywhere is animating, so there is no deadline at all and the loop blocks
        // until something arrives. One animating window is enough to set the pace,
        // and the windows that are not animating still draw nothing when it does.
        let next = self
            .windows
            .values()
            .filter_map(|state| state.next_frame)
            .min();
        event_loop.set_control_flow(match next {
            Some(next) => ControlFlow::WaitUntil(next),
            None => ControlFlow::Wait,
        });
    }

    /// The run is over, whoever ended it.
    ///
    /// Most ways out come through this runner first — a close, `exit_requested`,
    /// an error — but not all of them. On macOS the application menu's Quit, the
    /// Dock's and a logout all send `terminate:`, which winit answers by calling
    /// this from `applicationWillTerminate:`, and AppKit ends the process as soon
    /// as it returns: no close request, no frame, and `run_app` never returns to
    /// drop anything. So this is where every application still open is told,
    /// and the windows are left standing for whatever drops them, if anything
    /// does.
    fn exiting(&mut self, _event_loop: &ActiveEventLoop) {
        let links: Vec<Link> = self.links().collect();
        for id in exiting_order(&links, self.main) {
            if let Some(state) = self.windows.get_mut(&id) {
                state.app.exiting();
            }
        }
    }
}

fn element_state(state: winit::event::ElementState) -> ElementState {
    match state {
        winit::event::ElementState::Pressed => ElementState::Down,
        winit::event::ElementState::Released => ElementState::Up,
    }
}

/// One window's place in the ownership graph: the window, who opened it, and how.
///
/// The two rules below are the whole of what ownership *means* to the loop, and
/// they are the part that breaks: a cascade that closes an owner before the window
/// it owns leaves a window pointing at nothing, and an owner re-enabled while a
/// second modal is still up is a window that ignores the dialog in front of it.
/// Both are awkward to reproduce by hand and trivial to state, so they are stated
/// here — over plain data, with no window in sight — and tested everywhere rather
/// than only where there is a display. The same split `keymap` makes.
type Link = (WindowId, Option<WindowId>, Modality);

/// The modal blocking `id`, if one is open over it.
///
/// Takes an iterator because the caller that matters is on the input path and has
/// nothing to gain from a collection.
fn blocker_of(links: impl Iterator<Item = Link>, id: WindowId) -> Option<WindowId> {
    links
        .into_iter()
        .find(|(_, owner, modality)| *owner == Some(id) && *modality == Modality::Modal)
        .map(|(blocker, _, _)| blocker)
}

/// `id` and everything opened from it, innermost first.
///
/// The order is the point: a window is always listed after everything it owns, so
/// closing down the list never orphans anything.
fn closing_order(links: &[Link], id: WindowId) -> Vec<WindowId> {
    let mut order = Vec::new();
    for (child, owner, _) in links {
        if *owner == Some(id) {
            order.extend(closing_order(links, *child));
        }
    }
    order.push(id);
    order
}

/// Every window, each after everything it owns, with the main window's tree last.
///
/// The order the end of the run tells applications in, which is `closing_order`'s
/// for the same reason plus one: a form that writes into state it shares with the
/// main window has written it before the main window saves.
fn exiting_order(links: &[Link], main: Option<WindowId>) -> Vec<WindowId> {
    let open = |id| links.iter().any(|(window, _, _)| *window == id);
    let mut order = Vec::with_capacity(links.len());
    for (window, owner, _) in links {
        // A window whose owner is not open starts a tree of its own. `close`
        // never leaves one behind, but the promise is "every window", and it
        // should not rest on that.
        let root = !owner.is_some_and(open);
        if root && Some(*window) != main {
            order.extend(closing_order(links, *window));
        }
    }
    if let Some(main) = main.filter(|main| open(*main)) {
        order.extend(closing_order(links, main));
    }
    order
}

/// Every plugged-in display's extent, in the desktop's physical pixels.
fn monitor_bounds(event_loop: &ActiveEventLoop) -> impl Iterator<Item = Rect> {
    event_loop.available_monitors().map(|monitor| {
        let origin = monitor.position();
        let size = monitor.size();
        Rect::new(origin.x, origin.y, size.width as i32, size.height as i32)
    })
}

/// Whether a remembered window position still lands on one of `monitors`.
///
/// A machine that reports no monitors at all — headless, and some remote
/// displays — is taken at its word rather than argued with: there is nothing
/// there to say the position is wrong, so it is honoured.
fn reachable(monitors: impl IntoIterator<Item = Rect>, at: Point) -> bool {
    let mut any = false;
    for screen in monitors {
        any = true;
        if screen.contains(at) {
            return true;
        }
    }
    !any
}

#[cfg(test)]
mod tests {
    use super::*;

    fn id(raw: u64) -> WindowId {
        WindowId::from(raw)
    }

    /// The example's shape: a main window, a modeless settings form, a modal over
    /// that form, and a second modal over the main window.
    fn tree() -> Vec<Link> {
        vec![
            (id(1), None, Modality::Independent),
            (id(2), Some(id(1)), Modality::Owned),
            (id(3), Some(id(2)), Modality::Modal),
            (id(4), Some(id(1)), Modality::Modal),
        ]
    }

    #[test]
    fn a_modal_blocks_its_own_owner_and_nobody_else() {
        assert_eq!(blocker_of(tree().into_iter(), id(1)), Some(id(4)));
        assert_eq!(blocker_of(tree().into_iter(), id(2)), Some(id(3)));
        // Nothing is open over the modals themselves.
        assert_eq!(blocker_of(tree().into_iter(), id(3)), None);
        assert_eq!(blocker_of(tree().into_iter(), id(4)), None);
    }

    #[test]
    fn a_modeless_form_blocks_nothing() {
        let links = [
            (id(1), None, Modality::Independent),
            (id(2), Some(id(1)), Modality::Owned),
        ];
        assert_eq!(blocker_of(links.iter().copied(), id(1)), None);
    }

    #[test]
    fn closing_a_form_closes_what_it_opened_first() {
        assert_eq!(closing_order(&tree(), id(2)), vec![id(3), id(2)]);
    }

    #[test]
    fn closing_the_main_window_closes_the_tree_owners_last() {
        let order = closing_order(&tree(), id(1));
        assert_eq!(order.len(), 4);
        assert_eq!(*order.last().expect("the opener comes last"), id(1));

        let at = |window| {
            order
                .iter()
                .position(|listed| *listed == window)
                .expect("every window in the tree is listed")
        };
        assert!(
            at(id(3)) < at(id(2)),
            "a modal closes before the form under it"
        );
        assert!(at(id(2)) < at(id(1)));
        assert!(at(id(4)) < at(id(1)));
    }

    /// A laptop with a second display above and to the left of it.
    fn desk() -> Vec<Rect> {
        vec![
            Rect::new(0, 0, 1512, 982),
            Rect::new(-1920, -400, 1920, 1080),
        ]
    }

    #[test]
    fn a_position_on_a_display_that_is_still_there_is_honoured() {
        assert!(reachable(desk(), Point::new(40, 40)));
        // The display left of the built-in one: negative, and still a place.
        assert!(reachable(desk(), Point::new(-1800, -200)));
    }

    #[test]
    fn a_position_on_a_display_that_has_been_unplugged_is_not() {
        assert!(!reachable(desk(), Point::new(-1800, 900)), "below it");
        assert!(!reachable(desk(), Point::new(2000, 40)), "right of both");
    }

    #[test]
    fn a_machine_that_reports_no_displays_is_taken_at_its_word() {
        assert!(reachable(Vec::new(), Point::new(4000, 4000)));
    }

    #[test]
    fn a_window_that_owns_nothing_closes_alone() {
        assert_eq!(closing_order(&tree(), id(4)), vec![id(4)]);
    }

    /// An independent window is nobody's child, so nothing takes it along.
    #[test]
    fn an_independent_window_is_not_cascaded() {
        let links = [
            (id(1), None, Modality::Independent),
            (id(2), None, Modality::Independent),
        ];
        assert_eq!(closing_order(&links, id(1)), vec![id(1)]);
    }

    /// The rule `close` consults before handing input back to an owner.
    #[test]
    fn the_owner_stays_blocked_until_the_last_modal_goes() {
        let mut links = vec![
            (id(1), None, Modality::Independent),
            (id(2), Some(id(1)), Modality::Modal),
            (id(3), Some(id(1)), Modality::Modal),
        ];
        links.retain(|(window, _, _)| *window != id(2));
        assert_eq!(blocker_of(links.iter().copied(), id(1)), Some(id(3)));
        links.retain(|(window, _, _)| *window != id(3));
        assert_eq!(blocker_of(links.iter().copied(), id(1)), None);
    }

    // `Runner::exiting` itself is not tested: calling it needs an
    // `ActiveEventLoop`, and every `WindowState` a real window and surface, which
    // a test runner without a display cannot make. What can break is who is told
    // and in which order, and that is plain data.

    /// Every window is told once, each before its owner, and the main window last.
    #[test]
    fn the_end_of_the_run_tells_every_window_owners_last() {
        let mut links = tree();
        links.push((id(5), None, Modality::Independent));
        links.push((id(6), Some(id(5)), Modality::Owned));
        let order = exiting_order(&links, Some(id(1)));

        assert_eq!(order.len(), links.len());
        let at = |window| {
            order
                .iter()
                .position(|listed| *listed == window)
                .expect("every open window is told")
        };
        for (window, owner, _) in &links {
            if let Some(owner) = owner {
                assert!(at(*window) < at(*owner), "{window:?} before {owner:?}");
            }
        }
        assert_eq!(order.last(), Some(&id(1)));
    }

    #[test]
    fn a_window_whose_owner_is_gone_is_still_told() {
        let links = [
            (id(1), None, Modality::Independent),
            (id(2), Some(id(9)), Modality::Owned),
        ];
        assert_eq!(exiting_order(&links, Some(id(1))), vec![id(2), id(1)]);
    }

    /// A main window that never opened is not told, and nothing else is missed.
    #[test]
    fn a_run_without_its_main_window_tells_what_is_open() {
        let links = [(id(2), None, Modality::Independent)];
        assert_eq!(exiting_order(&links, Some(id(1))), vec![id(2)]);
        assert_eq!(exiting_order(&links, None), vec![id(2)]);
    }
}