guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
//! Pointer, touch and keyboard: everything the seat hands us.
//!
//! The three devices arrive together with the seat's capabilities and are
//! released together when it loses them, which is why they are kept in one
//! place rather than one struct each.
//!
//! Widgets only understand pointer events, so touch is folded into the same
//! pipeline: the first finger down drives it, and a tap becomes a click. The
//! rules of that folding are `translate_touch`, which the handlers call once
//! they have resolved the one thing that needs a compositor.

use std::time::{Duration, Instant};

use rustc_hash::FxHashMap;
use smithay_client_toolkit::seat::{
    Capability, SeatHandler, SeatState,
    keyboard::{KeyEvent, KeyboardHandler, Keysym, Modifiers as WlModifiers, RawModifiers},
    pointer::{
        AxisScroll, PointerEvent, PointerEventKind, PointerHandler,
        cursor_shape::CursorShapeManager,
    },
    touch::TouchHandler,
};

use smithay_client_toolkit::reexports::calloop::LoopHandle;
use smithay_client_toolkit::reexports::client::{
    Connection, Proxy, QueueHandle,
    protocol::{wl_keyboard, wl_pointer, wl_seat, wl_surface, wl_touch},
};
use smithay_client_toolkit::reexports::protocols::wp::cursor_shape::v1::client::wp_cursor_shape_device_v1::{
    Shape as WpCursorShape, WpCursorShapeDeviceV1,
};

use super::wayland::WaylandState;
use crate::reactive::CursorIcon;
use crate::surface::SurfaceId;
use crate::widgets::{Event, Key, Modifiers, MouseButton, Point, ScrollSource};

/// Pixels per line for discrete scroll (mouse wheel)
const SCROLL_PIXELS_PER_LINE: f32 = 40.0;

/// Queue an event, replacing the last one when a move follows a move. Every
/// queued `MouseMove` goes through here, whoever synthesized it.
///
/// Only the latest position matters for hover state, and every queued move
/// costs a full event-dispatch walk of the widget tree. The coalesced one keeps
/// the newest instant: it stands for where the pointer is now, not for where it
/// was when the run began.
fn push_event(events: &mut Vec<(Instant, Event)>, at: Instant, event: Event) {
    if matches!(event, Event::MouseMove { .. })
        && let Some(last @ (_, Event::MouseMove { .. })) = events.last_mut()
    {
        *last = (at, event);
    } else {
        events.push((at, event));
    }
}

/// The finger was *lifted*: release the synthesized press, and clear hover,
/// because unlike a real pointer nothing hovers after a lift. A release inside
/// the widget is what makes a tap a click, which is why a cancelled gesture
/// must not come through here — see the `Cancel` arm of `translate_touch`.
fn push_release(
    events: &mut Vec<(SurfaceId, Instant, Event)>,
    surface: SurfaceId,
    at: Instant,
    pointer: Point,
) {
    events.push((
        surface,
        at,
        Event::MouseUp {
            at: Some(pointer),
            button: MouseButton::Left,
        },
    ));
    events.push((surface, at, Event::MouseLeave));
}

/// The compositor speaks in surface-local `f64` pairs; everything above this
/// layer speaks in [`Point`].
fn point(position: (f64, f64)) -> Point {
    Point::new(position.0 as f32, position.1 as f32)
}

/// For the events the protocol gives no timestamp: `wl_pointer.enter` and
/// `.leave` carry a serial and nothing else, and `wl_touch.cancel` carries
/// neither. Now is the best available answer, and it is the answer everything
/// used before this existed.
fn untimed() -> Instant {
    Instant::now()
}

/// The compositor's clock, expressed in this process's.
///
/// Every input event carries a `uint` of milliseconds — `wl_pointer.motion`,
/// `.button` and `.axis`, `wl_touch.down`, and `KeyEvent::time` all do. The
/// protocol promises only that those milliseconds increase; the epoch is the
/// compositor's and there is no request that asks what it is. So the number
/// means nothing on its own and a *difference* between two of them means
/// everything, which is what an anchor turns into an `Instant`.
///
/// Reading the clock when the event is handled instead would be simpler and
/// wrong in one specific way: a handler runs some time after the event
/// happened, and that delay varies with how busy this process is. A velocity is
/// a ratio of differences, so a *constant* delay cancels out — but a varying
/// one does not, and an application too busy to draw is exactly when a gesture
/// most needs its speed read correctly.
///
/// On Linux the two clocks are the same one: libinput timestamps in
/// `CLOCK_MONOTONIC`, and so does `Instant`. The anchor is a change of origin
/// rather than a change of clock, so it cannot drift. What it does carry for
/// good is however late the *first* timestamped event was read: every instant
/// it yields is offset by that, which cancels between two events and does not
/// cancel against the frame clock.
pub(super) struct EventClock {
    /// The compositor's milliseconds at the moment `anchor` was read.
    anchor_ms: u32,
    anchor: Instant,
}

impl InputState {
    /// When an event carrying `ms` happened, anchoring the clock if this is the
    /// first one.
    ///
    /// The anchor is read here rather than at construction because the seat
    /// exists long before anything is pressed, and an anchor taken then would
    /// pair a compositor timestamp with an `Instant` from minutes earlier.
    pub(super) fn at(&mut self, ms: u32) -> Instant {
        self.event_clock
            .get_or_insert_with(|| EventClock::anchored(ms, Instant::now()))
            .instant(ms)
    }
}

impl EventClock {
    /// Anchor on the first event to arrive, whose timestamp is as close to
    /// `Instant::now()` as this process can observe.
    fn anchored(ms: u32, now: Instant) -> Self {
        Self {
            anchor_ms: ms,
            anchor: now,
        }
    }

    /// When an event carrying `ms` happened.
    ///
    /// `wrapping_sub` because the counter is a `u32` and goes round about every
    /// forty-nine days: subtracting it the ordinary way turns the first event
    /// after a wrap into one from seven weeks ago. The difference is correct as
    /// long as two events are less than that far apart, which is the same thing
    /// the protocol's own monotonicity promises.
    fn instant(&self, ms: u32) -> Instant {
        self.anchor + Duration::from_millis(ms.wrapping_sub(self.anchor_ms) as u64)
    }
}

/// The seat's three devices and the state that tracks them.
pub struct InputState {
    // Pointer
    pub(super) pointer: Option<wl_pointer::WlPointer>,
    /// Where the pointer is. One field rather than two coordinates, because
    /// every use of it is a [`Point`] — an `Event` carries an `Option<Point>`,
    /// and re-pairing two floats at each construction site is how one of them
    /// comes to be the wrong one.
    pub(super) pointer_at: Point,
    pub(super) pointer_over_surface: bool,
    pub(super) pointer_enter_serial: u32,

    // Touch
    pub(super) touch: Option<wl_touch::WlTouch>,
    /// Fingers currently down: id → (surface, x, y).
    pub(super) touch_fingers: FxHashMap<i32, (SurfaceId, f32, f32)>,
    /// The finger driving pointer emulation (the first one down). Widgets
    /// only understand pointer events, so the primary finger synthesizes
    /// MouseMove/MouseDown/MouseUp — a tap becomes a click.
    pub(super) primary_finger: Option<i32>,

    /// The compositor's clock expressed in ours, anchored on the first event
    /// that carries a timestamp. `None` until one does — which is why every
    /// reader goes through `at`.
    pub(super) event_clock: Option<EventClock>,

