unlit3d 0.1.0-dev.3

The high-level WebGPU rendering API over unlit_wgpu and unlit_ecs: ECS components, frame sources, input, UI and winit presentation.
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
1136
//! Translating the crate's portable input events into egui's.
//!
//! [`crate::input`] keeps input free of any windowing library or UI toolkit;
//! this module is the one place the two meet, so the rest of the UI code never
//! handles an egui event directly and the crate's events stay usable by game
//! logic on their own.
//!
//! # Units
//!
//! The crate reports pointer positions in physical pixels from the window's
//! top-left; egui works in logical points. The conversion therefore takes the
//! density and divides, and every position it produces is already in the space
//! egui expects. A consumer that feeds egui must not scale again.
//!
//! # Which event feeds egui's pointer
//!
//! One physical action can arrive in several categories, because the crate
//! reports it once per level of detail. egui's pointer is fed from the
//! **most detailed** source that exists for the device, and the coarser
//! duplicate is dropped:
//!
//! | device | events | what egui's pointer is fed from |
//! |---|---|---|
//! | mouse | [`MouseEvent`], [`PointerEvent`] | [`MouseEvent`], which names the button and the wheel unit |
//! | touch | [`TouchEvent`], [`PointerEvent`] | [`TouchEvent`], which names the touch and reports the lift ordering |
//! | pen and other | [`PointerEvent`] | [`PointerEvent`], there being nothing more detailed |
//!
//! # Touches
//!
//! egui's own documentation asks an integration to report a touch point
//! *both* as a touch and as the pointer: a touch is what a widget watching for
//! a finger wants, while the pointer events are what makes tapping a button
//! work at all. One touch therefore becomes several events, which is why the
//! conversion returns a list rather than one event.

use egui::TouchPhase as EguiTouchPhase;
use egui::{Event as EguiEvent, MouseWheelUnit, Pos2, TouchDeviceId, TouchId};
use egui::{ImeEvent as EguiImeEvent, PointerButton as EguiPointerButton};

use crate::input::{
    ImeEvent, ImeKind, InputEvent, Key, KeyEvent, Modifiers, MouseButton, MouseEvent,
    PointerAction, PointerEvent, PointerKind, TouchEvent, TouchPhase, WheelUnit,
};

/// Translate one crate event into the egui events it stands for.
///
/// Returns an empty list for an event egui has no counterpart for, so a caller
/// can translate a whole frame without matching on the kind first. A pointer
/// event that describes an action another event of the same frame already
/// describes in more detail is likewise dropped — see the module docs for which
/// source feeds egui's pointer per device. `pixels_per_point` converts the
/// crate's physical pixels into the points egui lays out in; it must be
/// positive.
pub fn to_egui_event(event: &InputEvent, pixels_per_point: f32) -> Vec<EguiEvent> {
    assert!(
        pixels_per_point > 0.0,
        "a pixel density must be positive to convert physical pixels into points"
    );
    match event {
        InputEvent::Key(event) => key_events(*event),
        InputEvent::Mouse(event) => mouse_events(event, pixels_per_point),
        InputEvent::Pointer(event) => pointer_events(event, pixels_per_point),
        InputEvent::Touch(event) => touch_events(*event, pixels_per_point),
        InputEvent::Text(text) => vec![EguiEvent::Text(text.0.clone())],
        InputEvent::Ime(event) => ime_events(event),
        InputEvent::ModifiersChanged(modifiers) => {
            vec![EguiEvent::ModifiersChanged(to_modifiers(*modifiers))]
        }
        InputEvent::FocusChanged(focused) => vec![EguiEvent::WindowFocused(*focused)],
        // egui learns the screen's size from the frame's target and its
        // density from the viewport, not from events, so these carry nothing
        // it needs.
        InputEvent::Resized { .. } | InputEvent::ScaleFactorChanged { .. } => Vec::new(),
    }
}

/// Translate a whole frame's events into `out`, appending them.
///
/// The order events arrive in is preserved: egui's own input handling depends
/// on a press coming before the release that follows it. The caller clears
/// `out` first and keeps it across frames, so a run of frames reuses one
/// allocation for the events egui is handed.
pub fn to_egui_events_into<'a>(
    events: impl IntoIterator<Item = &'a InputEvent>,
    pixels_per_point: f32,
    out: &mut Vec<EguiEvent>,
) {
    out.extend(
        events
            .into_iter()
            .flat_map(|event| to_egui_event(event, pixels_per_point)),
    );
}

