nadir-platform 0.4.0

OS layer of the Nadir engine: windows, the event loop, input devices, GL surfaces, audio output and paths.
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
// Copyright 2026 Joseph Anthony Abbott III
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! From AppKit's events to [`Event`]s.
//!
//! The window module reads each `NSEvent` and hands over what it found as an
//! [`Incoming`]. The helpers here, and [`Translator`], need no AppKit, so
//! their rules are tested here.

use nadir_core::{Key, MouseButton, UVec2, Vec2};
// The event types are used as `appkit::NSEventTypeKeyDown`, not imported by
// name: in a pattern, a bare name that is not upper case is linted as one
// that reads like a new variable.
use nadir_sys::macos::appkit::{
    self, NSEventModifierFlagCommand, NSEventModifierFlagControl, NSEventModifierFlagOption,
    NSEventModifierFlagShift, NX_DEVICELALTKEYMASK, NX_DEVICELCMDKEYMASK, NX_DEVICELCTLKEYMASK,
    NX_DEVICELSHIFTKEYMASK, NX_DEVICERALTKEYMASK, NX_DEVICERCMDKEYMASK, NX_DEVICERCTLKEYMASK,
    NX_DEVICERSHIFTKEYMASK,
};
use nadir_sys::macos::foundation::{CGFloat, NSInteger, NSPoint, NSUInteger};

use super::keymap;
use crate::Event;
use crate::text;

/// How many points a trackpad scrolls for one line of a mouse wheel. A
/// trackpad reports its scrolling in points, and a wheel in lines.
const POINTS_PER_LINE: CGFloat = 10.0;

/// Every device bit of the modifier flags.
const SIDE_BITS: NSUInteger = NX_DEVICELCTLKEYMASK
    | NX_DEVICELSHIFTKEYMASK
    | NX_DEVICERSHIFTKEYMASK
    | NX_DEVICELCMDKEYMASK
    | NX_DEVICERCMDKEYMASK
    | NX_DEVICELALTKEYMASK
    | NX_DEVICERALTKEYMASK
    | NX_DEVICERCTLKEYMASK;

/// An event, reduced to the kinds and fields we use.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Incoming {
    /// A key other than a modifier went down or up.
    Key { pressed: bool, code: u16 },
    /// A modifier key went down or up. `code` says which, and `flags` what
    /// is down now.
    FlagsChanged { code: u16, flags: NSUInteger },
    /// A button went down or up, with the pointer at `position`, in
    /// physical pixels.
    Button {
        pressed: bool,
        button: MouseButton,
        position: Vec2,
    },
    /// The pointer moved to `position`, in physical pixels.
    Motion { position: Vec2 },
    /// The wheel turned, or the trackpad scrolled, by this many lines.
    Wheel(Vec2),
}

/// Whether an event of this type is a button's going down or up.
pub(super) fn is_button_event(event_type: NSUInteger) -> bool {
    matches!(
        event_type,
        appkit::NSEventTypeLeftMouseDown
            | appkit::NSEventTypeLeftMouseUp
            | appkit::NSEventTypeRightMouseDown
            | appkit::NSEventTypeRightMouseUp
            | appkit::NSEventTypeOtherMouseDown
            | appkit::NSEventTypeOtherMouseUp
    )
}

/// Which button a mouse event is about, and whether it went down. `None`
/// for an event that is not a button's, or a button we have no name for.
/// `number` is the event's `buttonNumber`, which tells the other buttons
/// apart.
pub(super) fn mouse_button(
    event_type: NSUInteger,
    number: NSInteger,
) -> Option<(bool, MouseButton)> {
    let pressed = matches!(
        event_type,
        appkit::NSEventTypeLeftMouseDown
            | appkit::NSEventTypeRightMouseDown
            | appkit::NSEventTypeOtherMouseDown
    );
    let button = match event_type {
        appkit::NSEventTypeLeftMouseDown | appkit::NSEventTypeLeftMouseUp => MouseButton::Left,
        appkit::NSEventTypeRightMouseDown | appkit::NSEventTypeRightMouseUp => MouseButton::Right,
        appkit::NSEventTypeOtherMouseDown | appkit::NSEventTypeOtherMouseUp => match number {
            2 => MouseButton::Middle,
            3 => MouseButton::Back,
            4 => MouseButton::Forward,
            _ => return None,
        },
        _ => return None,
    };
    Some((pressed, button))
}