    // Cursor shape
    pub(super) cursor_shape_manager: Option<CursorShapeManager>,
    /// The pointer's one shape device, made and destroyed with it, as sctk's
    /// `ThemedPointer` keeps its own.
    pub(super) cursor_shape_device: Option<WpCursorShapeDeviceV1>,

    // Keyboard
    pub(super) keyboard: Option<wl_keyboard::WlKeyboard>,
    pub(super) modifiers: Modifiers,
    pub(super) keyboard_serial: u32,
    /// Track raw_code → Key for press/release matching (handles compose sequences)
    pub(super) pressed_keys: FxHashMap<u32, Key>,
    /// Key repeat runs on a calloop timer owned by the toolkit, armed with the
    /// rate and delay the compositor reports. The keyboard is created inside a
    /// seat capability callback, which has no other route to the loop.
    pub(super) loop_handle: LoopHandle<'static, WaylandState>,

    /// Serial of the most recent input event. Claiming a selection or taking a
    /// popup grab needs one the compositor still considers recent.
    pub(super) latest_input_serial: u32,
}

impl InputState {
    pub(super) fn new(
        cursor_shape_manager: Option<CursorShapeManager>,
        loop_handle: LoopHandle<'static, WaylandState>,
    ) -> Self {
        Self {
            pointer: None,
            pointer_at: Point::new(0.0, 0.0),
            pointer_over_surface: false,
            pointer_enter_serial: 0,
            touch: None,
            touch_fingers: FxHashMap::default(),
            primary_finger: None,
            event_clock: None,
            cursor_shape_manager,
            cursor_shape_device: None,
            keyboard: None,
            modifiers: Modifiers::default(),
            keyboard_serial: 0,
            pressed_keys: FxHashMap::default(),
            loop_handle,
            latest_input_serial: 0,
        }
    }
}

impl WaylandState {
    /// Set the cursor shape, against the serial of the enter it is for.
    ///
    /// The cursor-shape protocol has no hidden shape: hiding is
    /// `wl_pointer.set_cursor` with no surface. A visible shape after it goes
    /// back through `set_shape`, which replaces whatever the pointer showed.
    /// Hiding waits on the shape device like every other shape, because
    /// without one nothing could ever show the pointer again.
    pub fn set_cursor(&mut self, cursor: CursorIcon) {
        let (Some(device), Some(pointer)) = (&self.input.cursor_shape_device, &self.input.pointer)
        else {
            return;
        };
        let serial = self.input.pointer_enter_serial;
        let shape = match cursor {
            CursorIcon::Hidden => {
                pointer.set_cursor(serial, None, 0, 0);
                return;
            }
            CursorIcon::Default => WpCursorShape::Default,
            CursorIcon::Text => WpCursorShape::Text,
            CursorIcon::Pointer => WpCursorShape::Pointer,
            CursorIcon::Crosshair => WpCursorShape::Crosshair,
            CursorIcon::Move => WpCursorShape::Move,
            CursorIcon::NotAllowed => WpCursorShape::NotAllowed,
            CursorIcon::Grab => WpCursorShape::Grab,
            CursorIcon::Grabbing => WpCursorShape::Grabbing,
            CursorIcon::ResizeNorth => WpCursorShape::NResize,
            CursorIcon::ResizeSouth => WpCursorShape::SResize,
            CursorIcon::ResizeEast => WpCursorShape::EResize,
            CursorIcon::ResizeWest => WpCursorShape::WResize,
            CursorIcon::ResizeNorthEast => WpCursorShape::NeResize,
            CursorIcon::ResizeNorthWest => WpCursorShape::NwResize,
            CursorIcon::ResizeSouthEast => WpCursorShape::SeResize,
            CursorIcon::ResizeSouthWest => WpCursorShape::SwResize,
            CursorIcon::ColResize => WpCursorShape::ColResize,
            CursorIcon::RowResize => WpCursorShape::RowResize,
            CursorIcon::Wait => WpCursorShape::Wait,
            CursorIcon::Progress => WpCursorShape::Progress,
        };

        device.set_shape(serial, shape);
    }
}

impl SeatHandler for WaylandState {
    fn seat_state(&mut self) -> &mut SeatState {
        &mut self.seat_state
    }

    fn new_seat(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _seat: wl_seat::WlSeat) {}

    fn new_capability(
        &mut self,
        _conn: &Connection,
        qh: &QueueHandle<Self>,
        seat: wl_seat::WlSeat,
        capability: Capability,
    ) {
        // Handle pointer capability
        if capability == Capability::Pointer && self.input.pointer.is_none() {
            log::info!("Pointer capability available, creating pointer");
            match self.seat_state.get_pointer(qh, &seat) {
                Ok(pointer) => {
                    self.input.cursor_shape_device = self
                        .input
                        .cursor_shape_manager
                        .as_ref()
                        .map(|manager| manager.get_shape_device(&pointer, qh));
                    self.input.pointer = Some(pointer);
                }
                Err(e) => {
                    // A capability race at seat init is not fatal — the app
                    // just runs without pointer input until the seat updates
                    log::warn!("Failed to get pointer: {e}");
                    return;
                }
            }
        }

        // Handle touch capability
        if capability == Capability::Touch && self.input.touch.is_none() {
            log::info!("Touch capability available, creating touch");
            match self.seat_state.get_touch(qh, &seat) {
                Ok(touch) => self.input.touch = Some(touch),
                Err(e) => {
                    log::warn!("Failed to get touch: {e}");
                }
            }
        }

        // Handle keyboard capability
        if capability == Capability::Keyboard && self.input.keyboard.is_none() {
            log::info!("Keyboard capability available, creating keyboard");
            let loop_handle = self.input.loop_handle.clone();
            let keyboard = match self.seat_state.get_keyboard_with_repeat(
                qh,
                &seat,
                None,
                loop_handle,
                Box::new(|state: &mut WaylandState, _kbd, event| state.emit_key_repeat(event)),
            ) {
                Ok(keyboard) => keyboard,
                Err(e) => {
                    log::warn!("Failed to get keyboard: {e}");
                    return;
                }
            };
            self.input.keyboard = Some(keyboard);

            // Selections hang off the seat, so they cannot be created with
            // their managers at startup.
            self.selections.attach_devices(qh, &seat);
        }
    }

    fn remove_capability(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _seat: wl_seat::WlSeat,
        capability: Capability,
    ) {
        if capability == Capability::Pointer {
            log::info!("Pointer capability removed");
            if let Some(device) = self.input.cursor_shape_device.take() {
                device.destroy();
            }
            if let Some(pointer) = self.input.pointer.take() {
                pointer.release();
            }
        }
        if capability == Capability::Keyboard {
            log::info!("Keyboard capability removed");
            if let Some(keyboard) = self.input.keyboard.take() {
                keyboard.release();
            }
        }
        if capability == Capability::Touch {
            log::info!("Touch capability removed");
            if let Some(touch) = self.input.touch.take() {
                touch.release();
            }
            // The device went away mid-gesture, so no finger is ever lifting
            // again: the same teardown `cancel` does, and for the same reason.
            self.touch_event(TouchEvent::Cancel { at: untimed() });
        }
    }

    fn remove_seat(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _seat: wl_seat::WlSeat) {
    }
}

