input_pipeline/
mouse_binding.rs

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
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::input_device::{self, Handled, InputDeviceBinding, InputDeviceStatus, InputEvent};
use crate::utils::Position;
use crate::{metrics, mouse_model_database};
use anyhow::{format_err, Error};
use async_trait::async_trait;
use fidl_fuchsia_input_report as fidl_input_report;
use fidl_fuchsia_input_report::{InputDeviceProxy, InputReport};
use fuchsia_inspect::health::Reporter;
use fuchsia_inspect::ArrayProperty;
use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
use metrics_registry::*;
use std::collections::HashSet;

pub type MouseButton = u8;

/// Flag to indicate the scroll event is from device reporting precision delta.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum PrecisionScroll {
    /// Touchpad and some mouse able to report precision delta.
    Yes,
    /// Tick based mouse wheel.
    No,
}

/// A [`MouseLocation`] represents the mouse pointer location at the time of a pointer event.
#[derive(Copy, Clone, Debug, PartialEq)]
pub enum MouseLocation {
    /// A mouse movement relative to its current position.
    Relative(RelativeLocation),

    /// An absolute position, in device coordinates.
    Absolute(Position),
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub enum MousePhase {
    Down,  // One or more buttons were newly pressed.
    Move,  // The mouse moved with no change in button state.
    Up,    // One or more buttons were newly released.
    Wheel, // Mouse wheel is rotating.
}

/// A [`RelativeLocation`] contains the relative mouse pointer location at the time of a pointer event.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct RelativeLocation {
    /// A pointer location in millimeters.
    pub millimeters: Position,
}

impl Default for RelativeLocation {
    fn default() -> Self {
        RelativeLocation { millimeters: Position::zero() }
    }
}

/// [`RawWheelDelta`] is the wheel delta from driver or gesture arena.
#[derive(Clone, Debug, PartialEq)]
pub enum RawWheelDelta {
    /// For tick based mouse wheel, driver will report how many ticks rotated in i64.
    Ticks(i64),
    /// For Touchpad, gesture arena will compute how many swipe distance in mm in f32.
    Millimeters(f32),
}

/// A [`WheelDelta`] contains raw wheel delta from driver or gesture arena
/// and scaled wheel delta in physical pixels.
#[derive(Clone, Debug, PartialEq)]

pub struct WheelDelta {
    pub raw_data: RawWheelDelta,
    pub physical_pixel: Option<f32>,
}

/// A [`MouseEvent`] represents a pointer event with a specified phase, and the buttons
/// involved in said phase. The supported phases for mice include Up, Down, and Move.
///
/// # Example
/// The following MouseEvent represents a relative movement of 40 units in the x axis
/// and 20 units in the y axis while holding the primary button (1) down.
///
/// ```
/// let mouse_device_event = input_device::InputDeviceEvent::Mouse(MouseEvent::new(
///     MouseLocation::Relative(RelativePosition {
///       millimeters: Position { x: 4.0, y: 2.0 },
///     }),
///     Some(1),
///     Some(1),
///     MousePhase::Move,
///     HashSet::from_iter(vec![1]).into_iter()),
///     HashSet::from_iter(vec![1]).into_iter()),,
/// ));
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct MouseEvent {
    /// The mouse location.
    pub location: MouseLocation,

    /// The mouse wheel rotated delta in vertical.
    pub wheel_delta_v: Option<WheelDelta>,

    /// The mouse wheel rotated delta in horizontal.
    pub wheel_delta_h: Option<WheelDelta>,

    /// The mouse device reports precision scroll delta.
    pub is_precision_scroll: Option<PrecisionScroll>,

    /// The phase of the [`buttons`] associated with this input event.
    pub phase: MousePhase,

    /// The buttons relevant to this event.
    pub affected_buttons: HashSet<MouseButton>,

    /// The complete button state including this event.
    pub pressed_buttons: HashSet<MouseButton>,
}

impl MouseEvent {
    /// Creates a new [`MouseEvent`].
    ///
    /// # Parameters
    /// - `location`: The mouse location.
    /// - `phase`: The phase of the [`buttons`] associated with this input event.
    /// - `buttons`: The buttons relevant to this event.
    pub fn new(
        location: MouseLocation,
        wheel_delta_v: Option<WheelDelta>,
        wheel_delta_h: Option<WheelDelta>,
        phase: MousePhase,
        affected_buttons: HashSet<MouseButton>,
        pressed_buttons: HashSet<MouseButton>,
        is_precision_scroll: Option<PrecisionScroll>,
    ) -> MouseEvent {
        MouseEvent {
            location,
            wheel_delta_v,
            wheel_delta_h,
            phase,
            affected_buttons,
            pressed_buttons,
            is_precision_scroll,
        }
    }