/// How far a scroll event scrolled, in lines: +y away from the user, and +x
/// to the right, whatever the user's choice of "natural" scrolling, which
/// `inverted` reports. `precise` marks a trackpad's deltas, which are in
/// points.
pub(super) fn wheel_lines(dx: CGFloat, dy: CGFloat, precise: bool, inverted: bool) -> Vec2 {
    let scale = if precise { 1.0 / POINTS_PER_LINE } else { 1.0 };
    // With natural scrolling, the content follows the fingers, and the
    // deltas are the other way round from the device.
    let sign = if inverted { -1.0 } else { 1.0 };
    // A positive horizontal delta scrolls toward the left.
    Vec2::new((-dx * sign * scale) as f32, (dy * sign * scale) as f32)
}

/// A position in the view, in points from its top-left (the view is
/// flipped), as physical pixels.
pub(super) fn to_pixels(point: NSPoint, scale: f32) -> Vec2 {
    Vec2::new(point.x as f32 * scale, point.y as f32 * scale)
}

/// Whether the modifier `key` is down, by the flags of a flags-changed
/// event, or `None` if `key` is not one of the eight modifiers.
fn modifier_down(key: Key, flags: NSUInteger) -> Option<bool> {
    let (side, either) = match key {
        Key::LeftShift => (NX_DEVICELSHIFTKEYMASK, NSEventModifierFlagShift),
        Key::RightShift => (NX_DEVICERSHIFTKEYMASK, NSEventModifierFlagShift),
        Key::LeftControl => (NX_DEVICELCTLKEYMASK, NSEventModifierFlagControl),
        Key::RightControl => (NX_DEVICERCTLKEYMASK, NSEventModifierFlagControl),
        Key::LeftAlt => (NX_DEVICELALTKEYMASK, NSEventModifierFlagOption),
        Key::RightAlt => (NX_DEVICERALTKEYMASK, NSEventModifierFlagOption),
        Key::LeftSuper => (NX_DEVICELCMDKEYMASK, NSEventModifierFlagCommand),
        Key::RightSuper => (NX_DEVICERCMDKEYMASK, NSEventModifierFlagCommand),
        _ => return None,
    };
    // Some keyboards, and some remote sessions, set no device bits. Then
    // the flag for either side is all there is.
    if flags & SIDE_BITS != 0 {
        Some(flags & side != 0)
    } else {
        Some(flags & either != 0)
    }
}

/// Turns events into [`Event`]s, and remembers what that takes: which keys
/// and buttons are down, where the pointer is, and the window's size and
/// scale factor.
pub(super) struct Translator {
    scale: f32,
    /// Whether the scale factor has been reported.
    scale_announced: bool,
    size: UVec2,
    focused: bool,
    pointer: Option<Vec2>,
    /// Which keys are down, by [`Key::usage`].
    keys_down: [bool; 256],
    /// Which buttons are down, in the order of [`MouseButton::ALL`].
    buttons_down: [bool; MouseButton::ALL.len()],
}

impl Translator {
    /// A translator for a window of `size`, at the scale factor `scale`,
    /// that has seen no events yet.
    pub(super) fn new(size: UVec2, scale: f32) -> Self {
        Self {
            scale,
            scale_announced: false,
            size,
            focused: false,
            pointer: None,
            keys_down: [false; 256],
            buttons_down: [false; MouseButton::ALL.len()],
        }
    }

    /// The size of the inside of the window, in pixels.
    pub(super) fn size(&self) -> UVec2 {
        self.size
    }

    /// The scale factor of the window.
    pub(super) fn scale(&self) -> f32 {
        self.scale
    }

    /// Call this at the start of every pump, before the events that came
    /// since the last. The first time, it reports the scale factor, which
    /// therefore comes before every other event.
    pub(super) fn begin_pump(&mut self, out: &mut Vec<Event>) {
        if !self.scale_announced {
            self.scale_announced = true;
            out.push(Event::ScaleFactorChanged(self.scale));
        }
    }