/// What a `wl_touch` message says, with the only thing that needs a compositor
/// — which surface the finger landed on — already looked up.
enum TouchEvent {
    Down {
        id: i32,
        surface: SurfaceId,
        at: Instant,
        position: Point,
    },
    Motion {
        id: i32,
        at: Instant,
        position: Point,
    },
    Up {
        id: i32,
        at: Instant,
    },
    /// The gesture stopped being ours. Two things say so and neither carries a
    /// time — `wl_touch.cancel` has no serial and no timestamp, and a seat
    /// losing its touch capability is not a message about a finger at all — so
    /// the handler answers `untimed()`, as the pointer's `enter` and `leave`
    /// are answered.
    Cancel {
        at: Instant,
    },
}

/// What a touch message asks the surfaces to do, given the fingers already
/// down and which of them is driving the pointer.
///
/// Free rather than inline, for the same reason `translate_axis` is: a callback
/// that needs a compositor to run is a callback nothing checks, and the folding
/// of touch into pointer is a state machine with rules of its own — which
/// finger drives, what a second one does, where a drag is delivered once it
/// leaves the surface it started on.
fn translate_touch(
    fingers: &mut FxHashMap<i32, (SurfaceId, f32, f32)>,
    primary: &mut Option<i32>,
    event: TouchEvent,
) -> Vec<(SurfaceId, Instant, Event)> {
    let mut events = Vec::new();
    match event {
        TouchEvent::Down {
            id,
            surface,
            at,
            position,
        } => {
            fingers.insert(id, (surface, position.x, position.y));

            // The first finger down drives pointer emulation: move + press so
            // hover and pressed state layers respond, and a tap becomes a
            // click. A second finger is tracked and otherwise silent — widgets
            // have one pointer, and a press it cannot release is worse than no
            // press at all.
            if primary.is_none() {
                *primary = Some(id);
                events.push((surface, at, Event::finger_move(position.x, position.y)));
                events.push((surface, at, Event::finger_down(position.x, position.y)));
            }
        }
        TouchEvent::Motion { id, at, position } => {
            let Some(finger) = fingers.get_mut(&id) else {
                return events;
            };
            finger.1 = position.x;
            finger.2 = position.y;

            // The surface it landed on, not whatever is under it now:
            // `wl_touch.motion` names none, and the widget holding the press is
            // the one that has to see the release.
            let surface = finger.0;
            if *primary == Some(id) {
                events.push((surface, at, Event::finger_move(position.x, position.y)));
            }
        }
        TouchEvent::Up { id, at } => {
            let Some((surface, x, y)) = fingers.remove(&id) else {
                return events;
            };
            if *primary == Some(id) {
                *primary = None;
                push_release(&mut events, surface, at, Point::new(x, y));
            }
        }
        TouchEvent::Cancel { at } => {
            // The gesture is not ours any more, so the press has to end — but
            // it was not a click, and `MouseUp` is how a click is spelled. A
            // cancelled finger is still inside the widget it pressed, so a
            // release would land inside the hit and `on_click` would fire:
            // the compositor takes the gesture away and guido presses the
            // button. `MouseLeave` alone is what ending a press without
            // activating anything already means here — `pointer_left` in
            // `container/interaction.rs` drops `PRESSED` and cancels the
            // ripple rather than completing it — and because the `MouseUp`
            // arm there is guarded by `is_pressed`, a real release arriving
            // later does nothing.
            if let Some(id) = primary.take()
                && let Some((surface, _, _)) = fingers.get(&id).copied()
            {
                events.push((surface, at, Event::MouseLeave));
            }
            fingers.clear();
        }
    }
    events
}

impl WaylandState {
    /// Translate a touch message and queue the result on the surfaces it
    /// named. Everything the compositor is needed for happens before this.
    fn touch_event(&mut self, event: TouchEvent) {
        let translated = translate_touch(
            &mut self.input.touch_fingers,
            &mut self.input.primary_finger,
            event,
        );
        for (surface_id, at, event) in translated {
            if let Some(surface_state) = self.surfaces.get_mut(&surface_id) {
                push_event(&mut surface_state.pending_events, at, event);
            }
        }
    }
}

impl TouchHandler for WaylandState {
    fn down(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _touch: &wl_touch::WlTouch,
        serial: u32,
        time: u32,
        surface: wl_surface::WlSurface,
        id: i32,
        position: (f64, f64),
    ) {
        self.input.latest_input_serial = serial;
        let Some(surface_id) = self.surface_lookup.get(&surface.id()).copied() else {
            return;
        };
        let at = self.input.at(time);
        self.touch_event(TouchEvent::Down {
            id,
            surface: surface_id,
            at,
            position: point(position),
        });
    }

    fn up(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _touch: &wl_touch::WlTouch,
        _serial: u32,
        time: u32,
        id: i32,
    ) {
        let at = self.input.at(time);
        self.touch_event(TouchEvent::Up { id, at });
    }

    fn motion(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _touch: &wl_touch::WlTouch,
        time: u32,
        id: i32,
        position: (f64, f64),
    ) {
        let at = self.input.at(time);
        self.touch_event(TouchEvent::Motion {
            id,
            at,
            position: point(position),
        });
    }

    fn shape(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _touch: &wl_touch::WlTouch,
        _id: i32,
        _major: f64,
        _minor: f64,
    ) {
    }

    fn orientation(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _touch: &wl_touch::WlTouch,
        _id: i32,
        _orientation: f64,
    ) {
    }

    fn cancel(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _touch: &wl_touch::WlTouch) {
        self.touch_event(TouchEvent::Cancel { at: untimed() });
    }
}

impl PointerHandler for WaylandState {
    fn pointer_frame(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _pointer: &wl_pointer::WlPointer,
        events: &[PointerEvent],
    ) {
        for event in events {
            // Try to find the surface ID for this event's wl_surface
            let surface_id = self.surface_lookup.get(&event.surface.id()).copied();

            // When this one happened. `enter` and `leave` carry a serial and no
            // timestamp, so they get now — which is what everything got before
            // the clock existed.
            let at = match event.kind {
                PointerEventKind::Motion { time }
                | PointerEventKind::Press { time, .. }
                | PointerEventKind::Release { time, .. }
                | PointerEventKind::Axis { time, .. } => self.input.at(time),
                PointerEventKind::Enter { .. } | PointerEventKind::Leave { .. } => untimed(),
            };

            // Get the target event queue for this surface
            let target_events: Option<&mut Vec<(Instant, Event)>> = if let Some(id) = surface_id {
                self.surfaces.get_mut(&id).map(|s| &mut s.pending_events)
            } else if !matches!(event.kind, PointerEventKind::Leave { .. }) {
                // Not our surface and not a leave event, skip
                continue;
            } else {
                None
            };

            match event.kind {
                PointerEventKind::Enter { serial } => {
                    self.input.pointer_over_surface = true;
                    self.input.pointer_enter_serial = serial;
                    self.input.latest_input_serial = serial;
                    self.input.pointer_at = point(event.position);

                    // Track which surface has pointer focus
                    self.current_pointer_surface = surface_id;

                    if let Some(events) = target_events {
                        events.push((
                            at,
                            Event::MouseEnter {
                                at: Some(self.input.pointer_at),
                            },
                        ));
                        push_event(
                            events,
                            at,
                            Event::mouse_move(self.input.pointer_at.x, self.input.pointer_at.y),
                        );
                    }
                }
                PointerEventKind::Leave { .. } => {
                    if self.input.pointer_over_surface {
                        self.input.pointer_over_surface = false;

                        // Send leave event to the surface that had focus
                        if let Some(id) = self.current_pointer_surface
                            && let Some(surface_state) = self.surfaces.get_mut(&id)
                        {
                            surface_state.pending_events.push((at, Event::MouseLeave));
                        }

                        self.current_pointer_surface = None;
                    }
                }
                PointerEventKind::Motion { .. } => {
                    self.input.pointer_at = point(event.position);
                    if let Some(events) = target_events {
                        push_event(
                            events,
                            at,
                            Event::mouse_move(self.input.pointer_at.x, self.input.pointer_at.y),
                        );
                    }
                }
                PointerEventKind::Press { button, serial, .. } => {
                    self.input.latest_input_serial = serial;
                    if let Some(mouse_button) = wayland_button_to_mouse_button(button)
                        && let Some(events) = target_events
                    {
                        events.push((
                            at,
                            Event::mouse_down(
                                self.input.pointer_at.x,
                                self.input.pointer_at.y,
                                mouse_button,
                            ),
                        ));
                    }
                }
                PointerEventKind::Release { button, .. } => {
                    if let Some(mouse_button) = wayland_button_to_mouse_button(button)
                        && let Some(events) = target_events
                    {
                        events.push((
                            at,
                            Event::MouseUp {
                                at: Some(self.input.pointer_at),
                                button: mouse_button,
                            },
                        ));
                    }
                }
                PointerEventKind::Axis {
                    horizontal,
                    vertical,
                    source,
                    ..
                } => {
                    if let Some(events) = target_events {
                        translate_axis(
                            events,
                            at,
                            source,
                            &horizontal,
                            &vertical,
                            self.input.pointer_at,
                        );
                    }
                }
            }
        }
    }
}