/// A key event. The crate carries the text a key produced as a separate
/// [`TextEvent`](crate::input::TextEvent), so a key press becomes one egui event here and the text
/// arrives on its own.
fn key_events(event: KeyEvent) -> Vec<EguiEvent> {
    // A key only the platform knows has no name in egui's closed key space, so
    // there is nothing to forward. Dropping the event is better than picking a
    // key egui does recognize, which would report a press the user never made.
    let Some(key) = to_key(event.key) else {
        return Vec::new();
    };
    // `egui` wants the logical key, which its shortcuts are written against,
    // and the physical key, which a game control addresses. The crate's `Key`
    // is a physical key, so it fills both: a key the crate names has the same
    // identity either way, and the crate does not track the layout-dependent
    // logical key at all.
    vec![EguiEvent::Key {
        key,
        physical_key: Some(key),
        pressed: event.pressed,
        repeat: event.repeat,
        modifiers: to_modifiers(event.modifiers),
    }]
}

/// A mouse event.
///
/// A mouse feeds egui's pointer through its own events rather than through the
/// device-agnostic [`PointerEvent`] beside them: a [`MouseEvent::Button`] names
/// the button egui needs, and a [`MouseEvent::Wheel`] names the unit, neither
/// of which a pointer event carries.
fn mouse_events(event: &MouseEvent, pixels_per_point: f32) -> Vec<EguiEvent> {
    match event {
        MouseEvent::Moved { position } => {
            vec![EguiEvent::PointerMoved(to_pos(*position, pixels_per_point))]
        }
        MouseEvent::Button {
            position,
            button,
            pressed,
            modifiers,
        } => {
            // egui names five buttons and nothing else, so a button beyond
            // them cannot be reported. An empty list says so rather than
            // mapping it onto one egui does know.
            let Some(button) = to_pointer_button(*button) else {
                return Vec::new();
            };
            vec![EguiEvent::PointerButton {
                pos: to_pos(*position, pixels_per_point),
                button,
                pressed: *pressed,
                modifiers: to_modifiers(*modifiers),
            }]
        }
        MouseEvent::Left => vec![EguiEvent::PointerGone],
        MouseEvent::Wheel {
            delta,
            unit,
            phase,
            modifiers,
        } => vec![EguiEvent::MouseWheel {
            unit: to_wheel_unit(*unit),
            // egui's wheel delta is in points whichever unit it is measured
            // in, so a pixel delta is scaled like a position.
            delta: match unit {
                WheelUnit::Pixel => egui::Vec2::new(delta[0], delta[1]) / pixels_per_point,
                WheelUnit::Line | WheelUnit::Page => egui::Vec2::new(delta[0], delta[1]),
            },
            phase: to_touch_phase(*phase),
            modifiers: to_modifiers(*modifiers),
        }],
    }
}

/// A pointer event, in egui's point space.
///
/// A gesture has no point counterpart at any other level, so it always reaches
/// egui. The point actions do not: only a device egui hears about through this
/// level alone — a pen, or a device the platform did not classify — reaches
/// egui's pointer this way, because a mouse and a touch produce a
/// [`MouseEvent`] or a [`TouchEvent`] carrying the same point action in more
/// detail and egui is fed that instead. Forwarding the pointer too would report
/// one physical move twice.
fn pointer_events(event: &PointerEvent, pixels_per_point: f32) -> Vec<EguiEvent> {
    match event.action {
        PointerAction::Zoom(delta) => return vec![EguiEvent::Zoom(delta)],
        PointerAction::Rotate(delta) => return vec![EguiEvent::Rotate(delta)],
        PointerAction::Moved
        | PointerAction::Pressed
        | PointerAction::Released { .. }
        | PointerAction::Left => {}
    }
    let Some(position) = pointer_position(event, pixels_per_point) else {
        return Vec::new();
    };
    match event.action {
        PointerAction::Moved => vec![EguiEvent::PointerMoved(position)],
        PointerAction::Pressed => vec![EguiEvent::PointerButton {
            pos: position,
            button: EguiPointerButton::Primary,
            pressed: true,
            modifiers: to_modifiers(event.modifiers),
        }],
        PointerAction::Released { .. } => vec![
            EguiEvent::PointerButton {
                pos: position,
                button: EguiPointerButton::Primary,
                pressed: false,
                modifiers: to_modifiers(event.modifiers),
            },
            // A pen that lifts or is cancelled is not hovering any more, so it
            // leaves the screen; the mouse's own `Left` covers the mouse.
            EguiEvent::PointerGone,
        ],
        PointerAction::Left => vec![EguiEvent::PointerGone],
        PointerAction::Zoom(_) | PointerAction::Rotate(_) => unreachable!("handled above"),
    }
}

/// The position a pointer event's point action is reported at, or `None` when
/// the event must not reach egui's pointer at all.
///
/// A mouse, a touch and a trackpad are that case: each moves the pointer
/// through the same stream that already produces a [`MouseEvent`] or a
/// [`TouchEvent`], so only a device with no such event — a pen, or one the
/// platform did not classify — reaches egui here. The position falls back to
/// the origin for an action that carries none, which egui treats as a pointer
/// at the top-left corner rather than as no pointer at all.
fn pointer_position(event: &PointerEvent, pixels_per_point: f32) -> Option<Pos2> {
    match event.kind {
        PointerKind::Mouse | PointerKind::Touch | PointerKind::Trackpad => return None,
        PointerKind::Pen | PointerKind::Other => {}
    }
    Some(
        event
            .position
            .map_or(Pos2::ZERO, |position| to_pos(position, pixels_per_point)),
    )
}