    /// The window is at a new scale factor now. It is reported at once if
    /// it changed, unless the first pump has not come yet: that one reports
    /// the latest.
    pub(super) fn set_scale(&mut self, scale: f32, out: &mut Vec<Event>) {
        if scale == self.scale {
            return;
        }
        self.scale = scale;
        if self.scale_announced {
            out.push(Event::ScaleFactorChanged(scale));
        }
    }

    /// The user asked to close the window, or to quit.
    pub(super) fn close(&mut self, out: &mut Vec<Event>) {
        out.push(Event::CloseRequested);
    }

    /// Appends the events that `incoming` amounts to, which may be none.
    pub(super) fn handle(&mut self, incoming: Incoming, out: &mut Vec<Event>) {
        match incoming {
            Incoming::Key { pressed, code } => {
                if let Some(key) = keymap::from_key_code(code) {
                    self.key(key, pressed, out);
                }
            }
            Incoming::FlagsChanged { code, flags } => self.flags_changed(code, flags, out),
            Incoming::Button {
                pressed,
                button,
                position,
            } => {
                self.move_pointer(position, out);
                self.button(pressed, button, out);
            }
            Incoming::Motion { position } => self.move_pointer(position, out),
            Incoming::Wheel(lines) => {
                if lines != Vec2::ZERO {
                    out.push(Event::MouseWheel(lines));
                }
            }
        }
    }

    fn key(&mut self, key: Key, pressed: bool, out: &mut Vec<Event>) {
        let down = &mut self.keys_down[usize::from(key.usage())];
        // A release of a key we never saw go down, which happens when the
        // key was pressed while another window had the focus, is not
        // reported: every release follows a press.
        if !pressed && !*down {
            return;
        }
        // A held key repeats as presses only.
        let repeat = pressed && *down;
        *down = pressed;
        out.push(Event::Key {
            key,
            pressed,
            repeat,
        });
    }

    fn flags_changed(&mut self, code: u16, flags: NSUInteger, out: &mut Vec<Event>) {
        let Some(key) = keymap::from_key_code(code) else {
            return;
        };
        if key == Key::CapsLock {
            // Caps Lock reports a change of its state for each press, and
            // nothing when it comes up: a press and a release, at once.
            self.key(key, true, out);
            self.key(key, false, out);
            return;
        }
        let Some(pressed) = modifier_down(key, flags) else {
            return;
        };
        if pressed != self.keys_down[usize::from(key.usage())] {
            self.key(key, pressed, out);
        }
    }

    fn button(&mut self, pressed: bool, button: MouseButton, out: &mut Vec<Event>) {
        let down = &mut self.buttons_down[button as usize];
        if pressed == *down {
            // A second press without a release, or a release with no press:
            // see `key`.
            return;
        }
        *down = pressed;
        out.push(Event::MouseButton { button, pressed });
    }

    fn move_pointer(&mut self, position: Vec2, out: &mut Vec<Event>) {
        if self.pointer == Some(position) {
            return;
        }
        self.pointer = Some(position);
        out.push(Event::MouseMoved(position));
    }

    /// Appends what a key press typed: `characters`, the press's
    /// `-characters`, with `flags`, its `-modifierFlags`. Apple types the
    /// keys that type nothing, the arrows and the function keys among them,
    /// as characters of its own, which are left out; and nothing is typed
    /// with ⌘, or with Control without Option. The press's own flags say
    /// what is held, also a ⌘ that went down before the window had the
    /// focus.
    pub(super) fn text(&mut self, characters: &str, flags: NSUInteger, out: &mut Vec<Event>) {
        let held = |flag: NSUInteger| flags & flag != 0;
        let shortcut = text::shortcut(
            held(NSEventModifierFlagControl),
            held(NSEventModifierFlagOption),
            held(NSEventModifierFlagCommand),
        );
        let typed = characters
            .chars()
            .filter(|&c| !text::is_apple_function_key(c));
        text::push_text(typed, shortcut, out);
    }

    /// The window got the keyboard focus, or lost it.
    pub(super) fn focus(&mut self, gained: bool, out: &mut Vec<Event>) {
        if gained != self.focused {
            self.focused = gained;
            out.push(Event::Focused(gained));
        }
        // After the news, so that a reader can tell these releases from the
        // ones the user made.
        if !gained {
            self.release_everything(out);
        }
    }