/// What an axis message asks a widget to do, given where the pointer is.
///
/// Free rather than inline, for the same reason `keysym_to_key` is: a callback
/// that needs a compositor to run is a callback nothing checks, and this is
/// where the protocol's only statement about a gesture *ending* is read.
fn translate_axis(
    events: &mut Vec<(Instant, Event)>,
    at: Instant,
    source: Option<wl_pointer::AxisSource>,
    horizontal: &AxisScroll,
    vertical: &AxisScroll,
    pointer: Point,
) {
    let scroll_source = match source {
        Some(wl_pointer::AxisSource::Wheel) => ScrollSource::Wheel,
        Some(wl_pointer::AxisSource::Finger) => ScrollSource::Finger,
        Some(wl_pointer::AxisSource::Continuous) => ScrollSource::Continuous,
        Some(wl_pointer::AxisSource::WheelTilt) => ScrollSource::Wheel,
        _ => ScrollSource::Wheel,
    };

    // Wheel steps by preference: value120 (wl_pointer v8+, fractional steps
    // from high-resolution wheels) then legacy discrete. Touchpad and finger
    // scroll have neither and report absolute pixels, which pass through —
    // multiplying those by a line height scrolls a page for a fingertip.
    let pixels = |scroll: &AxisScroll| {
        let steps = if scroll.value120 != 0 {
            scroll.value120 as f32 / 120.0
        } else {
            scroll.discrete as f32
        };
        if steps != 0.0 {
            steps * SCROLL_PIXELS_PER_LINE
        } else {
            scroll.absolute as f32
        }
    };

    let delta_x = pixels(horizontal);
    let delta_y = pixels(vertical);

    // An axis message says two things, and a guard on the delta alone dropped
    // the second. `axis_stop` is how the hardware ends a continuous scroll, and
    // it carries no delta — because nothing moved — so it was filtered out one
    // line before anything could use it. It is the only unguessed answer to
    // when a gesture is over.
    if delta_x != 0.0 || delta_y != 0.0 {
        events.push((
            at,
            Event::Scroll {
                at: Some(pointer),
                delta_x,
                delta_y,
                source: scroll_source,
            },
        ));
    }
    if horizontal.stop || vertical.stop {
        events.push((at, Event::ScrollEnd { at: Some(pointer) }));
    }
}

/// Convert Wayland button code to MouseButton
fn wayland_button_to_mouse_button(button: u32) -> Option<MouseButton> {
    // Linux input event codes (from linux/input-event-codes.h)
    const BTN_LEFT: u32 = 0x110;
    const BTN_RIGHT: u32 = 0x111;
    const BTN_MIDDLE: u32 = 0x112;

    match button {
        BTN_LEFT => Some(MouseButton::Left),
        BTN_RIGHT => Some(MouseButton::Right),
        BTN_MIDDLE => Some(MouseButton::Middle),
        _ => None,
    }
}

impl KeyboardHandler for WaylandState {
    fn enter(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &wl_keyboard::WlKeyboard,
        surface: &wl_surface::WlSurface,
        _serial: u32,
        _raw: &[u32],
        _keysyms: &[Keysym],
    ) {
        log::debug!("Keyboard focus entered");

        // Track which surface has keyboard focus
        let surface_id = self.surface_lookup.get(&surface.id()).copied();
        self.current_keyboard_surface = surface_id;

        // Route event to correct surface
        if let Some(id) = surface_id
            && let Some(surface_state) = self.surfaces.get_mut(&id)
        {
            surface_state
                .pending_events
                .push((untimed(), Event::FocusIn));
        }
    }

    fn leave(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &wl_keyboard::WlKeyboard,
        surface: &wl_surface::WlSurface,
        _serial: u32,
    ) {
        log::debug!("Keyboard focus left");

        // Route event to correct surface
        let surface_id = self.surface_lookup.get(&surface.id()).copied();
        if let Some(id) = surface_id
            && let Some(surface_state) = self.surfaces.get_mut(&id)
        {
            surface_state
                .pending_events
                .push((untimed(), Event::FocusOut));
        }

        self.current_keyboard_surface = None;
    }

    fn press_key(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &wl_keyboard::WlKeyboard,
        serial: u32,
        event: KeyEvent,
    ) {
        // Track serial for clipboard operations
        self.input.keyboard_serial = serial;
        self.input.latest_input_serial = serial;

        if let Some(delivered) = self.input.key_pressed(&event) {
            self.deliver_key(delivered);
        }
    }

    fn release_key(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &wl_keyboard::WlKeyboard,
        _serial: u32,
        event: KeyEvent,
    ) {
        // Use the stored key from press_key if available (handles compose sequences
        // where the composed character differs from the raw keysym on release)
        let key = self
            .input
            .pressed_keys
            .remove(&event.raw_code)
            .or_else(|| keysym_to_key(event.keysym, event.utf8.as_deref(), false));

        if let Some(key) = key {
            let at = self.input.at(event.time);
            let key_event = Event::KeyUp {
                key,
                modifiers: self.input.modifiers,
            };
            self.deliver_key((at, key_event));
        }
    }

    fn update_modifiers(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &wl_keyboard::WlKeyboard,
        _serial: u32,
        modifiers: WlModifiers,
        _raw_modifiers: RawModifiers,
        _layout: u32,
    ) {
        self.input.modifiers = Modifiers {
            ctrl: modifiers.ctrl,
            alt: modifiers.alt,
            shift: modifiers.shift,
            logo: modifiers.logo,
            caps_lock: modifiers.caps_lock,
        };
        // Published as a signal as well: a latched modifier is a state
        // something on screen may need to show with nothing pressed and no key
        // event coming to carry it.
        crate::keyboard::set_keyboard_modifiers(self.input.modifiers);
    }

    fn repeat_key(
        &mut self,
        _conn: &Connection,
        _qh: &QueueHandle<Self>,
        _keyboard: &wl_keyboard::WlKeyboard,
        _serial: u32,
        event: KeyEvent,
    ) {
        self.emit_key_repeat(event);
    }
}