/// A touch, reported as egui asks: the touch itself plus the pointer events
/// that make a widget respond to it.
fn touch_events(event: TouchEvent, pixels_per_point: f32) -> Vec<EguiEvent> {
    let pos = to_pos(event.position, pixels_per_point);
    let mut events = vec![EguiEvent::Touch {
        // The crate numbers touches per device without naming the device, so
        // every touch belongs to one synthetic device.
        device_id: TouchDeviceId(0),
        id: TouchId(event.id),
        phase: to_touch_phase(event.phase),
        pos,
        force: event.force,
    }];

    match event.phase {
        // A finger down is the pointer arriving and pressing its primary
        // button, which is what a tap on a widget is.
        TouchPhase::Started => {
            events.push(EguiEvent::PointerMoved(pos));
            events.push(EguiEvent::PointerButton {
                pos,
                button: EguiPointerButton::Primary,
                pressed: true,
                modifiers: Modifiers::default().into(),
            });
        }
        TouchPhase::Moved => events.push(EguiEvent::PointerMoved(pos)),
        // Lifting ends the touch, and egui wants the release before the
        // pointer leaves the screen.
        TouchPhase::Ended | TouchPhase::Cancelled => {
            events.push(EguiEvent::PointerButton {
                pos,
                button: EguiPointerButton::Primary,
                pressed: false,
                modifiers: Modifiers::default().into(),
            });
            // Nothing follows the last finger, so the pointer is gone. A
            // cancellation is not a hover, so it leaves the screen too.
            events.push(EguiEvent::PointerGone);
        }
    }
    events
}

/// An input-method event.
///
/// The two sides measure text differently: the crate counts bytes because a
/// windowing library reports byte offsets, while egui counts characters. A
/// preedit's active range is therefore re-measured in characters here, and a
/// delete request is converted the other way.
fn ime_events(event: &ImeEvent) -> Vec<EguiEvent> {
    let inner = match &event.kind {
        ImeKind::Preedit { text, active_range } => EguiImeEvent::Preedit {
            text: text.clone(),
            active_range_chars: active_range
                .clone()
                .map(|range| bytes_to_chars(text, range)),
        },
        ImeKind::Commit(text) => EguiImeEvent::Commit(text.clone()),
        ImeKind::DeleteSurrounding { before, after } => {
            // Without the surrounding text there is no way to know how many
            // characters a byte count covers, so the counts are passed through
            // as the crate stated them. A consumer that produced them from
            // characters (which the crate's own docs allow) is exact.
            EguiImeEvent::DeleteSurrounding {
                before_chars: *before,
                after_chars: *after,
            }
        }
        // egui deprecated both variants: it no longer tracks whether an input
        // method is on, so neither has a counterpart to forward.
        ImeKind::Enabled | ImeKind::Disabled => return Vec::new(),
    };
    vec![EguiEvent::Ime(inner)]
}

/// Re-express a byte range within `text` as the character range covering the
/// same span.
///
/// A byte offset that lands inside a character is not a boundary the text has,
/// so it is rounded to the nearest boundary that exists rather than panicking.
fn bytes_to_chars(text: &str, range: core::ops::Range<usize>) -> core::ops::Range<usize> {
    let start = text
        .char_indices()
        .position(|(offset, _)| offset >= range.start)
        .unwrap_or_else(|| text.chars().count());
    let end = text
        .char_indices()
        .position(|(offset, _)| offset >= range.end)
        .unwrap_or_else(|| text.chars().count());
    start..end
}

/// A position in physical pixels as egui's logical point.
fn to_pos(position: [f32; 2], pixels_per_point: f32) -> Pos2 {
    Pos2::new(
        position[0] / pixels_per_point,
        position[1] / pixels_per_point,
    )
}

/// The crate's modifier set as egui's, field for field.
fn to_modifiers(modifiers: Modifiers) -> egui::Modifiers {
    modifiers.into()
}

impl From<Modifiers> for egui::Modifiers {
    fn from(modifiers: Modifiers) -> Self {
        Self {
            alt: modifiers.alt,
            ctrl: modifiers.ctrl,
            shift: modifiers.shift,
            mac_cmd: modifiers.mac_cmd,
            command: modifiers.command,
        }
    }
}

/// The crate's wheel unit as egui's. The crate has no point unit, and a
/// pixel is what a trackpad reports, which is what egui calls a point.
fn to_wheel_unit(unit: WheelUnit) -> MouseWheelUnit {
    match unit {
        WheelUnit::Line => MouseWheelUnit::Line,
        WheelUnit::Page => MouseWheelUnit::Page,
        WheelUnit::Pixel => MouseWheelUnit::Point,
    }
}