    /// Reports a release for every key and button that is down. Without
    /// the focus we will not see them go up.
    fn release_everything(&mut self, out: &mut Vec<Event>) {
        for &key in Key::ALL {
            let down = &mut self.keys_down[usize::from(key.usage())];
            if *down {
                *down = false;
                out.push(Event::Key {
                    key,
                    pressed: false,
                    repeat: false,
                });
            }
        }
        for &button in MouseButton::ALL {
            let down = &mut self.buttons_down[button as usize];
            if *down {
                *down = false;
                out.push(Event::MouseButton {
                    button,
                    pressed: false,
                });
            }
        }
    }

    /// The inside of the window has this size now, in physical pixels.
    pub(super) fn resize(&mut self, size: UVec2, out: &mut Vec<Event>) {
        if size.x == 0 || size.y == 0 || size == self.size {
            return;
        }
        self.size = size;
        out.push(Event::Resized(size));
    }
}

#[cfg(test)]
mod tests {
    use nadir_sys::macos::appkit::{
        NSEventModifierFlagCapsLock, NSEventTypeKeyDown, NSEventTypeLeftMouseDown,
        NSEventTypeLeftMouseUp, NSEventTypeOtherMouseDown, NSEventTypeOtherMouseUp,
        NSEventTypeRightMouseDown, NSEventTypeRightMouseUp,
    };
    use nadir_sys::macos::hitoolbox::{
        kVK_ANSI_A, kVK_ANSI_W, kVK_CapsLock, kVK_Command, kVK_RightShift, kVK_Shift,
    };

    use super::*;

    /// A key with a code and no [`Key`]. `HIToolbox/Events.h`: `kVK_VolumeUp
    /// = 0x48,`
    const VOLUME_UP: u16 = 0x48;

    fn translator() -> Translator {
        Translator::new(UVec2::new(1280, 720), 2.0)
    }

    /// Feeds the events to a translator and returns what comes out.
    fn run(translator: &mut Translator, incoming: &[Incoming]) -> Vec<Event> {
        let mut out = Vec::new();
        for &event in incoming {
            translator.handle(event, &mut out);
        }
        out
    }

    fn press(code: u16) -> Incoming {
        Incoming::Key {
            pressed: true,
            code,
        }
    }

    fn release(code: u16) -> Incoming {
        Incoming::Key {
            pressed: false,
            code,
        }
    }

    fn flags(code: u16, flags: NSUInteger) -> Incoming {
        Incoming::FlagsChanged { code, flags }
    }

    fn key_event(key: Key, pressed: bool, repeat: bool) -> Event {
        Event::Key {
            key,
            pressed,
            repeat,
        }
    }

    // -- helpers ------------------------------------------------------------

    #[test]
    fn button_events_are_told_from_the_others() {
        for event_type in [
            NSEventTypeLeftMouseDown,
            NSEventTypeLeftMouseUp,
            NSEventTypeRightMouseDown,
            NSEventTypeRightMouseUp,
            NSEventTypeOtherMouseDown,
            NSEventTypeOtherMouseUp,
        ] {
            assert!(is_button_event(event_type), "{event_type}");
            // Every button event names a button for some number.
            assert!((0..5).any(|number| mouse_button(event_type, number).is_some()));
        }
        // Mouse moved, a drag, a key, a scroll.
        for event_type in [5, 6, 10, 22, 27] {
            assert!(!is_button_event(event_type), "{event_type}");
        }
    }

    #[test]
    fn mouse_events_name_their_buttons() {
        assert_eq!(
            mouse_button(NSEventTypeLeftMouseDown, 0),
            Some((true, MouseButton::Left))
        );
        assert_eq!(
            mouse_button(NSEventTypeLeftMouseUp, 0),
            Some((false, MouseButton::Left))
        );
        assert_eq!(
            mouse_button(NSEventTypeRightMouseDown, 1),
            Some((true, MouseButton::Right))
        );
        assert_eq!(
            mouse_button(NSEventTypeRightMouseUp, 1),
            Some((false, MouseButton::Right))
        );
        let other = |pressed: bool, number| {
            let event_type = if pressed {
                NSEventTypeOtherMouseDown
            } else {
                NSEventTypeOtherMouseUp
            };
            mouse_button(event_type, number)
        };
        assert_eq!(other(true, 2), Some((true, MouseButton::Middle)));
        assert_eq!(other(true, 3), Some((true, MouseButton::Back)));
        assert_eq!(other(false, 4), Some((false, MouseButton::Forward)));
        assert_eq!(other(true, 5), None);
        assert_eq!(mouse_button(NSEventTypeKeyDown, 0), None);
    }