impl WaylandState {
    /// Deliver a held key.
    ///
    /// Two sources reach here: the toolkit's calloop timer, armed from the
    /// compositor's `repeat_info`, and the protocol's own repeated key state.
    /// A widget is not told which — only that the key repeats.
    fn emit_key_repeat(&mut self, event: KeyEvent) {
        if let Some(delivered) = self.input.key_repeated(&event) {
            self.deliver_key(delivered);
        }
    }

    /// Queue a key event on the surface with keyboard focus.
    fn deliver_key(&mut self, (at, event): (Instant, Event)) {
        if let Some(id) = self.current_keyboard_surface
            && let Some(surface_state) = self.surfaces.get_mut(&id)
        {
            surface_state.pending_events.push((at, event));
        }
    }
}

impl InputState {
    /// The key-down a press delivers, and when — `None` for a key with
    /// nothing to say yet, an open compose sequence.
    ///
    /// The key is kept against its raw code, so the release names the key the
    /// press did — a composed 'é', not the raw 'e' — when it carries no text.
    pub(super) fn key_pressed(&mut self, event: &KeyEvent) -> Option<(Instant, Event)> {
        let key = keysym_to_key(event.keysym, event.utf8.as_deref(), true)?;
        self.pressed_keys.insert(event.raw_code, key);
        Some(self.key_down(key, event.time, false))
    }

    /// The key-down a held key delivers, and when.
    ///
    /// A repeat's `time` is the original press advanced by the repeat gap
    /// rather than something the compositor observed — sctk's timer computes
    /// it. It is still in the compositor's clock and still increases, which is
    /// all the conversion needs, and a held key spaced by the compositor's own
    /// repeat rate is a truer account than the moment a timer fired here.
    pub(super) fn key_repeated(&mut self, event: &KeyEvent) -> Option<(Instant, Event)> {
        let key = keysym_to_key(event.keysym, event.utf8.as_deref(), true)?;
        Some(self.key_down(key, event.time, true))
    }

    fn key_down(&mut self, key: Key, time: u32, repeat: bool) -> (Instant, Event) {
        let key_down = Event::KeyDown {
            key,
            modifiers: self.modifiers,
            repeat,
        };
        (self.at(time), key_down)
    }
}

/// Convert XKB keysym to our Key type
fn keysym_to_key(keysym: Keysym, utf8: Option<&str>, is_press: bool) -> Option<Key> {
    // Named keys first
    match keysym {
        Keysym::BackSpace => return Some(Key::Backspace),
        Keysym::Delete => return Some(Key::Delete),
        Keysym::Return | Keysym::KP_Enter => return Some(Key::Enter),
        Keysym::Tab | Keysym::ISO_Left_Tab => return Some(Key::Tab),
        Keysym::Escape => return Some(Key::Escape),
        Keysym::Left => return Some(Key::Left),
        Keysym::Right => return Some(Key::Right),
        Keysym::Up => return Some(Key::Up),
        Keysym::Down => return Some(Key::Down),
        Keysym::Home => return Some(Key::Home),
        Keysym::End => return Some(Key::End),
        _ => {}
    }

    // Character input: utf8 carries the composed result, so it wins whenever
    // it holds something printable.
    if let Some(text) = utf8
        && let Some(c) = text.chars().next()
    {
        if !c.is_control() || c == '\n' || c == '\r' || c == '\t' {
            return Some(Key::Char(c));
        }

        // A control character here means a modifier ate the letter: Ctrl+C
        // arrives as U+0003, not as 'c'. The keysym still carries the letter,
        // so fall through to it — otherwise every Ctrl chord is dropped and
        // copy, cut and paste never reach a widget.
        return keysym_char(keysym);
    }

    // No utf8 on a press means a compose sequence is still open: there is
    // nothing to insert yet. On release utf8 is always absent, so the keysym
    // is all there is.
    if !is_press {
        return keysym_char(keysym);
    }

    None
}