    pub fn record_inspect(&self, node: &fuchsia_inspect::Node) {
        match self.location {
            MouseLocation::Relative(pos) => {
                node.record_child("location_relative", move |location_node| {
                    location_node.record_double("x", f64::from(pos.millimeters.x));
                    location_node.record_double("y", f64::from(pos.millimeters.y));
                })
            }
            MouseLocation::Absolute(pos) => {
                node.record_child("location_absolute", move |location_node| {
                    location_node.record_double("x", f64::from(pos.x));
                    location_node.record_double("y", f64::from(pos.y));
                })
            }
        };

        if let Some(wheel_delta_v) = &self.wheel_delta_v {
            node.record_child("wheel_delta_v", move |wheel_delta_v_node| {
                match wheel_delta_v.raw_data {
                    RawWheelDelta::Ticks(ticks) => wheel_delta_v_node.record_int("ticks", ticks),
                    RawWheelDelta::Millimeters(mm) => {
                        wheel_delta_v_node.record_double("millimeters", f64::from(mm))
                    }
                }
                if let Some(physical_pixel) = wheel_delta_v.physical_pixel {
                    wheel_delta_v_node.record_double("physical_pixel", f64::from(physical_pixel));
                }
            });
        }

        if let Some(wheel_delta_h) = &self.wheel_delta_h {
            node.record_child("wheel_delta_h", move |wheel_delta_h_node| {
                match wheel_delta_h.raw_data {
                    RawWheelDelta::Ticks(ticks) => wheel_delta_h_node.record_int("ticks", ticks),
                    RawWheelDelta::Millimeters(mm) => {
                        wheel_delta_h_node.record_double("millimeters", f64::from(mm))
                    }
                }
                if let Some(physical_pixel) = wheel_delta_h.physical_pixel {
                    wheel_delta_h_node.record_double("physical_pixel", f64::from(physical_pixel));
                }
            });
        }

        if let Some(is_precision_scroll) = self.is_precision_scroll {
            match is_precision_scroll {
                PrecisionScroll::Yes => node.record_string("is_precision_scroll", "yes"),
                PrecisionScroll::No => node.record_string("is_precision_scroll", "no"),
            }
        }

        match self.phase {
            MousePhase::Down => node.record_string("phase", "down"),
            MousePhase::Move => node.record_string("phase", "move"),
            MousePhase::Up => node.record_string("phase", "up"),
            MousePhase::Wheel => node.record_string("phase", "wheel"),
        }

        let affected_buttons_node =
            node.create_uint_array("affected_buttons", self.affected_buttons.len());
        self.affected_buttons.iter().enumerate().for_each(|(i, button)| {
            affected_buttons_node.set(i, *button);
        });
        node.record(affected_buttons_node);

        let pressed_buttons_node =
            node.create_uint_array("pressed_buttons", self.pressed_buttons.len());
        self.pressed_buttons.iter().enumerate().for_each(|(i, button)| {
            pressed_buttons_node.set(i, *button);
        });
        node.record(pressed_buttons_node);
    }
}

/// A [`MouseBinding`] represents a connection to a mouse input device.
///
/// The [`MouseBinding`] parses and exposes mouse descriptor properties (e.g., the range of
/// possible x values) for the device it is associated with. It also parses [`InputReport`]s
/// from the device, and sends them to the device binding owner over `event_sender`.
pub struct MouseBinding {
    /// The channel to stream InputEvents to.
    event_sender: UnboundedSender<input_device::InputEvent>,

    /// Holds information about this device.
    device_descriptor: MouseDeviceDescriptor,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct MouseDeviceDescriptor {
    /// The id of the connected mouse input device.
    pub device_id: u32,

    /// The range of possible x values of absolute mouse positions reported by this device.
    pub absolute_x_range: Option<fidl_input_report::Range>,

    /// The range of possible y values of absolute mouse positions reported by this device.
    pub absolute_y_range: Option<fidl_input_report::Range>,

    /// The range of possible vertical wheel delta reported by this device.
    pub wheel_v_range: Option<fidl_input_report::Axis>,

    /// The range of possible horizontal wheel delta reported by this device.
    pub wheel_h_range: Option<fidl_input_report::Axis>,

    /// This is a vector of ids for the mouse buttons.
    pub buttons: Option<Vec<MouseButton>>,

    /// This is the conversion factor between counts and millimeters for the
    /// connected mouse input device.
    pub counts_per_mm: u32,
}

#[async_trait]
impl input_device::InputDeviceBinding for MouseBinding {
    fn input_event_sender(&self) -> UnboundedSender<input_device::InputEvent> {
        self.event_sender.clone()
    }