    #[test]
    fn a_wheel_scrolls_in_lines_and_a_trackpad_in_points() {
        // A wheel turned away from the user, without natural scrolling.
        assert_eq!(wheel_lines(0.0, 1.0, false, false), Vec2::new(0.0, 1.0));
        // A trackpad, 20 points to the left.
        assert_eq!(wheel_lines(20.0, 0.0, true, false), Vec2::new(-2.0, 0.0));
    }

    #[test]
    fn natural_scrolling_does_not_change_the_direction_reported() {
        assert_eq!(wheel_lines(0.0, -1.0, false, true), Vec2::new(0.0, 1.0));
        assert_eq!(wheel_lines(-20.0, 30.0, true, true), Vec2::new(-2.0, -3.0));
    }

    #[test]
    fn a_point_is_scaled_to_pixels() {
        let point = NSPoint { x: 10.5, y: 20.0 };
        assert_eq!(to_pixels(point, 2.0), Vec2::new(21.0, 40.0));
        assert_eq!(to_pixels(point, 1.0), Vec2::new(10.5, 20.0));
    }

    #[test]
    fn a_modifier_is_down_by_its_own_side_bit() {
        let left_shift = NSEventModifierFlagShift | NX_DEVICELSHIFTKEYMASK;
        assert_eq!(modifier_down(Key::LeftShift, left_shift), Some(true));
        assert_eq!(modifier_down(Key::RightShift, left_shift), Some(false));
        let right_command = NSEventModifierFlagCommand | NX_DEVICERCMDKEYMASK;
        assert_eq!(modifier_down(Key::RightSuper, right_command), Some(true));
        assert_eq!(modifier_down(Key::LeftSuper, right_command), Some(false));
        assert_eq!(
            modifier_down(Key::RightControl, NX_DEVICERCTLKEYMASK),
            Some(true)
        );
        assert_eq!(
            modifier_down(Key::LeftAlt, NX_DEVICELALTKEYMASK),
            Some(true)
        );
        assert_eq!(
            modifier_down(Key::RightAlt, NX_DEVICELALTKEYMASK),
            Some(false)
        );
        assert_eq!(modifier_down(Key::A, left_shift), None);
    }

    #[test]
    fn without_side_bits_the_flag_for_either_side_decides() {
        assert_eq!(
            modifier_down(Key::LeftControl, NSEventModifierFlagControl),
            Some(true)
        );
        assert_eq!(
            modifier_down(Key::RightControl, NSEventModifierFlagControl),
            Some(true)
        );
        assert_eq!(modifier_down(Key::LeftAlt, 0), Some(false));
    }

    // -- translating --------------------------------------------------------

    #[test]
    fn the_scale_factor_is_reported_once_before_anything_else() {
        let mut translator = translator();
        let mut out = Vec::new();
        translator.begin_pump(&mut out);
        translator.handle(press(kVK_ANSI_A), &mut out);
        translator.begin_pump(&mut out);
        assert_eq!(
            out,
            [
                Event::ScaleFactorChanged(2.0),
                key_event(Key::A, true, false)
            ]
        );
    }

    #[test]
    fn a_new_scale_is_reported_when_it_changes() {
        let mut translator = translator();
        let mut out = Vec::new();
        translator.set_scale(1.0, &mut out);
        assert!(out.is_empty());
        translator.begin_pump(&mut out);
        translator.set_scale(1.0, &mut out);
        translator.set_scale(2.0, &mut out);
        assert_eq!(
            out,
            [
                Event::ScaleFactorChanged(1.0),
                Event::ScaleFactorChanged(2.0)
            ]
        );
    }