/// The crate's mouse button as egui's, or `None` for a button egui does not
/// name. The crate names the two side buttons and egui numbers them, in the
/// same order.
fn to_pointer_button(button: MouseButton) -> Option<EguiPointerButton> {
    Some(match button {
        MouseButton::Primary => EguiPointerButton::Primary,
        MouseButton::Secondary => EguiPointerButton::Secondary,
        MouseButton::Middle => EguiPointerButton::Middle,
        MouseButton::Back => EguiPointerButton::Extra1,
        MouseButton::Forward => EguiPointerButton::Extra2,
        MouseButton::Other(_) => return None,
    })
}

/// A gesture phase in egui's spelling: the crate's `Ended` is egui's `End`.
fn to_touch_phase(phase: TouchPhase) -> EguiTouchPhase {
    match phase {
        TouchPhase::Started => EguiTouchPhase::Start,
        TouchPhase::Moved => EguiTouchPhase::Move,
        TouchPhase::Ended => EguiTouchPhase::End,
        TouchPhase::Cancelled => EguiTouchPhase::Cancel,
    }
}

/// The crate's key as egui's, or `None` for a key egui cannot name.
///
/// Every key the crate names has an egui counterpart, so this is a plain
/// rename except for [`Key::Other`]: egui's key space is closed and has no
/// "some other key" variant, so a platform key stays untranslatable.
fn to_key(key: Key) -> Option<egui::Key> {
    Some(match key {
        Key::Escape => egui::Key::Escape,
        Key::Space => egui::Key::Space,
        Key::Enter => egui::Key::Enter,
        Key::Tab => egui::Key::Tab,
        Key::Backspace => egui::Key::Backspace,
        Key::Delete => egui::Key::Delete,
        Key::ArrowUp => egui::Key::ArrowUp,
        Key::ArrowDown => egui::Key::ArrowDown,
        Key::ArrowLeft => egui::Key::ArrowLeft,
        Key::ArrowRight => egui::Key::ArrowRight,
        Key::Home => egui::Key::Home,
        Key::End => egui::Key::End,
        Key::PageUp => egui::Key::PageUp,
        Key::PageDown => egui::Key::PageDown,
        Key::A => egui::Key::A,
        Key::B => egui::Key::B,
        Key::C => egui::Key::C,
        Key::D => egui::Key::D,
        Key::E => egui::Key::E,
        Key::F => egui::Key::F,
        Key::G => egui::Key::G,
        Key::H => egui::Key::H,
        Key::I => egui::Key::I,
        Key::J => egui::Key::J,
        Key::K => egui::Key::K,
        Key::L => egui::Key::L,
        Key::M => egui::Key::M,
        Key::N => egui::Key::N,
        Key::O => egui::Key::O,
        Key::P => egui::Key::P,
        Key::Q => egui::Key::Q,
        Key::R => egui::Key::R,
        Key::S => egui::Key::S,
        Key::T => egui::Key::T,
        Key::U => egui::Key::U,
        Key::V => egui::Key::V,
        Key::W => egui::Key::W,
        Key::X => egui::Key::X,
        Key::Y => egui::Key::Y,
        Key::Z => egui::Key::Z,
        Key::Num0 => egui::Key::Num0,
        Key::Num1 => egui::Key::Num1,
        Key::Num2 => egui::Key::Num2,
        Key::Num3 => egui::Key::Num3,
        Key::Num4 => egui::Key::Num4,
        Key::Num5 => egui::Key::Num5,
        Key::Num6 => egui::Key::Num6,
        Key::Num7 => egui::Key::Num7,
        Key::Num8 => egui::Key::Num8,
        Key::Num9 => egui::Key::Num9,
        Key::F1 => egui::Key::F1,
        Key::F2 => egui::Key::F2,
        Key::F3 => egui::Key::F3,
        Key::F4 => egui::Key::F4,
        Key::F5 => egui::Key::F5,
        Key::F6 => egui::Key::F6,
        Key::F7 => egui::Key::F7,
        Key::F8 => egui::Key::F8,
        Key::F9 => egui::Key::F9,
        Key::F10 => egui::Key::F10,
        Key::F11 => egui::Key::F11,
        Key::F12 => egui::Key::F12,
        Key::F13 => egui::Key::F13,
        Key::F14 => egui::Key::F14,
        Key::F15 => egui::Key::F15,
        Key::F16 => egui::Key::F16,
        Key::F17 => egui::Key::F17,
        Key::F18 => egui::Key::F18,
        Key::F19 => egui::Key::F19,
        Key::F20 => egui::Key::F20,
        Key::F21 => egui::Key::F21,
        Key::F22 => egui::Key::F22,
        Key::F23 => egui::Key::F23,
        Key::F24 => egui::Key::F24,
        Key::F25 => egui::Key::F25,
        Key::F26 => egui::Key::F26,
        Key::F27 => egui::Key::F27,
        Key::F28 => egui::Key::F28,
        Key::F29 => egui::Key::F29,
        Key::F30 => egui::Key::F30,
        Key::F31 => egui::Key::F31,
        Key::F32 => egui::Key::F32,
        Key::F33 => egui::Key::F33,
        Key::F34 => egui::Key::F34,
        Key::F35 => egui::Key::F35,
        Key::Other(_) => return None,
    })
}

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

    /// One event's translation at a density of one, where points and pixels
    /// coincide.
    fn at_one(event: InputEvent) -> Vec<EguiEvent> {
        to_egui_event(&event, 1.0)
    }

    fn key(key: Key, pressed: bool) -> InputEvent {
        InputEvent::Key(KeyEvent {
            key,
            pressed,
            repeat: false,
            modifiers: Modifiers::default(),
        })
    }

    #[test]
    fn a_key_press_carries_both_readings_of_the_key() {
        let event = at_one(key(Key::W, true));
        assert_eq!(
            event,
            vec![EguiEvent::Key {
                key: egui::Key::W,
                physical_key: Some(egui::Key::W),
                pressed: true,
                repeat: false,
                modifiers: egui::Modifiers::default(),
            }],
            "egui's shortcuts read the logical key and a game control the \
             physical one, so both are filled from the crate's physical key"
        );
    }

    #[test]
    fn a_key_release_and_repeat_survive_the_translation() {
        let release = at_one(InputEvent::Key(KeyEvent {
            key: Key::Space,
            pressed: false,
            repeat: true,
            modifiers: Modifiers::default(),
        }));
        let EguiEvent::Key {
            pressed, repeat, ..
        } = release[0]
        else {
            panic!("a key event should translate to one egui key event");
        };
        assert!(!pressed && repeat, "both flags belong to egui's own event");
    }

    #[test]
    fn every_named_key_has_a_counterpart() {
        // The crate's keys and egui's are close enough that a name missing on
        // one side is a gap, not a deliberate omission: walk every key the
        // crate names and require a translation.
        for key in every_named_key() {
            assert!(to_key(key).is_some(), "{key:?} has no egui counterpart");
        }
    }

    /// The crate's `Key::Other` is the only key with no egui counterpart, and
    /// its event is dropped rather than reported as a different key.
    #[test]
    fn an_unnamed_key_is_dropped_rather_than_misreported() {
        assert!(at_one(key(Key::Other(0x58), true)).is_empty());
    }

    /// `Key::Other` is a real platform key, not a key the crate forgot to
    /// name, so it must not be equivalent to any named one.
    #[test]
    fn an_unnamed_key_is_not_any_named_one() {
        assert!(to_key(Key::Other(4)).is_none());
    }

    #[test]
    fn a_mouse_position_is_converted_to_points() {
        let events = to_egui_event(
            &InputEvent::Mouse(MouseEvent::Moved {
                position: [40.0, 20.0],
            }),
            2.0,
        );
        assert_eq!(
            events,
            vec![EguiEvent::PointerMoved(Pos2::new(20.0, 10.0))],
            "the crate reports physical pixels and egui lays out in points"
        );
    }

    #[test]
    fn a_mouse_button_keeps_its_position_button_and_state() {
        let events = to_egui_event(
            &InputEvent::Mouse(MouseEvent::Button {
                position: [10.0, 30.0],
                button: MouseButton::Secondary,
                pressed: true,
                modifiers: Modifiers {
                    shift: true,
                    ..Modifiers::default()
                },
            }),
            1.0,
        );
        assert_eq!(
            events,
            vec![EguiEvent::PointerButton {
                pos: Pos2::new(10.0, 30.0),
                button: EguiPointerButton::Secondary,
                pressed: true,
                modifiers: egui::Modifiers {
                    shift: true,
                    ..egui::Modifiers::default()
                },
            }]
        );
    }

    #[test]
    fn every_mouse_button_maps_to_its_own_egui_button() {
        let buttons = [
            (MouseButton::Primary, EguiPointerButton::Primary),
            (MouseButton::Secondary, EguiPointerButton::Secondary),
            (MouseButton::Middle, EguiPointerButton::Middle),
            (MouseButton::Back, EguiPointerButton::Extra1),
            (MouseButton::Forward, EguiPointerButton::Extra2),
        ];
        for (ours, theirs) in buttons {
            assert_eq!(to_pointer_button(ours), Some(theirs));
        }
        // The two side buttons must not collapse onto one.
        assert_ne!(
            to_pointer_button(MouseButton::Back),
            to_pointer_button(MouseButton::Forward)
        );
        assert_eq!(to_pointer_button(MouseButton::Other(7)), None);
    }

    #[test]
    fn a_mouse_leaving_the_window_becomes_pointer_gone() {
        assert_eq!(
            at_one(InputEvent::Mouse(MouseEvent::Left)),
            vec![EguiEvent::PointerGone]
        );
    }

    /// A device egui only hears about through the pointer level — a pen — does
    /// reach egui through it. A mouse, a touch and a trackpad do not, because
    /// each already feeds egui's pointer from its own event.
    #[test]
    fn a_mouse_a_touch_and_a_trackpad_pointer_event_is_dropped_as_a_duplicate() {
        for kind in [
            PointerKind::Mouse,
            PointerKind::Touch,
            PointerKind::Trackpad,
        ] {
            let event = InputEvent::Pointer(PointerEvent {
                kind,
                id: 0,
                action: PointerAction::Moved,
                position: Some([12.0, 24.0]),
                modifiers: Modifiers::default(),
            });
            assert!(
                at_one(event).is_empty(),
                "a {kind:?} pointer event duplicates the event that already feeds egui"
            );
        }
    }

    /// A device egui only hears about through the pointer level — a pen — does
    /// reach egui through it.
    #[test]
    fn a_pen_pointer_event_reaches_egui() {
        assert_eq!(
            at_one(InputEvent::Pointer(PointerEvent {
                kind: PointerKind::Pen,
                id: 1,
                action: PointerAction::Moved,
                position: Some([12.0, 24.0]),
                modifiers: Modifiers::default(),
            })),
            vec![EguiEvent::PointerMoved(Pos2::new(12.0, 24.0))]
        );

        assert_eq!(
            at_one(InputEvent::Pointer(PointerEvent {
                kind: PointerKind::Pen,
                id: 1,
                action: PointerAction::Pressed,
                position: Some([1.0, 2.0]),
                modifiers: Modifiers::default(),
            })),
            vec![EguiEvent::PointerButton {
                pos: Pos2::new(1.0, 2.0),
                button: EguiPointerButton::Primary,
                pressed: true,
                modifiers: egui::Modifiers::default(),
            }]
        );

        // A pen that lifts stops hovering, so it leaves the screen after the
        // release; a press keeps the pointer where it is.
        assert_eq!(
            at_one(InputEvent::Pointer(PointerEvent {
                kind: PointerKind::Pen,
                id: 1,
                action: PointerAction::Released { cancelled: false },
                position: Some([1.0, 2.0]),
                modifiers: Modifiers::default(),
            })),
            vec![
                EguiEvent::PointerButton {
                    pos: Pos2::new(1.0, 2.0),
                    button: EguiPointerButton::Primary,
                    pressed: false,
                    modifiers: egui::Modifiers::default(),
                },
                EguiEvent::PointerGone,
            ]
        );
    }

    #[test]
    fn a_pen_leaving_the_window_becomes_pointer_gone() {
        assert_eq!(
            at_one(InputEvent::Pointer(PointerEvent {
                kind: PointerKind::Pen,
                id: 1,
                action: PointerAction::Left,
                position: None,
                modifiers: Modifiers::default(),
            })),
            vec![EguiEvent::PointerGone]
        );
    }

    #[test]
    fn a_wheel_line_delta_passes_through_unscaled() {
        let events = at_one(InputEvent::Mouse(MouseEvent::Wheel {
            delta: [1.0, -3.0],
            unit: WheelUnit::Line,
            phase: TouchPhase::Moved,
            modifiers: Modifiers::default(),
        }));
        assert_eq!(
            events,
            vec![EguiEvent::MouseWheel {
                unit: MouseWheelUnit::Line,
                delta: egui::Vec2::new(1.0, -3.0),
                phase: EguiTouchPhase::Move,
                modifiers: egui::Modifiers::default(),
            }]
        );
    }

    #[test]
    fn a_wheel_pixel_delta_is_converted_to_points() {
        let events = to_egui_event(
            &InputEvent::Mouse(MouseEvent::Wheel {
                delta: [8.0, -16.0],
                unit: WheelUnit::Pixel,
                phase: TouchPhase::Started,
                modifiers: Modifiers::default(),
            }),
            2.0,
        );
        assert_eq!(
            events,
            vec![EguiEvent::MouseWheel {
                unit: MouseWheelUnit::Point,
                delta: egui::Vec2::new(4.0, -8.0),
                phase: EguiTouchPhase::Start,
                modifiers: egui::Modifiers::default(),
            }],
            "egui measures a point-unit delta in points, so a pixel delta is scaled"
        );
    }

    #[test]
    fn zoom_and_rotate_pass_their_amount_through() {
        assert_eq!(
            at_one(InputEvent::Pointer(PointerEvent {
                kind: PointerKind::Touch,
                id: 1,
                action: PointerAction::Zoom(1.5),
                position: None,
                modifiers: Modifiers::default(),
            })),
            vec![EguiEvent::Zoom(1.5)]
        );
        assert_eq!(
            at_one(InputEvent::Pointer(PointerEvent {
                kind: PointerKind::Touch,
                id: 1,
                action: PointerAction::Rotate(0.5),
                position: None,
                modifiers: Modifiers::default(),
            })),
            vec![EguiEvent::Rotate(0.5)]
        );
    }

    #[test]
    fn text_is_forwarded_as_its_own_event() {
        assert_eq!(
            at_one(InputEvent::Text(TextEvent("héllo".to_string()))),
            vec![EguiEvent::Text("héllo".to_string())]
        );
    }

    #[test]
    fn modifiers_are_forwarded_with_command_intact() {
        let modifiers = Modifiers {
            ctrl: true,
            command: true,
            ..Modifiers::default()
        };
        assert_eq!(
            at_one(InputEvent::ModifiersChanged(modifiers)),
            vec![EguiEvent::ModifiersChanged(egui::Modifiers {
                ctrl: true,
                command: true,
                ..egui::Modifiers::default()
            })]
        );
    }

    /// A touch becomes the touch egui wants plus the pointer events that make
    /// a widget react to it; a start and an end differ in which pointer
    /// transitions they carry.
    #[test]
    fn a_touch_reports_itself_and_the_pointer() {
        let start = at_one(InputEvent::Touch(TouchEvent {
            id: 7,
            phase: TouchPhase::Started,
            position: [12.0, 24.0],
            force: Some(0.5),
        }));
        assert_eq!(
            start,
            vec![
                EguiEvent::Touch {
                    device_id: TouchDeviceId(0),
                    id: TouchId(7),
                    phase: EguiTouchPhase::Start,
                    pos: Pos2::new(12.0, 24.0),
                    force: Some(0.5),
                },
                EguiEvent::PointerMoved(Pos2::new(12.0, 24.0)),
                EguiEvent::PointerButton {
                    pos: Pos2::new(12.0, 24.0),
                    button: EguiPointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
            ],
            "a finger down must also press the pointer, or a tap hits nothing"
        );

        let end = at_one(InputEvent::Touch(TouchEvent {
            id: 7,
            phase: TouchPhase::Ended,
            position: [12.0, 24.0],
            force: None,
        }));
        assert_eq!(
            end,
            vec![
                EguiEvent::Touch {
                    device_id: TouchDeviceId(0),
                    id: TouchId(7),
                    phase: EguiTouchPhase::End,
                    pos: Pos2::new(12.0, 24.0),
                    force: None,
                },
                EguiEvent::PointerButton {
                    pos: Pos2::new(12.0, 24.0),
                    button: EguiPointerButton::Primary,
                    pressed: false,
                    modifiers: egui::Modifiers::default(),
                },
                EguiEvent::PointerGone,
            ],
            "the release must come before the pointer leaves"
        );
    }

    #[test]
    fn a_moved_touch_only_moves_the_pointer() {
        let events = at_one(InputEvent::Touch(TouchEvent {
            id: 1,
            phase: TouchPhase::Moved,
            position: [4.0, 5.0],
            force: None,
        }));
        assert_eq!(events.len(), 2, "the touch and one pointer move");
        assert!(matches!(events[1], EguiEvent::PointerMoved(_)));
    }

    #[test]
    fn a_cancelled_touch_also_releases_the_pointer() {
        let events = at_one(InputEvent::Touch(TouchEvent {
            id: 1,
            phase: TouchPhase::Cancelled,
            position: [1.0, 1.0],
            force: None,
        }));
        assert!(
            matches!(events.last(), Some(EguiEvent::PointerGone)),
            "a cancelled touch is not a hover"
        );
    }

    #[test]
    fn a_preedit_range_is_remeasured_in_characters() {
        // "héllo": `é` is two bytes, so byte offsets and character offsets
        // disagree from there on.
        let text = "héllo";
        let events = at_one(InputEvent::Ime(ImeEvent {
            kind: ImeKind::Preedit {
                text: text.to_string(),
                active_range: Some(1..4),
            },
        }));
        assert_eq!(
            events,
            vec![EguiEvent::Ime(EguiImeEvent::Preedit {
                text: text.to_string(),
                active_range_chars: Some(1..3),
            })],
            "egui counts characters where the crate counts bytes"
        );
    }

    #[test]
    fn a_preedit_without_a_range_keeps_it_absent() {
        let events = at_one(InputEvent::Ime(ImeEvent {
            kind: ImeKind::Preedit {
                text: "ab".to_string(),
                active_range: None,
            },
        }));
        assert_eq!(
            events,
            vec![EguiEvent::Ime(EguiImeEvent::Preedit {
                text: "ab".to_string(),
                active_range_chars: None,
            })]
        );
    }

    #[test]
    fn a_commit_and_a_delete_surrounding_reach_egui() {
        assert_eq!(
            at_one(InputEvent::Ime(ImeEvent {
                kind: ImeKind::Commit("done".to_string()),
            })),
            vec![EguiEvent::Ime(EguiImeEvent::Commit("done".to_string()))]
        );
        assert_eq!(
            at_one(InputEvent::Ime(ImeEvent {
                kind: ImeKind::DeleteSurrounding {
                    before: 2,
                    after: 3,
                },
            })),
            vec![EguiEvent::Ime(EguiImeEvent::DeleteSurrounding {
                before_chars: 2,
                after_chars: 3,
            })]
        );
    }

    /// egui deprecated its own on/off variants, so there is nothing to
    /// forward.
    #[test]
    fn enabling_and_disabling_the_input_method_produce_nothing() {
        assert!(
            at_one(InputEvent::Ime(ImeEvent {
                kind: ImeKind::Enabled
            }))
            .is_empty()
        );
        assert!(
            at_one(InputEvent::Ime(ImeEvent {
                kind: ImeKind::Disabled
            }))
            .is_empty()
        );
    }

    #[test]
    fn focus_changes_reach_egui() {
        assert_eq!(
            at_one(InputEvent::FocusChanged(false)),
            vec![EguiEvent::WindowFocused(false)]
        );
    }

    /// A whole frame is translated in order, and the pointer transitions keep
    /// their sequence: egui's own press/release tracking depends on it.
    #[test]
    fn a_frame_keeps_its_event_order() {
        let events = vec![
            InputEvent::Mouse(MouseEvent::Moved {
                position: [1.0, 1.0],
            }),
            InputEvent::Mouse(MouseEvent::Button {
                position: [1.0, 1.0],
                button: MouseButton::Primary,
                pressed: true,
                modifiers: Modifiers::default(),
            }),
            InputEvent::Mouse(MouseEvent::Left),
        ];
        let mut converted = Vec::new();
        to_egui_events_into(&events, 1.0, &mut converted);
        assert_eq!(
            converted,
            vec![
                EguiEvent::PointerMoved(Pos2::new(1.0, 1.0)),
                EguiEvent::PointerButton {
                    pos: Pos2::new(1.0, 1.0),
                    button: EguiPointerButton::Primary,
                    pressed: true,
                    modifiers: egui::Modifiers::default(),
                },
                EguiEvent::PointerGone,
            ]
        );
    }

    #[test]
    fn an_empty_frame_converts_to_nothing() {
        let mut converted = Vec::new();
        to_egui_events_into([], 1.0, &mut converted);
        assert!(converted.is_empty());
    }

    /// The density must be usable, since every position is divided by it.
    #[test]
    #[should_panic(expected = "must be positive")]
    fn a_zero_density_is_rejected() {
        let _ = to_egui_event(
            &InputEvent::Mouse(MouseEvent::Moved {
                position: [0.0, 0.0],
            }),
            0.0,
        );
    }

    /// Every key the crate names, so a new variant cannot be added without
    /// either a translation or a deliberate decision to skip it.
    fn every_named_key() -> Vec<Key> {
        let mut keys = vec![
            Key::Escape,
            Key::Space,
            Key::Enter,
            Key::Tab,
            Key::Backspace,
            Key::Delete,
            Key::ArrowUp,
            Key::ArrowDown,
            Key::ArrowLeft,
            Key::ArrowRight,
            Key::Home,
            Key::End,
            Key::PageUp,
            Key::PageDown,
        ];
        keys.extend([
            Key::A,
            Key::B,
            Key::C,
            Key::D,
            Key::E,
            Key::F,
            Key::G,
            Key::H,
            Key::I,
            Key::J,
            Key::K,
            Key::L,
            Key::M,
            Key::N,
            Key::O,
            Key::P,
            Key::Q,
            Key::R,
            Key::S,
            Key::T,
            Key::U,
            Key::V,
            Key::W,
            Key::X,
            Key::Y,
            Key::Z,
        ]);
        keys.extend([
            Key::Num0,
            Key::Num1,
            Key::Num2,
            Key::Num3,
            Key::Num4,
            Key::Num5,
            Key::Num6,
            Key::Num7,
            Key::Num8,
            Key::Num9,
        ]);
        keys.extend([
            Key::F1,
            Key::F2,
            Key::F3,
            Key::F4,
            Key::F5,
            Key::F6,
            Key::F7,
            Key::F8,
            Key::F9,
            Key::F10,
            Key::F11,
            Key::F12,
            Key::F13,
            Key::F14,
            Key::F15,
            Key::F16,
            Key::F17,
            Key::F18,
            Key::F19,
            Key::F20,
            Key::F21,
            Key::F22,
            Key::F23,
            Key::F24,
            Key::F25,
            Key::F26,
            Key::F27,
            Key::F28,
            Key::F29,
            Key::F30,
            Key::F31,
            Key::F32,
            Key::F33,
            Key::F34,
            Key::F35,
        ]);
        keys
    }
}