    fn get_device_descriptor(&self) -> input_device::InputDeviceDescriptor {
        input_device::InputDeviceDescriptor::Mouse(self.device_descriptor.clone())
    }
}

impl MouseBinding {
    /// Creates a new [`InputDeviceBinding`] from the `device_proxy`.
    ///
    /// The binding will start listening for input reports immediately and send new InputEvents
    /// to the device binding owner over `input_event_sender`.
    ///
    /// # Parameters
    /// - `device_proxy`: The proxy to bind the new [`InputDeviceBinding`] to.
    /// - `device_id`: The id of the connected mouse device.
    /// - `input_event_sender`: The channel to send new InputEvents to.
    /// - `device_node`: The inspect node for this device binding
    /// - `metrics_logger`: The metrics logger.
    ///
    /// # Errors
    /// If there was an error binding to the proxy.
    pub async fn new(
        device_proxy: InputDeviceProxy,
        device_id: u32,
        input_event_sender: UnboundedSender<input_device::InputEvent>,
        device_node: fuchsia_inspect::Node,
        metrics_logger: metrics::MetricsLogger,
    ) -> Result<Self, Error> {
        let (device_binding, mut inspect_status) =
            Self::bind_device(&device_proxy, device_id, input_event_sender, device_node).await?;
        inspect_status.health_node.set_ok();
        input_device::initialize_report_stream(
            device_proxy,
            device_binding.get_device_descriptor(),
            device_binding.input_event_sender(),
            inspect_status,
            metrics_logger,
            Self::process_reports,
        );

        Ok(device_binding)
    }

    /// Binds the provided input device to a new instance of `Self`.
    ///
    /// # Parameters
    /// - `device`: The device to use to initialize the binding.
    /// - `device_id`: The id of the connected mouse device.
    /// - `input_event_sender`: The channel to send new InputEvents to.
    /// - `device_node`: The inspect node for this device binding
    ///
    /// # Errors
    /// If the device descriptor could not be retrieved, or the descriptor could
    /// not be parsed correctly.
    async fn bind_device(
        device: &InputDeviceProxy,
        device_id: u32,
        input_event_sender: UnboundedSender<input_device::InputEvent>,
        device_node: fuchsia_inspect::Node,
    ) -> Result<(Self, InputDeviceStatus), Error> {
        let mut input_device_status = InputDeviceStatus::new(device_node);
        let device_descriptor: fidl_input_report::DeviceDescriptor = match device
            .get_descriptor()
            .await
        {
            Ok(descriptor) => descriptor,
            Err(_) => {
                input_device_status.health_node.set_unhealthy("Could not get device descriptor.");
                return Err(format_err!("Could not get descriptor for device_id: {}", device_id));
            }
        };

        let mouse_descriptor = device_descriptor.mouse.ok_or_else(|| {
            input_device_status
                .health_node
                .set_unhealthy("DeviceDescriptor does not have a MouseDescriptor.");
            format_err!("DeviceDescriptor does not have a MouseDescriptor")
        })?;

        let mouse_input_descriptor = mouse_descriptor.input.ok_or_else(|| {
            input_device_status
                .health_node
                .set_unhealthy("MouseDescriptor does not have a MouseInputDescriptor.");
            format_err!("MouseDescriptor does not have a MouseInputDescriptor")
        })?;

        let model = mouse_model_database::db::get_mouse_model(device_descriptor.device_information);

        let device_descriptor: MouseDeviceDescriptor = MouseDeviceDescriptor {
            device_id,
            absolute_x_range: mouse_input_descriptor.position_x.map(|axis| axis.range),
            absolute_y_range: mouse_input_descriptor.position_y.map(|axis| axis.range),
            wheel_v_range: mouse_input_descriptor.scroll_v,
            wheel_h_range: mouse_input_descriptor.scroll_h,
            buttons: mouse_input_descriptor.buttons,
            counts_per_mm: model.counts_per_mm,
        };

        Ok((
            MouseBinding { event_sender: input_event_sender, device_descriptor },
            input_device_status,
        ))
    }