    #[test]
    fn a_key_goes_down_repeats_and_comes_up() {
        let mut translator = translator();
        let out = run(
            &mut translator,
            &[press(kVK_ANSI_W), press(kVK_ANSI_W), release(kVK_ANSI_W)],
        );
        assert_eq!(
            out,
            [
                key_event(Key::W, true, false),
                key_event(Key::W, true, true),
                key_event(Key::W, false, false),
            ]
        );
    }

    #[test]
    fn a_release_without_a_press_and_a_code_with_no_key_are_ignored() {
        let mut translator = translator();
        let out = run(&mut translator, &[release(kVK_ANSI_A), press(VOLUME_UP)]);
        assert!(out.is_empty(), "{out:?}");
    }

    #[test]
    fn modifiers_go_down_and_up_by_their_flags() {
        let mut translator = translator();
        let left = NSEventModifierFlagShift | NX_DEVICELSHIFTKEYMASK;
        let both = left | NX_DEVICERSHIFTKEYMASK;
        let right = NSEventModifierFlagShift | NX_DEVICERSHIFTKEYMASK;
        let out = run(
            &mut translator,
            &[
                flags(kVK_Shift, left),
                flags(kVK_RightShift, both),
                flags(kVK_Shift, right),
                flags(kVK_RightShift, 0),
            ],
        );
        assert_eq!(
            out,
            [
                key_event(Key::LeftShift, true, false),
                key_event(Key::RightShift, true, false),
                key_event(Key::LeftShift, false, false),
                key_event(Key::RightShift, false, false),
            ]
        );
    }

    #[test]
    fn a_flags_change_that_changes_nothing_reports_nothing() {
        let mut translator = translator();
        let command = NSEventModifierFlagCommand | NX_DEVICELCMDKEYMASK;
        let out = run(
            &mut translator,
            &[flags(kVK_Command, command), flags(kVK_Command, command)],
        );
        assert_eq!(out, [key_event(Key::LeftSuper, true, false)]);
        // A release of a modifier we never saw go down is not reported.
        assert!(run(&mut translator, &[flags(kVK_Shift, 0)]).is_empty());
    }

    #[test]
    fn caps_lock_is_a_tap_on_each_change_of_its_state() {
        let mut translator = translator();
        let out = run(
            &mut translator,
            &[
                flags(kVK_CapsLock, NSEventModifierFlagCapsLock),
                flags(kVK_CapsLock, 0),
            ],
        );
        let tap = [
            key_event(Key::CapsLock, true, false),
            key_event(Key::CapsLock, false, false),
        ];
        assert_eq!(out, [tap, tap].concat());
    }

    #[test]
    fn a_button_goes_down_and_up_where_the_pointer_is() {
        let mut translator = translator();
        let position = Vec2::new(10.0, 20.0);
        let button = |pressed| Incoming::Button {
            pressed,
            button: MouseButton::Left,
            position,
        };
        let out = run(
            &mut translator,
            &[button(true), button(false), button(false)],
        );
        assert_eq!(
            out,
            [
                Event::MouseMoved(position),
                Event::MouseButton {
                    button: MouseButton::Left,
                    pressed: true
                },
                Event::MouseButton {
                    button: MouseButton::Left,
                    pressed: false
                },
            ]
        );
    }

    #[test]
    fn motion_is_reported_when_the_position_changes() {
        let mut translator = translator();
        let motion = |x, y| Incoming::Motion {
            position: Vec2::new(x, y),
        };
        let out = run(
            &mut translator,
            &[motion(1.0, 2.0), motion(1.0, 2.0), motion(3.5, 2.0)],
        );
        assert_eq!(
            out,
            [
                Event::MouseMoved(Vec2::new(1.0, 2.0)),
                Event::MouseMoved(Vec2::new(3.5, 2.0)),
            ]
        );
    }

    #[test]
    fn a_scroll_of_nothing_is_not_reported() {
        let mut translator = translator();
        let out = run(
            &mut translator,
            &[
                Incoming::Wheel(Vec2::ZERO),
                Incoming::Wheel(Vec2::new(0.0, -1.0)),
            ],
        );
        assert_eq!(out, [Event::MouseWheel(Vec2::new(0.0, -1.0))]);
    }