/// The character a keysym stands for, ignoring any composition.
fn keysym_char(keysym: Keysym) -> Option<Key> {
    let raw = keysym.raw();

    // Printable ASCII range (space through tilde): 0x20-0x7E
    // XKB keysyms for these characters have the same value as ASCII
    if (0x20..=0x7e).contains(&raw) {
        return Some(Key::Char(char::from_u32(raw)?));
    }

    // Handle keypad numbers (KP_0 through KP_9)
    // XKB_KEY_KP_0 = 0xffb0, XKB_KEY_KP_9 = 0xffb9
    if (0xffb0..=0xffb9).contains(&raw) {
        return Some(Key::Char(char::from_u32(raw - 0xffb0 + 0x30)?)); // Convert to '0'-'9'
    }

    None
}

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

    /// A held modifier replaces the character xkb reports: Ctrl+C arrives as
    /// U+0003, not as 'c'. The keysym still carries the letter, and dropping
    /// the event here means copy, cut, paste, undo and select-all never reach
    /// a widget at all.
    #[test]
    fn a_ctrl_chord_keeps_its_letter() {
        let c = Keysym::new(0x63); // 'c'
        assert_eq!(
            keysym_to_key(c, Some("\u{3}"), true),
            Some(Key::Char('c')),
            "Ctrl+C must arrive as 'c'"
        );
    }

    /// The case the control-character guard exists for: while a compose
    /// sequence is open xkb reports no text, and nothing should be inserted
    /// until it resolves.
    #[test]
    fn an_open_compose_sequence_inserts_nothing() {
        let e = Keysym::new(0x65); // 'e'
        assert_eq!(keysym_to_key(e, None, true), None);
    }

    /// Release events never carry text, so the keysym is all there is —
    /// that is how a composed key is matched back to the press that made it.
    #[test]
    fn a_release_falls_back_to_the_keysym() {
        let e = Keysym::new(0x65);
        assert_eq!(keysym_to_key(e, None, false), Some(Key::Char('e')));
    }

    /// Ordinary typing still goes through the text, not the keysym: that is
    /// what carries an accented or composed character.
    #[test]
    fn plain_typing_uses_the_composed_text() {
        let e = Keysym::new(0x65); // 'e', composed into 'é'
        assert_eq!(keysym_to_key(e, Some("é"), true), Some(Key::Char('é')));
    }

    /// A keyboard with nothing pressed. The loop handle is only carried, to
    /// arm the toolkit's repeat timer when a keyboard arrives.
    fn keyboard() -> InputState {
        let event_loop = smithay_client_toolkit::reexports::calloop::EventLoop::try_new()
            .expect("an event loop needs no compositor");
        InputState::new(None, event_loop.handle())
    }

    fn enter(time: u32) -> KeyEvent {
        KeyEvent {
            time,
            raw_code: 28,
            keysym: Keysym::Return,
            utf8: Some("\r".into()),
        }
    }

    fn repeat_of(delivered: Option<(Instant, Event)>) -> bool {
        match delivered {
            Some((_, Event::KeyDown { repeat, .. })) => repeat,
            other => panic!("expected a key-down, got {other:?}"),
        }
    }

    /// What `press_key` delivers is a press, and what a held key delivers is a
    /// repeat — whichever produced it. The toolkit's timer and the protocol's
    /// repeated key state both reach `emit_key_repeat`, which delivers
    /// `key_repeated`; a widget sees one flag for both, as winit, SDL and the
    /// DOM give it.
    #[test]
    fn a_press_and_a_held_key_say_which_they_are() {
        let mut input = keyboard();

        assert!(!repeat_of(input.key_pressed(&enter(0))), "the press");
        assert!(
            repeat_of(input.key_repeated(&enter(600))),
            "the first repeat"
        );
        assert!(repeat_of(input.key_repeated(&enter(625))), "the next");
        assert!(!repeat_of(input.key_pressed(&enter(900))), "pressed again");
    }

    /// A repeat is the key that was pressed, under the modifiers held now, at
    /// the time the compositor's clock gives it.
    #[test]
    fn a_repeat_carries_its_key_modifiers_and_time() {
        let mut input = keyboard();
        let (pressed, _) = input.key_pressed(&enter(1_000)).unwrap();
        input.modifiers.shift = true;

        let (at, event) = input.key_repeated(&enter(1_600)).unwrap();

        assert_eq!(at - pressed, Duration::from_millis(600));
        let Event::KeyDown { key, modifiers, .. } = event else {
            panic!("{event:?}")
        };
        assert_eq!(key, Key::Enter);
        assert!(modifiers.shift);
    }

    /// An open compose sequence has nothing to deliver, pressed or held.
    #[test]
    fn a_key_with_no_text_yet_delivers_nothing() {
        let mut input = keyboard();
        let composing = KeyEvent {
            time: 0,
            raw_code: 18,
            keysym: Keysym::new(0x65),
            utf8: None,
        };

        assert!(input.key_pressed(&composing).is_none());
        assert!(input.key_repeated(&composing).is_none());
    }

    /// A timestamp equal to the anchor's is the anchor's instant, and one after
    /// it is that far after. Nothing else about the compositor's epoch matters:
    /// the protocol says only that its milliseconds increase, so a difference
    /// is the only thing that can be read out of them.
    #[test]
    fn an_events_time_is_read_as_a_distance_from_the_anchor() {
        let t0 = Instant::now();
        let clock = EventClock::anchored(1_000, t0);

        assert_eq!(clock.instant(1_000), t0, "the anchor is where it says");
        assert_eq!(
            clock.instant(1_250),
            t0 + Duration::from_millis(250),
            "and a quarter second later is a quarter second later"
        );
    }

    /// The compositor's clock is a `u32` of milliseconds, so it wraps roughly
    /// every 49 days and a client that has been running across one sees the
    /// number fall. Subtracting it the ordinary way makes 16ms after the wrap
    /// look like 49 days before it — a scroll gesture that ended in the far
    /// past, a caret that never blinks again.
    #[test]
    fn a_clock_that_has_wrapped_still_moves_forwards() {
        let t0 = Instant::now();
        let clock = EventClock::anchored(u32::MAX - 4, t0);

        // Five milliseconds later the counter has gone round: MAX-4 → MAX → 0
        // → 11 is sixteen milliseconds of real time.
        assert_eq!(
            clock.instant(11),
            t0 + Duration::from_millis(16),
            "the wrap is sixteen milliseconds forwards, not forty-nine days back"
        );
    }

    /// The pointer position the events carry, so a test can tell it apart
    /// from a delta.
    const PX: f32 = 10.0;
    const PY: f32 = 20.0;

    fn at(pointer: Point) -> Event {
        Event::mouse_move(pointer.x, pointer.y)
    }

    /// The rule `push_event` took off its call sites. A queued move stands for
    /// where the pointer is now, so the next one replaces it — and an event
    /// that is not a move is appended, because a press queued behind a move
    /// that then swallowed it is a click the widget never sees.
    #[test]
    fn a_queued_move_gives_way_to_the_next_move_and_to_nothing_else() {
        let t0 = Instant::now();
        let later = t0 + Duration::from_millis(16);
        let mut events = Vec::new();

        push_event(&mut events, t0, at(Point::new(1.0, 1.0)));
        push_event(&mut events, later, at(Point::new(2.0, 2.0)));
        let [
            (
                when,
                Event::MouseMove {
                    at: Some(pointer), ..
                },
            ),
        ] = events.as_slice()
        else {
            panic!("two moves are one move, got {events:?}");
        };
        assert_eq!(*pointer, Point::new(2.0, 2.0), "the newest position wins");
        assert_eq!(*when, later, "and brings its instant with it");

        push_event(
            &mut events,
            later,
            Event::mouse_down(2.0, 2.0, MouseButton::Left),
        );
        push_event(&mut events, later, at(Point::new(3.0, 3.0)));
        assert!(
            matches!(
                events.as_slice(),
                [
                    (_, Event::MouseMove { .. }),
                    (_, Event::MouseDown { .. }),
                    (_, Event::MouseMove { .. }),
                ]
            ),
            "the press survives, and the move after it starts a new run, got {events:?}"
        );
    }

    fn axis(
        source: Option<wl_pointer::AxisSource>,
        horizontal: AxisScroll,
        vertical: AxisScroll,
    ) -> Vec<Event> {
        let mut events = Vec::new();
        translate_axis(
            &mut events,
            Instant::now(),
            source,
            &horizontal,
            &vertical,
            Point::new(PX, PY),
        );
        events.into_iter().map(|(_, event)| event).collect()
    }

    fn nothing() -> AxisScroll {
        AxisScroll::default()
    }

    fn wheel(value120: i32) -> AxisScroll {
        AxisScroll {
            value120,
            ..Default::default()
        }
    }

    fn finger(absolute: f64) -> AxisScroll {
        AxisScroll {
            absolute,
            ..Default::default()
        }
    }

    fn stopped() -> AxisScroll {
        AxisScroll {
            stop: true,
            ..Default::default()
        }
    }

    /// The case #205 rests on. `axis_stop` carries no delta — nothing moved —
    /// so a guard on the delta alone swallows the only unguessed answer to
    /// when a gesture is over.
    #[test]
    fn a_stop_with_no_delta_is_an_end_and_nothing_else() {
        let events = axis(Some(wl_pointer::AxisSource::Finger), nothing(), stopped());
        assert_eq!(events.len(), 1, "one event, got {events:?}");
        let Event::ScrollEnd { at } = events[0] else {
            panic!("a stop is a ScrollEnd, got {:?}", events[0]);
        };
        assert_eq!(
            at,
            Some(Point::new(PX, PY)),
            "and it carries the pointer, not a delta"
        );

        // Either axis alone says it: a vertical gesture ends on the vertical
        // axis, a horizontal one on the horizontal.
        let events = axis(Some(wl_pointer::AxisSource::Finger), stopped(), nothing());
        assert!(
            matches!(events.as_slice(), [Event::ScrollEnd { .. }]),
            "the horizontal axis ends a gesture too, got {events:?}"
        );
    }

    /// One logical step is one line, and a high-resolution wheel reports it in
    /// hundred-and-twentieths so half a step is half a line.
    #[test]
    fn a_wheel_step_is_a_line_and_a_fraction_of_one_is_a_fraction_of_a_line() {
        let events = axis(Some(wl_pointer::AxisSource::Wheel), nothing(), wheel(120));
        let [
            Event::Scroll {
                delta_y, source, ..
            },
        ] = events.as_slice()
        else {
            panic!("a wheel step scrolls, got {events:?}");
        };
        assert_eq!(*delta_y, SCROLL_PIXELS_PER_LINE);
        assert_eq!(*source, ScrollSource::Wheel);

        let events = axis(Some(wl_pointer::AxisSource::Wheel), nothing(), wheel(60));
        let [Event::Scroll { delta_y, .. }] = events.as_slice() else {
            panic!("half a step scrolls, got {events:?}");
        };
        assert_eq!(*delta_y, SCROLL_PIXELS_PER_LINE / 2.0);
    }

    /// A compositor that sends both sends the legacy field for the benefit of
    /// clients that cannot read the other one. Reading `discrete` in
    /// preference would round a half step down to nothing.
    #[test]
    fn value120_answers_before_discrete() {
        let both = AxisScroll {
            value120: 60,
            discrete: 1,
            ..Default::default()
        };
        let events = axis(Some(wl_pointer::AxisSource::Wheel), nothing(), both);
        let [Event::Scroll { delta_y, .. }] = events.as_slice() else {
            panic!("expected one scroll, got {events:?}");
        };
        assert_eq!(
            *delta_y,
            SCROLL_PIXELS_PER_LINE / 2.0,
            "the high-resolution field decides"
        );
    }

    /// A touchpad has neither step field: it already speaks in pixels, and
    /// multiplying those by a line height would scroll a page for a fingertip.
    #[test]
    fn a_touchpad_scrolls_the_pixels_it_reports() {
        let events = axis(Some(wl_pointer::AxisSource::Finger), nothing(), finger(7.5));
        let [
            Event::Scroll {
                at,
                delta_y,
                source,
                ..
            },
        ] = events.as_slice()
        else {
            panic!("expected one scroll, got {events:?}");
        };
        assert_eq!(*delta_y, 7.5, "pixels pass through");
        assert_eq!(*source, ScrollSource::Finger);
        // Where the scroll happened, not how far it went: `hit.contains(at)`
        // in `interaction.rs` is what decides whose scroll this is.
        assert_eq!(*at, Some(Point::new(PX, PY)), "and it carries the pointer");
    }

    /// The last message of a flick carries both: the final movement and the
    /// lifted finger. The movement has to arrive first, or the momentum is
    /// computed from a sample the gesture had not yet made.
    #[test]
    fn a_gesture_that_moves_and_stops_says_both_in_that_order() {
        let last = AxisScroll {
            absolute: 12.0,
            stop: true,
            ..Default::default()
        };
        let events = axis(Some(wl_pointer::AxisSource::Finger), nothing(), last);
        assert!(
            matches!(
                events.as_slice(),
                [Event::Scroll { .. }, Event::ScrollEnd { .. }]
            ),
            "the movement, then the end, got {events:?}"
        );
    }

    /// An axis message that says neither is a frame boundary, not an event.
    /// Pushing for it would wake the surface for nothing.
    #[test]
    fn an_axis_message_with_neither_a_delta_nor_a_stop_says_nothing() {
        let events = axis(Some(wl_pointer::AxisSource::Wheel), nothing(), nothing());
        assert!(events.is_empty(), "got {events:?}");
    }

    /// A continuous source is neither of the others: it reports pixels like a
    /// finger, and since #248 it coasts when the gesture ends where a wheel
    /// does not. Folding it into either one changes what happens on release.
    #[test]
    fn a_continuous_source_stays_continuous() {
        let events = axis(
            Some(wl_pointer::AxisSource::Continuous),
            nothing(),
            finger(5.0),
        );
        let [
            Event::Scroll {
                delta_y, source, ..
            },
        ] = events.as_slice()
        else {
            panic!("expected one scroll, got {events:?}");
        };
        assert_eq!(*delta_y, 5.0);
        assert_eq!(*source, ScrollSource::Continuous);
    }

    /// A tilted wheel is still a wheel — it steps — and a source the protocol
    /// grows later is treated as one until somebody teaches it otherwise.
    #[test]
    fn a_tilted_wheel_is_a_wheel_and_so_is_an_unnamed_source() {
        let events = axis(
            Some(wl_pointer::AxisSource::WheelTilt),
            wheel(120),
            nothing(),
        );
        let [
            Event::Scroll {
                delta_x, source, ..
            },
        ] = events.as_slice()
        else {
            panic!("expected one scroll, got {events:?}");
        };
        assert_eq!(*source, ScrollSource::Wheel);
        assert_eq!(
            *delta_x, SCROLL_PIXELS_PER_LINE,
            "and a tilt steps sideways by a line"
        );

        let events = axis(None, wheel(120), nothing());
        let [Event::Scroll { source, .. }] = events.as_slice() else {
            panic!("expected one scroll, got {events:?}");
        };
        assert_eq!(*source, ScrollSource::Wheel);
    }

    /// The finger map and the primary slot, which is all the translation
    /// remembers between messages.
    #[derive(Default)]
    struct Touch {
        fingers: FxHashMap<i32, (SurfaceId, f32, f32)>,
        primary: Option<i32>,
    }

    impl Touch {
        /// What this message asks of the surfaces. The instants are dropped:
        /// they come from the compositor's clock, which
        /// `an_events_time_is_read_as_a_distance_from_the_anchor` covers.
        fn send(&mut self, event: TouchEvent) -> Vec<(SurfaceId, Event)> {
            translate_touch(&mut self.fingers, &mut self.primary, event)
                .into_iter()
                .map(|(surface, _, event)| (surface, event))
                .collect()
        }
    }

    fn down(id: i32, surface: SurfaceId, x: f32, y: f32) -> TouchEvent {
        TouchEvent::Down {
            id,
            surface,
            at: Instant::now(),
            position: Point::new(x, y),
        }
    }

    fn motion(id: i32, x: f32, y: f32) -> TouchEvent {
        TouchEvent::Motion {
            id,
            at: Instant::now(),
            position: Point::new(x, y),
        }
    }

    fn up(id: i32) -> TouchEvent {
        TouchEvent::Up {
            id,
            at: Instant::now(),
        }
    }

    fn cancel() -> TouchEvent {
        TouchEvent::Cancel { at: untimed() }
    }

    /// The move-and-press a landing finger synthesizes, as the surface it went
    /// to and where — or a panic naming what arrived instead.
    ///
    /// The pointer kind is asserted here rather than in a test of its own
    /// because it is a property of every synthesized press: a scroller reads
    /// it to tell a finger dragging its content from a mouse doing the same
    /// (#429), so a fold that said `Mouse` would leave touch scrolling dead on
    /// a device with every test still green.
    fn press(events: &[(SurfaceId, Event)]) -> (SurfaceId, Option<Point>) {
        let [
            (
                moved_to,
                Event::MouseMove {
                    at: moved,
                    pointer: moved_by,
                },
            ),
            (
                pressed_on,
                Event::MouseDown {
                    at: pressed,
                    button,
                    pointer: pressed_by,
                },
            ),
        ] = events
        else {
            panic!("a landing finger moves then presses, got {events:?}");
        };
        assert_eq!(*button, MouseButton::Left, "a finger is a left button");
        assert_eq!(
            (*moved_by, *pressed_by),
            (PointerKind::Finger, PointerKind::Finger),
            "and a finger, which is what the fold cannot say any other way"
        );
        assert_eq!(moved_to, pressed_on, "both to one surface");
        assert_eq!(moved, pressed, "and both at one place");
        (*pressed_on, *pressed)
    }

    /// The release-and-leave a lifted or cancelled finger synthesizes.
    fn release(events: &[(SurfaceId, Event)]) -> (SurfaceId, Option<Point>) {
        let [
            (released_on, Event::MouseUp { at, button }),
            (left, Event::MouseLeave),
        ] = events
        else {
            panic!("a leaving finger releases then un-hovers, got {events:?}");
        };
        assert_eq!(*button, MouseButton::Left);
        assert_eq!(released_on, left, "both to one surface");
        (*released_on, *at)
    }

    /// The whole of pointer emulation in one gesture: a finger landing is a
    /// move and a press, so hover and pressed state layers respond, and
    /// lifting it is a release and a leave — a tap is a click.
    #[test]
    fn a_tap_is_a_move_a_press_and_a_release() {
        let surface = SurfaceId::next();
        let mut touch = Touch::default();

        let landed = touch.send(down(0, surface, PX, PY));
        assert_eq!(
            press(&landed),
            (surface, Some(Point::new(PX, PY))),
            "the press lands where the finger did"
        );
        assert_eq!(touch.primary, Some(0), "and that finger drives the pointer");

        let lifted = touch.send(up(0));
        assert_eq!(
            release(&lifted),
            (surface, Some(Point::new(PX, PY))),
            "and the release is where it was last seen"
        );
        assert_eq!(touch.primary, None);
        assert!(touch.fingers.is_empty(), "the finger is forgotten");
    }

    /// Only one finger drives the pointer. A second one landing would
    /// otherwise press a second widget that nothing will release.
    #[test]
    fn a_second_finger_on_a_held_first_says_nothing() {
        let surface = SurfaceId::next();
        let mut touch = Touch::default();
        touch.send(down(0, surface, PX, PY));

        let second = touch.send(down(1, surface, 100.0, 200.0));
        assert!(
            second.is_empty(),
            "the second finger is silent, got {second:?}"
        );
        assert_eq!(touch.primary, Some(0), "and the first one still drives");
        assert_eq!(
            touch.fingers.get(&1).copied(),
            Some((surface, 100.0, 200.0)),
            "but it is remembered, so its own up can be matched"
        );
    }

    /// A non-primary finger moves without the pointer moving — and its
    /// position is tracked anyway, because it is the point a cancel would
    /// release it at.
    #[test]
    fn a_non_primary_fingers_motion_says_nothing_but_is_remembered() {
        let surface = SurfaceId::next();
        let mut touch = Touch::default();
        touch.send(down(0, surface, PX, PY));
        touch.send(down(1, surface, 100.0, 200.0));

        let moved = touch.send(motion(1, 110.0, 210.0));
        assert!(
            moved.is_empty(),
            "the pointer does not follow, got {moved:?}"
        );
        assert_eq!(
            touch.fingers.get(&1).copied(),
            Some((surface, 110.0, 210.0)),
            "the stored position still moved"
        );
        assert_eq!(
            touch.fingers.get(&0).copied(),
            Some((surface, PX, PY)),
            "and the primary finger did not"
        );
    }

    /// Where a drag goes is decided at `down`. `wl_touch.motion` names no
    /// surface, and the widget that took the press is the one that has to see
    /// the release — so a finger sliding past the edge keeps reporting to the
    /// surface it landed on.
    #[test]
    fn a_finger_that_slides_off_keeps_delivering_where_it_landed() {
        let landed_on = SurfaceId::next();
        let mut touch = Touch::default();
        touch.send(down(0, landed_on, PX, PY));

        let slid = touch.send(motion(0, -40.0, 900.0));
        let [(surface, Event::MouseMove { at, pointer })] = slid.as_slice() else {
            panic!("the primary finger moves the pointer, got {slid:?}");
        };
        assert_eq!(*surface, landed_on, "off the surface, still the surface's");
        assert_eq!(*at, Some(Point::new(-40.0, 900.0)));
        assert_eq!(*pointer, PointerKind::Finger, "and still a finger");

        let lifted = touch.send(up(0));
        assert_eq!(
            release(&lifted),
            (landed_on, Some(Point::new(-40.0, 900.0))),
            "and so is the release, at the point it slid to"
        );
    }

    /// The gesture is not ours any more. The press has to end, and it must end
    /// *without* being a click: a cancelled finger is still inside the widget
    /// it pressed, so a synthesized `MouseUp` would land inside the hit and
    /// `interaction.rs` would call `on_click` — the compositor takes the
    /// gesture away and guido activates the button. `MouseLeave` alone is how
    /// this codebase already spells a press that ended without activating
    /// anything.
    ///
    /// Two callers reach it: `wl_touch.cancel`, and the seat losing its touch
    /// capability, where the device is what went away and no finger is ever
    /// lifting again. Neither activated anything, and both leave state a later
    /// gesture can be built on — the last thing this asserts.
    #[test]
    fn a_cancel_ends_the_press_without_clicking_and_forgets_every_finger() {
        let surface = SurfaceId::next();
        let mut touch = Touch::default();
        touch.send(down(0, surface, PX, PY));
        touch.send(down(1, surface, 100.0, 200.0));

        let cancelled = touch.send(cancel());
        assert!(
            matches!(cancelled.as_slice(), [(left, Event::MouseLeave)] if *left == surface),
            "a cancel is a leave and nothing else, got {cancelled:?}"
        );
        assert!(
            !cancelled
                .iter()
                .any(|(_, event)| matches!(event, Event::MouseUp { .. })),
            "and never a release, which is what a click is made of"
        );
        assert_eq!(touch.primary, None);
        assert!(
            touch.fingers.is_empty(),
            "every finger goes, not only the primary"
        );

        // Nothing is left over to make the next finger a second one: after a
        // touchscreen is unplugged and plugged back in, the first tap is a tap.
        let landed = touch.send(down(0, surface, PX, PY));
        assert_eq!(
            press(&landed),
            (surface, Some(Point::new(PX, PY))),
            "the next finger down drives the pointer again"
        );
        assert_eq!(touch.primary, Some(0));
    }

    /// A cancel can arrive with nothing pressed — the state
    /// `a_lifted_primary_does_not_promote_the_finger_still_down` leaves
    /// behind. There is no press to release, and the fingers still go.
    #[test]
    fn a_cancel_with_no_primary_finger_says_nothing_and_still_clears() {
        let surface = SurfaceId::next();
        let mut touch = Touch::default();
        touch.send(down(0, surface, PX, PY));
        touch.send(down(1, surface, 100.0, 200.0));
        touch.send(up(0));

        let cancelled = touch.send(cancel());
        assert!(
            cancelled.is_empty(),
            "no press was held, so nothing is released, got {cancelled:?}"
        );
        assert!(touch.fingers.is_empty(), "and the rest of the hand is gone");
    }

    /// An up for a down this client never saw. The release it would
    /// synthesize belongs to no surface and no position, so there is none.
    #[test]
    fn an_up_for_a_finger_that_was_never_down_says_nothing() {
        let mut touch = Touch::default();
        let stray = touch.send(up(7));
        assert!(stray.is_empty(), "got {stray:?}");
        assert_eq!(touch.primary, None);
    }

    /// Current behaviour, pinned rather than endorsed: when the primary finger
    /// lifts while a second is still on the glass, the second is not promoted.
    /// The pointer stays where it was until that finger is lifted and put back
    /// down. Changing it is its own issue with its own acceptance.
    #[test]
    fn a_lifted_primary_does_not_promote_the_finger_still_down() {
        let surface = SurfaceId::next();
        let mut touch = Touch::default();
        touch.send(down(0, surface, PX, PY));
        touch.send(down(1, surface, 100.0, 200.0));

        touch.send(up(0));
        assert_eq!(touch.primary, None, "nobody drives the pointer now");
        assert_eq!(
            touch.fingers.get(&1).copied(),
            Some((surface, 100.0, 200.0)),
            "though a finger is still down"
        );

        let moved = touch.send(motion(1, 120.0, 220.0));
        assert!(
            moved.is_empty(),
            "and moving it moves nothing, got {moved:?}"
        );
    }
}