    /// Parses an [`InputReport`] into one or more [`InputEvent`]s.
    ///
    /// The [`InputEvent`]s are sent to the device binding owner via [`input_event_sender`].
    ///
    /// # Parameters
    /// `report`: The incoming [`InputReport`].
    /// `previous_report`: The previous [`InputReport`] seen for the same device. This can be
    ///                    used to determine, for example, which keys are no longer present in
    ///                    a keyboard report to generate key released events. If `None`, no
    ///                    previous report was found.
    /// `device_descriptor`: The descriptor for the input device generating the input reports.
    /// `input_event_sender`: The sender for the device binding's input event stream.
    ///
    /// # Returns
    /// An [`InputReport`] which will be passed to the next call to [`process_reports`], as
    /// [`previous_report`]. If `None`, the next call's [`previous_report`] will be `None`.
    /// A [`UnboundedReceiver<InputEvent>`] which will poll asynchronously generated events to be
    /// recorded by `inspect_status` in `input_device::initialize_report_stream()`. If device
    /// binding does not generate InputEvents asynchronously, this will be `None`.
    fn process_reports(
        report: InputReport,
        previous_report: Option<InputReport>,
        device_descriptor: &input_device::InputDeviceDescriptor,
        input_event_sender: &mut UnboundedSender<input_device::InputEvent>,
        inspect_status: &InputDeviceStatus,
        metrics_logger: &metrics::MetricsLogger,
    ) -> (Option<InputReport>, Option<UnboundedReceiver<InputEvent>>) {
        inspect_status.count_received_report(&report);
        // Input devices can have multiple types so ensure `report` is a MouseInputReport.
        let mouse_report: &fidl_input_report::MouseInputReport = match &report.mouse {
            Some(mouse) => mouse,
            None => {
                inspect_status.count_filtered_report();
                return (previous_report, None);
            }
        };

        let previous_buttons: HashSet<MouseButton> =
            buttons_from_optional_report(&previous_report.as_ref());
        let current_buttons: HashSet<MouseButton> = buttons_from_report(&report);

        // Send a Down event with:
        // * affected_buttons: the buttons that were pressed since the previous report,
        //   i.e. that are in the current report, but were not in the previous report.
        // * pressed_buttons: the full set of currently pressed buttons, including the
        //   recently pressed ones (affected_buttons).
        send_mouse_event(
            MouseLocation::Relative(Default::default()),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            MousePhase::Down,
            current_buttons.difference(&previous_buttons).cloned().collect(),
            current_buttons.clone(),
            device_descriptor,
            input_event_sender,
            inspect_status,
            metrics_logger,
        );

        let counts_per_mm = match device_descriptor {
            input_device::InputDeviceDescriptor::Mouse(ds) => ds.counts_per_mm,
            _ => {
                metrics_logger.log_error(
                    InputPipelineErrorMetricDimensionEvent::MouseDescriptionNotMouse,
                    "mouse_binding::process_reports got device_descriptor not mouse".to_string(),
                );
                mouse_model_database::db::DEFAULT_COUNTS_PER_MM
            }
        };

        // Create a location for the move event. Use the absolute position if available.
        let location = if let (Some(position_x), Some(position_y)) =
            (mouse_report.position_x, mouse_report.position_y)
        {
            MouseLocation::Absolute(Position { x: position_x as f32, y: position_y as f32 })
        } else {
            let movement_x = mouse_report.movement_x.unwrap_or_default() as f32;
            let movement_y = mouse_report.movement_y.unwrap_or_default() as f32;
            MouseLocation::Relative(RelativeLocation {
                millimeters: Position {
                    x: movement_x / counts_per_mm as f32,
                    y: movement_y / counts_per_mm as f32,
                },
            })
        };

        // Send a Move event with buttons from both the current report and the previous report.
        // * affected_buttons and pressed_buttons are identical in this case, since the full
        //   set of currently pressed buttons are the same set affected by the event.
        send_mouse_event(
            location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            MousePhase::Move,
            current_buttons.union(&previous_buttons).cloned().collect(),
            current_buttons.union(&previous_buttons).cloned().collect(),
            device_descriptor,
            input_event_sender,
            inspect_status,
            metrics_logger,
        );

        let wheel_delta_v = match mouse_report.scroll_v {
            None => None,
            Some(ticks) => {
                Some(WheelDelta { raw_data: RawWheelDelta::Ticks(ticks), physical_pixel: None })
            }
        };

        let wheel_delta_h = match mouse_report.scroll_h {
            None => None,
            Some(ticks) => {
                Some(WheelDelta { raw_data: RawWheelDelta::Ticks(ticks), physical_pixel: None })
            }
        };

        // Send a mouse wheel event.
        send_mouse_event(
            MouseLocation::Relative(Default::default()),
            wheel_delta_v,
            wheel_delta_h,
            MousePhase::Wheel,
            current_buttons.union(&previous_buttons).cloned().collect(),
            current_buttons.union(&previous_buttons).cloned().collect(),
            device_descriptor,
            input_event_sender,
            inspect_status,
            metrics_logger,
        );

        // Send an Up event with:
        // * affected_buttons: the buttons that were released since the previous report,
        //   i.e. that were in the previous report, but are not in the current report.
        // * pressed_buttons: the full set of currently pressed buttons, excluding the
        //   recently released ones (affected_buttons).
        send_mouse_event(
            MouseLocation::Relative(Default::default()),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            MousePhase::Up,
            previous_buttons.difference(&current_buttons).cloned().collect(),
            current_buttons.clone(),
            device_descriptor,
            input_event_sender,
            inspect_status,
            metrics_logger,
        );

        (Some(report), None)
    }
}

/// Sends an InputEvent over `sender`.
///
/// When no buttons are present, only [`MousePhase::Move`] events will
/// be sent.
///
/// # Parameters
/// - `location`: The mouse location.
/// - `wheel_delta_v`: The mouse wheel delta in vertical.
/// - `wheel_delta_h`: The mouse wheel delta in horizontal.
/// - `phase`: The phase of the [`buttons`] associated with the input event.
/// - `buttons`: The buttons relevant to the event.
/// - `device_descriptor`: The descriptor for the input device generating the input reports.
/// - `sender`: The stream to send the MouseEvent to.
fn send_mouse_event(
    location: MouseLocation,
    wheel_delta_v: Option<WheelDelta>,
    wheel_delta_h: Option<WheelDelta>,
    phase: MousePhase,
    affected_buttons: HashSet<MouseButton>,
    pressed_buttons: HashSet<MouseButton>,
    device_descriptor: &input_device::InputDeviceDescriptor,
    sender: &mut UnboundedSender<input_device::InputEvent>,
    inspect_status: &InputDeviceStatus,
    metrics_logger: &metrics::MetricsLogger,
) {
    // Only send Down/Up events when there are buttons affected.
    if (phase == MousePhase::Down || phase == MousePhase::Up) && affected_buttons.is_empty() {
        return;
    }

    // Don't send Move events when there is no relative movement.
    // However, absolute movement is always reported.
    if phase == MousePhase::Move && location == MouseLocation::Relative(Default::default()) {
        return;
    }

    // Only send wheel events when the delta has value.
    if phase == MousePhase::Wheel && wheel_delta_v.is_none() && wheel_delta_h.is_none() {
        return;
    }

    let event = input_device::InputEvent {
        device_event: input_device::InputDeviceEvent::Mouse(MouseEvent::new(
            location,
            wheel_delta_v,
            wheel_delta_h,
            phase,
            affected_buttons,
            pressed_buttons,
            match phase {
                MousePhase::Wheel => Some(PrecisionScroll::No),
                _ => None,
            },
        )),
        device_descriptor: device_descriptor.clone(),
        event_time: zx::MonotonicInstant::get(),
        handled: Handled::No,
        trace_id: None,
    };

    match sender.unbounded_send(event.clone()) {
        Err(e) => {
            metrics_logger.log_error(
                InputPipelineErrorMetricDimensionEvent::MouseFailedToSendEvent,
                std::format!("Failed to send MouseEvent with error: {:?}", e),
            );
        }
        _ => inspect_status.count_generated_event(event),
    }
}

/// Returns a u32 representation of `buttons`, where each u8 of `buttons` is an id of a button and
/// indicates the position of a bit to set.
///
/// This supports hashsets with numbers from 1 to fidl_input_report::MOUSE_MAX_NUM_BUTTONS.
///
/// # Parameters
/// - `buttons`: The hashset containing the position of bits to be set.
///
/// # Example
/// ```
/// let bits = get_u32_from_buttons(&HashSet::from_iter(vec![1, 3, 5]).into_iter());
/// assert_eq!(bits, 21 /* ...00010101 */)
/// ```
pub fn get_u32_from_buttons(buttons: &HashSet<MouseButton>) -> u32 {
    let mut bits: u32 = 0;
    for button in buttons {
        if *button > 0 && *button <= fidl_input_report::MOUSE_MAX_NUM_BUTTONS as u8 {
            bits = ((1 as u32) << *button - 1) | bits;
        }
    }

    bits
}

/// Returns the set of pressed buttons present in the given input report.
///
/// # Parameters
/// - `report`: The input report to parse the mouse buttons from.
fn buttons_from_report(input_report: &fidl_input_report::InputReport) -> HashSet<MouseButton> {
    buttons_from_optional_report(&Some(input_report))
}

/// Returns the set of pressed buttons present in the given input report.
///
/// # Parameters
/// - `report`: The input report to parse the mouse buttons from.
fn buttons_from_optional_report(
    input_report: &Option<&fidl_input_report::InputReport>,
) -> HashSet<MouseButton> {
    input_report
        .as_ref()
        .and_then(|unwrapped_report| unwrapped_report.mouse.as_ref())
        .and_then(|mouse_report| match &mouse_report.pressed_buttons {
            Some(buttons) => Some(HashSet::from_iter(buttons.iter().cloned())),
            None => None,
        })
        .unwrap_or_default()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing_utilities;
    use fuchsia_async as fasync;
    use futures::StreamExt;
    use pretty_assertions::assert_eq;

    const DEVICE_ID: u32 = 1;
    const COUNTS_PER_MM: u32 = 12;

    fn mouse_device_descriptor(device_id: u32) -> input_device::InputDeviceDescriptor {
        input_device::InputDeviceDescriptor::Mouse(MouseDeviceDescriptor {
            device_id,
            absolute_x_range: None,
            absolute_y_range: None,
            wheel_v_range: Some(fidl_fuchsia_input_report::Axis {
                range: fidl_input_report::Range { min: -1, max: 1 },
                unit: fidl_input_report::Unit {
                    type_: fidl_input_report::UnitType::Other,
                    exponent: 1,
                },
            }),
            wheel_h_range: Some(fidl_fuchsia_input_report::Axis {
                range: fidl_input_report::Range { min: -1, max: 1 },
                unit: fidl_input_report::Unit {
                    type_: fidl_input_report::UnitType::Other,
                    exponent: 1,
                },
            }),
            buttons: None,
            counts_per_mm: COUNTS_PER_MM,
        })
    }

    fn wheel_delta_ticks(delta: i64) -> Option<WheelDelta> {
        Some(WheelDelta { raw_data: RawWheelDelta::Ticks(delta), physical_pixel: None })
    }

    // Tests that the right u32 representation is returned from a vector of digits.
    #[test]
    fn get_u32_from_buttons_test() {
        let bits = get_u32_from_buttons(&HashSet::from_iter(vec![1, 3, 5].into_iter()));
        assert_eq!(bits, 21 /* 0...00010101 */)
    }

    // Tests that the right u32 representation is returned from a vector of digits that includes 0.
    #[test]
    fn get_u32_with_0_in_vector() {
        let bits = get_u32_from_buttons(&HashSet::from_iter(vec![0, 1, 3].into_iter()));
        assert_eq!(bits, 5 /* 0...00000101 */)
    }

    // Tests that the right u32 representation is returned from an empty vector.
    #[test]
    fn get_u32_with_empty_vector() {
        let bits = get_u32_from_buttons(&HashSet::new());
        assert_eq!(bits, 0 /* 0...00000000 */)
    }

    // Tests that the right u32 representation is returned from a vector containing std::u8::MAX.
    #[test]
    fn get_u32_with_u8_max_in_vector() {
        let bits = get_u32_from_buttons(&HashSet::from_iter(vec![1, 3, std::u8::MAX].into_iter()));
        assert_eq!(bits, 5 /* 0...00000101 */)
    }

    // Tests that the right u32 representation is returned from a vector containing the largest
    // button id possible.
    #[test]
    fn get_u32_with_max_mouse_buttons() {
        let bits = get_u32_from_buttons(&HashSet::from_iter(
            vec![1, 3, fidl_input_report::MOUSE_MAX_NUM_BUTTONS as MouseButton].into_iter(),
        ));
        assert_eq!(bits, 2147483653 /* 10...00000101 */)
    }

    /// Tests that a report containing no buttons but with movement generates a move event.
    #[fasync::run_singlethreaded(test)]
    async fn movement_without_button() {
        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position { x: 10.0, y: 16.0 },
            None, /* scroll_v */
            None, /* scroll_h */
            vec![],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report];
        let expected_events = vec![testing_utilities::create_mouse_event(
            MouseLocation::Relative(RelativeLocation {
                millimeters: Position {
                    x: 10.0 / COUNTS_PER_MM as f32,
                    y: 16.0 / COUNTS_PER_MM as f32,
                },
            }),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            MousePhase::Move,
            HashSet::new(),
            HashSet::new(),
            event_time_u64,
            &descriptor,
        )];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that a report containing a new mouse button generates a down event.
    #[fasync::run_singlethreaded(test)]
    async fn down_without_movement() {
        let mouse_button: MouseButton = 3;
        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![mouse_button],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report];
        let expected_events = vec![testing_utilities::create_mouse_event(
            MouseLocation::Relative(Default::default()),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            MousePhase::Down,
            HashSet::from_iter(vec![mouse_button].into_iter()),
            HashSet::from_iter(vec![mouse_button].into_iter()),
            event_time_u64,
            &descriptor,
        )];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that a report containing a new mouse button with movement generates a down event and a
    /// move event.
    #[fasync::run_singlethreaded(test)]
    async fn down_with_movement() {
        let mouse_button: MouseButton = 3;
        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position { x: 10.0, y: 16.0 },
            None, /* scroll_v */
            None, /* scroll_h */
            vec![mouse_button],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![mouse_button].into_iter()),
                HashSet::from_iter(vec![mouse_button].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(RelativeLocation {
                    millimeters: Position {
                        x: 10.0 / COUNTS_PER_MM as f32,
                        y: 16.0 / COUNTS_PER_MM as f32,
                    },
                }),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Move,
                HashSet::from_iter(vec![mouse_button].into_iter()),
                HashSet::from_iter(vec![mouse_button].into_iter()),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that a press and release of a mouse button without movement generates a down and up event.
    #[fasync::run_singlethreaded(test)]
    async fn down_up() {
        let button = 1;
        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![button],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::from_iter(vec![button].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Up,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that a press and release of a mouse button with movement generates down, move, and up events.
    #[fasync::run_singlethreaded(test)]
    async fn down_up_with_movement() {
        let button = 1;

        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![button],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position { x: 10.0, y: 16.0 },
            None, /* scroll_v */
            None, /* scroll_h */
            vec![],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::from_iter(vec![button].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(RelativeLocation {
                    millimeters: Position {
                        x: 10.0 / COUNTS_PER_MM as f32,
                        y: 16.0 / COUNTS_PER_MM as f32,
                    },
                }),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Move,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::from_iter(vec![button].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Up,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that a press, move, and release of a button generates down, move, and up events.
    /// This specifically tests the separate input report containing the movement, instead of sending
    /// the movement as part of the down or up events.
    #[fasync::run_singlethreaded(test)]
    async fn down_move_up() {
        let button = 1;

        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![button],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position { x: 10.0, y: 16.0 },
            None, /* scroll_v */
            None, /* scroll_h */
            vec![button],
            event_time_i64,
        );
        let third_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report, third_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::from_iter(vec![button].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(RelativeLocation {
                    millimeters: Position {
                        x: 10.0 / COUNTS_PER_MM as f32,
                        y: 16.0 / COUNTS_PER_MM as f32,
                    },
                }),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Move,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::from_iter(vec![button].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Up,
                HashSet::from_iter(vec![button].into_iter()),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that a report with absolute movement to {0, 0} generates a move event.
    #[fasync::run_until_stalled(test)]
    async fn absolute_movement_to_origin() {
        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![testing_utilities::create_mouse_input_report_absolute(
            Position::zero(),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            vec![],
            event_time_i64,
        )];
        let expected_events = vec![testing_utilities::create_mouse_event(
            MouseLocation::Absolute(Position { x: 0.0, y: 0.0 }),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            MousePhase::Move,
            HashSet::new(),
            HashSet::new(),
            event_time_u64,
            &descriptor,
        )];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that a report that contains both a relative movement and absolute position
    /// generates a move event to the absolute position.
    #[fasync::run_until_stalled(test)]
    async fn report_with_both_movement_and_position() {
        let relative_movement = Position { x: 5.0, y: 5.0 };
        let absolute_position = Position { x: 10.0, y: 10.0 };
        let expected_location = MouseLocation::Absolute(absolute_position);

        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![fidl_input_report::InputReport {
            event_time: Some(event_time_i64),
            keyboard: None,
            mouse: Some(fidl_input_report::MouseInputReport {
                movement_x: Some(relative_movement.x as i64),
                movement_y: Some(relative_movement.y as i64),
                position_x: Some(absolute_position.x as i64),
                position_y: Some(absolute_position.y as i64),
                scroll_h: None,
                scroll_v: None,
                pressed_buttons: None,
                ..Default::default()
            }),
            touch: None,
            sensor: None,
            consumer_control: None,
            trace_id: None,
            ..Default::default()
        }];
        let expected_events = vec![testing_utilities::create_mouse_event(
            expected_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            MousePhase::Move,
            HashSet::new(),
            HashSet::new(),
            event_time_u64,
            &descriptor,
        )];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that two separate button presses generate two separate down events with differing
    /// sets of `affected_buttons` and `pressed_buttons`.
    #[fasync::run_singlethreaded(test)]
    async fn down_down() {
        const PRIMARY_BUTTON: u8 = 1;
        const SECONDARY_BUTTON: u8 = 2;

        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![PRIMARY_BUTTON],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![PRIMARY_BUTTON, SECONDARY_BUTTON],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![SECONDARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON, SECONDARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Tests that two staggered button presses followed by stagged releases generate four mouse
    /// events with distinct `affected_buttons` and `pressed_buttons`.
    /// Specifically, we test and expect the following in order:
    /// | Action           | MousePhase | `affected_buttons` | `pressed_buttons` |
    /// | ---------------- | ---------- | ------------------ | ----------------- |
    /// | Press button 1   | Down       | [1]                | [1]               |
    /// | Press button 2   | Down       | [2]                | [1, 2]            |
    /// | Release button 1 | Up         | [1]                | [2]               |
    /// | Release button 2 | Up         | [2]                | []                |
    #[fasync::run_singlethreaded(test)]
    async fn down_down_up_up() {
        const PRIMARY_BUTTON: u8 = 1;
        const SECONDARY_BUTTON: u8 = 2;

        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![PRIMARY_BUTTON],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![PRIMARY_BUTTON, SECONDARY_BUTTON],
            event_time_i64,
        );
        let third_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![SECONDARY_BUTTON],
            event_time_i64,
        );
        let fourth_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![],
            event_time_i64,
        );
        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report, third_report, fourth_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![SECONDARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON, SECONDARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Up,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![SECONDARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Up,
                HashSet::from_iter(vec![SECONDARY_BUTTON].into_iter()),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Test simple scroll in vertical and horizontal.
    #[fasync::run_singlethreaded(test)]
    async fn scroll() {
        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            Some(1),
            None,
            vec![],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None,
            Some(1),
            vec![],
            event_time_i64,
        );

        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                wheel_delta_ticks(1),
                None,
                Some(PrecisionScroll::No),
                MousePhase::Wheel,
                HashSet::new(),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None,
                wheel_delta_ticks(1),
                Some(PrecisionScroll::No),
                MousePhase::Wheel,
                HashSet::new(),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Test button down -> scroll -> button up -> continue scroll.
    #[fasync::run_singlethreaded(test)]
    async fn down_scroll_up_scroll() {
        const PRIMARY_BUTTON: u8 = 1;

        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![PRIMARY_BUTTON],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            Some(1),
            None,
            vec![PRIMARY_BUTTON],
            event_time_i64,
        );
        let third_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            None, /* scroll_v */
            None, /* scroll_h */
            vec![],
            event_time_i64,
        );
        let fourth_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            Some(1),
            None,
            vec![],
            event_time_i64,
        );

        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report, third_report, fourth_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                wheel_delta_ticks(1),
                None,
                Some(PrecisionScroll::No),
                MousePhase::Wheel,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Up,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                wheel_delta_ticks(1),
                None,
                Some(PrecisionScroll::No),
                MousePhase::Wheel,
                HashSet::new(),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }

    /// Test button down with scroll -> button up with scroll -> scroll.
    #[fasync::run_singlethreaded(test)]
    async fn down_scroll_bundle_up_scroll_bundle() {
        const PRIMARY_BUTTON: u8 = 1;

        let (event_time_i64, event_time_u64) = testing_utilities::event_times();
        let first_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            Some(1),
            None,
            vec![PRIMARY_BUTTON],
            event_time_i64,
        );
        let second_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            Some(1),
            None,
            vec![],
            event_time_i64,
        );
        let third_report = testing_utilities::create_mouse_input_report_relative(
            Position::zero(),
            Some(1),
            None,
            vec![],
            event_time_i64,
        );

        let descriptor = mouse_device_descriptor(DEVICE_ID);

        let input_reports = vec![first_report, second_report, third_report];
        let expected_events = vec![
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Down,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                wheel_delta_ticks(1),
                None,
                Some(PrecisionScroll::No),
                MousePhase::Wheel,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                wheel_delta_ticks(1),
                None,
                Some(PrecisionScroll::No),
                MousePhase::Wheel,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                MousePhase::Up,
                HashSet::from_iter(vec![PRIMARY_BUTTON].into_iter()),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
            testing_utilities::create_mouse_event(
                MouseLocation::Relative(Default::default()),
                wheel_delta_ticks(1),
                None,
                Some(PrecisionScroll::No),
                MousePhase::Wheel,
                HashSet::new(),
                HashSet::new(),
                event_time_u64,
                &descriptor,
            ),
        ];

        assert_input_report_sequence_generates_events!(
            input_reports: input_reports,
            expected_events: expected_events,
            device_descriptor: descriptor,
            device_type: MouseBinding,
        );
    }
}