    #[test]
    fn losing_the_focus_releases_what_is_held() {
        let mut translator = translator();
        let mut out = Vec::new();
        translator.focus(true, &mut out);
        translator.handle(press(kVK_ANSI_A), &mut out);
        translator.handle(
            flags(kVK_Shift, NSEventModifierFlagShift | NX_DEVICELSHIFTKEYMASK),
            &mut out,
        );
        translator.handle(
            Incoming::Button {
                pressed: true,
                button: MouseButton::Right,
                position: Vec2::ZERO,
            },
            &mut out,
        );
        out.clear();
        translator.focus(false, &mut out);
        assert_eq!(
            out,
            [
                Event::Focused(false),
                key_event(Key::A, false, false),
                key_event(Key::LeftShift, false, false),
                Event::MouseButton {
                    button: MouseButton::Right,
                    pressed: false
                },
            ]
        );
        out.clear();
        translator.focus(false, &mut out);
        assert!(out.is_empty());
    }

    #[test]
    fn a_new_size_is_reported_once_and_close_asks_to_close() {
        let mut translator = translator();
        let mut out = Vec::new();
        translator.resize(UVec2::new(1280, 720), &mut out);
        translator.resize(UVec2::new(1600, 900), &mut out);
        translator.resize(UVec2::new(1600, 900), &mut out);
        translator.resize(UVec2::new(0, 900), &mut out);
        translator.close(&mut out);
        assert_eq!(
            out,
            [Event::Resized(UVec2::new(1600, 900)), Event::CloseRequested]
        );
        assert_eq!(translator.size(), UVec2::new(1600, 900));
    }

    // -- typed text ---------------------------------------------------------

    /// What a key press typed, as the pump reports it after the press,
    /// with no modifiers.
    fn typed(translator: &mut Translator, characters: &str) -> Vec<Event> {
        typed_with(translator, characters, 0)
    }

    fn typed_with(translator: &mut Translator, characters: &str, flags: NSUInteger) -> Vec<Event> {
        let mut out = Vec::new();
        translator.text(characters, flags, &mut out);
        out
    }

    #[test]
    fn a_key_press_types_its_characters() {
        let mut translator = translator();
        assert_eq!(typed(&mut translator, "a"), [Event::Text('a')]);
        // Option types the layout's other characters.
        assert_eq!(typed(&mut translator, "å"), [Event::Text('å')]);
        assert_eq!(
            typed(&mut translator, "é😀"),
            [Event::Text('é'), Event::Text('😀')]
        );
        // A dead key alone types nothing.
        assert_eq!(typed(&mut translator, ""), []);
    }

    #[test]
    fn the_keys_that_type_nothing_and_controls_are_left_out() {
        let mut translator = translator();
        // `NSUpArrowFunctionKey`, `NSF1FunctionKey`; Return, Tab, Delete
        // (backward), Escape.
        assert_eq!(typed(&mut translator, "\u{F700}\u{F704}"), []);
        assert_eq!(typed(&mut translator, "\r\t\u{7f}\u{1b}"), []);
        // The Apple logo is typed.
        assert_eq!(
            typed(&mut translator, "\u{F8FF}"),
            [Event::Text('\u{F8FF}')]
        );
    }

    #[test]
    fn nothing_is_typed_with_command_or_with_control_without_option() {
        let mut translator = translator();
        let command = NSEventModifierFlagCommand | NX_DEVICELCMDKEYMASK;
        // ⌘A gives "a", also with a ⌘ that went down before the focus came,
        // which no flags change reported.
        assert_eq!(typed_with(&mut translator, "a", command), []);
        let control = NSEventModifierFlagControl | NX_DEVICELCTLKEYMASK;
        // Control+1 gives "1".
        assert_eq!(typed_with(&mut translator, "1", control), []);
        // Option, and Shift, type.
        let option = NSEventModifierFlagOption | NX_DEVICELALTKEYMASK;
        assert_eq!(typed_with(&mut translator, "å", option), [Event::Text('å')]);
        let shift = NSEventModifierFlagShift | NX_DEVICELSHIFTKEYMASK;
        assert_eq!(typed_with(&mut translator, "A", shift), [Event::Text('A')]);
        assert_eq!(
            typed_with(&mut translator, "x", control | option),
            [Event::Text('x')]
        );
        assert_eq!(typed_with(&mut translator, "x", command | option), []);
    }
}