input_pipeline/
mouse_injector_handler.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
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
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
// Copyright 2021 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.

#![warn(clippy::await_holding_refcell_ref)]

use crate::input_handler::{InputHandler, InputHandlerStatus};
use crate::utils::{CursorMessage, Position, Size};
use crate::{input_device, metrics, mouse_binding};
use anyhow::{anyhow, Context, Error, Result};
use async_trait::async_trait;
use async_utils::hanging_get::client::HangingGetStream;
use fidl::endpoints::create_proxy;
use fidl_fuchsia_input_report::Range;
use fuchsia_component::client::connect_to_protocol;
use fuchsia_inspect::health::Reporter;
use futures::channel::mpsc::Sender;
use futures::stream::StreamExt;
use futures::SinkExt;
use metrics_registry::*;
use std::cell::{Ref, RefCell, RefMut};
use std::collections::HashMap;
use std::rc::Rc;
use {
    fidl_fuchsia_input_interaction_observation as interaction_observation,
    fidl_fuchsia_ui_pointerinjector as pointerinjector,
    fidl_fuchsia_ui_pointerinjector_configuration as pointerinjector_config,
};

/// Each mm of physical movement by the mouse translates to the cursor moving
/// on the display by 10 logical pixels.
/// Because pointer_display_scale_handler scaled for device pixel ratio, here
/// only need to apply mm * logical pixel scale factor to get physical pixel.
/// TODO(https://fxbug.dev/42066909): need to revisit this
/// 1. allow users to adjust how fast the mouse move.
/// 2. allow different value per monitor model.
const MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL: f32 = 10.0;

/// A [`MouseInjectorHandler`] parses mouse events and forwards them to Scenic through the
/// fidl_fuchsia_pointerinjector protocols.
pub struct MouseInjectorHandler {
    /// The mutable fields of this handler.
    mutable_state: RefCell<MutableState>,

    /// The scope and coordinate system of injection.
    /// See [`fidl_fuchsia_pointerinjector::Context`] for more details.
    context_view_ref: fidl_fuchsia_ui_views::ViewRef,

    /// The region where dispatch is attempted for injected events.
    /// See [`fidl_fuchsia_pointerinjector::Target`] for more details.
    target_view_ref: fidl_fuchsia_ui_views::ViewRef,

    /// The maximum position sent to clients, used to bound relative movements
    /// and scale absolute positions from device coordinates.
    max_position: Position,

    /// The FIDL proxy to register new injectors.
    injector_registry_proxy: pointerinjector::RegistryProxy,

    /// The FIDL proxy used to get configuration details for pointer injection.
    configuration_proxy: pointerinjector_config::SetupProxy,

    /// The inventory of this handler's Inspect status.
    pub inspect_status: InputHandlerStatus,

    metrics_logger: metrics::MetricsLogger,

    /// The FIDL proxy used to report mouse activity to the activity service.
    aggregator_proxy: interaction_observation::AggregatorProxy,
}

struct MutableState {
    /// A rectangular region that directs injected events into a target.
    /// See fidl_fuchsia_pointerinjector::Viewport for more details.
    viewport: Option<pointerinjector::Viewport>,

    /// The injectors registered with Scenic, indexed by their device ids.
    injectors: HashMap<u32, pointerinjector::DeviceProxy>,

    /// The current position.
    current_position: Position,

    /// A [`Sender`] used to communicate the current cursor state.
    cursor_message_sender: Sender<CursorMessage>,
}

#[async_trait(?Send)]
impl InputHandler for MouseInjectorHandler {
    async fn handle_input_event(
        self: Rc<Self>,
        mut input_event: input_device::InputEvent,
    ) -> Vec<input_device::InputEvent> {
        match input_event {
            input_device::InputEvent {
                device_event: input_device::InputDeviceEvent::Mouse(ref mouse_event),
                device_descriptor:
                    input_device::InputDeviceDescriptor::Mouse(ref mouse_device_descriptor),
                event_time,
                handled: input_device::Handled::No,
                trace_id: _,
            } => {
                self.inspect_status
                    .count_received_event(input_device::InputEvent::from(input_event.clone()));
                // TODO(https://fxbug.dev/42171756): Investigate latency introduced by waiting for update_cursor_renderer
                if let Err(e) =
                    self.update_cursor_renderer(mouse_event, &mouse_device_descriptor).await
                {
                    self.metrics_logger.log_error(
                        InputPipelineErrorMetricDimensionEvent::MouseInjectorUpdateCursorRendererFailed,
                        std::format!("update_cursor_renderer failed: {}", e));
                }

                // Create a new injector if this is the first time seeing device_id.
                if let Err(e) = self
                    .ensure_injector_registered(&mouse_event, &mouse_device_descriptor, event_time)
                    .await
                {
                    self.metrics_logger.log_error(
                        InputPipelineErrorMetricDimensionEvent::MouseInjectorEnsureInjectorRegisteredFailed,
                        std::format!("ensure_injector_registered failed: {}", e));
                }

                // Handle the event.
                if let Err(e) = self
                    .send_event_to_scenic(&mouse_event, &mouse_device_descriptor, event_time)
                    .await
                {
                    self.metrics_logger.log_error(
                        InputPipelineErrorMetricDimensionEvent::MouseInjectorSendEventToScenicFailed,
                        std::format!("send_event_to_scenic failed: {}", e));
                }

                // Report the event to the Activity Service.
                if let Err(e) = self.report_mouse_activity(event_time).await {
                    tracing::error!("report_mouse_activity failed: {}", e);
                }

                // Consume the input event.
                input_event.handled = input_device::Handled::Yes;
                self.inspect_status.count_handled_event();
            }
            _ => {}
        }
        vec![input_event]
    }

    fn set_handler_healthy(self: std::rc::Rc<Self>) {
        self.inspect_status.health_node.borrow_mut().set_ok();
    }

    fn set_handler_unhealthy(self: std::rc::Rc<Self>, msg: &str) {
        self.inspect_status.health_node.borrow_mut().set_unhealthy(msg);
    }
}

impl MouseInjectorHandler {
    /// Creates a new mouse handler that holds mouse pointer injectors.
    /// The caller is expected to spawn a task to continually watch for updates to the viewport.
    /// Example:
    /// let handler = MouseInjectorHandler::new(display_size).await?;
    /// fasync::Task::local(handler.clone().watch_viewport()).detach();
    ///
    /// # Parameters
    /// - `display_size`: The size of the associated display.
    /// - `cursor_message_sender`: A [`Sender`] used to communicate the current cursor state.
    ///
    /// # Errors
    /// If unable to connect to pointerinjector protocols.
    pub async fn new(
        display_size: Size,
        cursor_message_sender: Sender<CursorMessage>,
        input_handlers_node: &fuchsia_inspect::Node,
        metrics_logger: metrics::MetricsLogger,
    ) -> Result<Rc<Self>, Error> {
        let configuration_proxy = connect_to_protocol::<pointerinjector_config::SetupMarker>()?;
        let injector_registry_proxy = connect_to_protocol::<pointerinjector::RegistryMarker>()?;
        let aggregator_proxy = connect_to_protocol::<interaction_observation::AggregatorMarker>()?;

        Self::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            display_size,
            cursor_message_sender,
            input_handlers_node,
            metrics_logger,
        )
        .await
    }

    /// Creates a new mouse handler that holds mouse pointer injectors.
    /// The caller is expected to spawn a task to continually watch for updates to the viewport.
    /// Example:
    /// let handler = MouseInjectorHandler::new_with_config_proxy(config_proxy, display_size).await?;
    /// fasync::Task::local(handler.clone().watch_viewport()).detach();
    ///
    /// # Parameters
    /// - `configuration_proxy`: A proxy used to get configuration details for pointer
    ///    injection.
    /// - `display_size`: The size of the associated display.
    /// - `cursor_message_sender`: A [`Sender`] used to communicate the current cursor state.
    ///
    /// # Errors
    /// If unable to get injection view refs from `configuration_proxy`.
    /// If unable to connect to pointerinjector Registry protocol.
    pub async fn new_with_config_proxy(
        configuration_proxy: pointerinjector_config::SetupProxy,
        display_size: Size,
        cursor_message_sender: Sender<CursorMessage>,
        input_handlers_node: &fuchsia_inspect::Node,
        metrics_logger: metrics::MetricsLogger,
    ) -> Result<Rc<Self>, Error> {
        let aggregator_proxy = connect_to_protocol::<interaction_observation::AggregatorMarker>()?;
        let injector_registry_proxy = connect_to_protocol::<pointerinjector::RegistryMarker>()?;
        Self::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            display_size,
            cursor_message_sender,
            input_handlers_node,
            metrics_logger,
        )
        .await
    }

    fn inner(&self) -> Ref<'_, MutableState> {
        self.mutable_state.borrow()
    }

    fn inner_mut(&self) -> RefMut<'_, MutableState> {
        self.mutable_state.borrow_mut()
    }

    /// Creates a new mouse handler that holds mouse pointer injectors.
    /// The caller is expected to spawn a task to continually watch for updates to the viewport.
    /// Example:
    /// let handler = MouseInjectorHandler::new_handler(None, None, display_size).await?;
    /// fasync::Task::local(handler.clone().watch_viewport()).detach();
    ///
    /// # Parameters
    /// - `aggregator_proxy`: A proxy used to report to the activity service
    /// - `configuration_proxy`: A proxy used to get configuration details for pointer
    ///    injection.
    /// - `injector_registry_proxy`: A proxy used to register new pointer injectors.
    /// - `display_size`: The size of the associated display.
    /// - `cursor_message_sender`: A [`Sender`] used to communicate the current cursor state.
    ///
    /// # Errors
    /// If unable to get injection view refs from `configuration_proxy`.
    async fn new_handler(
        aggregator_proxy: interaction_observation::AggregatorProxy,
        configuration_proxy: pointerinjector_config::SetupProxy,
        injector_registry_proxy: pointerinjector::RegistryProxy,
        display_size: Size,
        cursor_message_sender: Sender<CursorMessage>,
        input_handlers_node: &fuchsia_inspect::Node,
        metrics_logger: metrics::MetricsLogger,
    ) -> Result<Rc<Self>, Error> {
        // Get the context and target views to inject into.
        let (context_view_ref, target_view_ref) = configuration_proxy.get_view_refs().await?;
        let inspect_status = InputHandlerStatus::new(
            input_handlers_node,
            "mouse_injector_handler",
            /* generates_events */ false,
        );
        let handler = Rc::new(Self {
            mutable_state: RefCell::new(MutableState {
                viewport: None,
                injectors: HashMap::new(),
                // Initially centered.
                current_position: Position {
                    x: display_size.width / 2.0,
                    y: display_size.height / 2.0,
                },
                cursor_message_sender,
            }),
            context_view_ref,
            target_view_ref,
            max_position: Position { x: display_size.width, y: display_size.height },
            injector_registry_proxy,
            configuration_proxy,
            inspect_status,
            metrics_logger,
            aggregator_proxy,
        });

        Ok(handler)
    }

    /// Adds a new pointer injector and tracks it in `self.injectors` if one doesn't exist at
    /// `mouse_descriptor.device_id`.
    ///
    /// # Parameters
    /// - `mouse_event`: The mouse event to send to Scenic.
    /// - `mouse_descriptor`: The descriptor for the device that sent the mouse event.
    /// - `event_time`: The time in nanoseconds when the event was first recorded.
    async fn ensure_injector_registered(
        self: &Rc<Self>,
        mouse_event: &mouse_binding::MouseEvent,
        mouse_descriptor: &mouse_binding::MouseDeviceDescriptor,
        event_time: zx::MonotonicInstant,
    ) -> Result<(), anyhow::Error> {
        if self.inner().injectors.contains_key(&mouse_descriptor.device_id) {
            return Ok(());
        }

        // Create a new injector.
        let (device_proxy, device_server) = create_proxy::<pointerinjector::DeviceMarker>();
        let context = fuchsia_scenic::duplicate_view_ref(&self.context_view_ref)
            .context("Failed to duplicate context view ref.")?;
        let target = fuchsia_scenic::duplicate_view_ref(&self.target_view_ref)
            .context("Failed to duplicate target view ref.")?;

        let viewport = self.inner().viewport.clone();
        let config = pointerinjector::Config {
            device_id: Some(mouse_descriptor.device_id),
            device_type: Some(pointerinjector::DeviceType::Mouse),
            context: Some(pointerinjector::Context::View(context)),
            target: Some(pointerinjector::Target::View(target)),
            viewport,
            dispatch_policy: Some(pointerinjector::DispatchPolicy::MouseHoverAndLatchInTarget),
            scroll_v_range: mouse_descriptor.wheel_v_range.clone(),
            scroll_h_range: mouse_descriptor.wheel_h_range.clone(),
            buttons: mouse_descriptor.buttons.clone(),
            ..Default::default()
        };

        // Register the new injector.
        self.injector_registry_proxy
            .register(config, device_server)
            .await
            .context("Failed to register injector.")?;
        tracing::info!("Registered injector with device id {:?}", mouse_descriptor.device_id);

        // Keep track of the injector.
        self.inner_mut().injectors.insert(mouse_descriptor.device_id, device_proxy.clone());

        // Inject ADD event the first time a MouseDevice is seen.
        let events_to_send = &[self.create_pointer_sample_event(
            mouse_event,
            event_time,
            pointerinjector::EventPhase::Add,
            self.inner().current_position,
            None,
        )];
        device_proxy.inject(events_to_send).await.context("Failed to ADD new MouseDevice.")?;

        Ok(())
    }

    /// Updates the current cursor position according to the received mouse event.
    ///
    /// The updated cursor state is sent via `self.inner.cursor_message_sender` to a client
    /// that renders the cursor on-screen.
    ///
    /// If there is no movement, the location is not sent.
    ///
    /// # Parameters
    /// - `mouse_event`: The mouse event to use to update the cursor location.
    /// - `mouse_descriptor`: The descriptor for the input device generating the input reports.
    async fn update_cursor_renderer(
        &self,
        mouse_event: &mouse_binding::MouseEvent,
        mouse_descriptor: &mouse_binding::MouseDeviceDescriptor,
    ) -> Result<(), anyhow::Error> {
        let mut new_position = match (mouse_event.location, mouse_descriptor) {
            (
                mouse_binding::MouseLocation::Relative(mouse_binding::RelativeLocation {
                    millimeters,
                }),
                _,
            ) => {
                self.inner().current_position
                    + self.relative_movement_mm_to_phyical_pixel(millimeters)
            }
            (
                mouse_binding::MouseLocation::Absolute(position),
                mouse_binding::MouseDeviceDescriptor {
                    absolute_x_range: Some(x_range),
                    absolute_y_range: Some(y_range),
                    ..
                },
            ) => self.scale_absolute_position(&position, &x_range, &y_range),
            (mouse_binding::MouseLocation::Absolute(_), _) => {
                return Err(anyhow!(
                    "Received an Absolute mouse location without absolute device ranges."
                ))
            }
        };
        Position::clamp(&mut new_position, Position::zero(), self.max_position);
        self.inner_mut().current_position = new_position;

        let mut cursor_message_sender = self.inner().cursor_message_sender.clone();
        cursor_message_sender
            .send(CursorMessage::SetPosition(new_position))
            .await
            .context("Failed to send current mouse position to cursor renderer")?;

        Ok(())
    }

    /// Returns an absolute cursor position scaled from device coordinates to the handler's
    /// max position.
    ///
    /// # Parameters
    /// - `position`: Absolute cursor position in device coordinates.
    /// - `x_range`: The range of possible x values of absolute mouse positions.
    /// - `y_range`: The range of possible y values of absolute mouse positions.
    fn scale_absolute_position(
        &self,
        position: &Position,
        x_range: &Range,
        y_range: &Range,
    ) -> Position {
        let range_min = Position { x: x_range.min as f32, y: y_range.min as f32 };
        let range_max = Position { x: x_range.max as f32, y: y_range.max as f32 };
        self.max_position * ((*position - range_min) / (range_max - range_min))
    }

    /// Sends the given event to Scenic.
    ///
    /// # Parameters
    /// - `mouse_event`: The mouse event to send to Scenic.
    /// - `mouse_descriptor`: The descriptor for the device that sent the mouse event.
    /// - `event_time`: The time in nanoseconds when the event was first recorded.
    async fn send_event_to_scenic(
        &self,
        mouse_event: &mouse_binding::MouseEvent,
        mouse_descriptor: &mouse_binding::MouseDeviceDescriptor,
        event_time: zx::MonotonicInstant,
    ) -> Result<(), anyhow::Error> {
        let injector = self.inner().injectors.get(&mouse_descriptor.device_id).cloned();
        if let Some(injector) = injector {
            let relative_motion = match mouse_event.location {
                mouse_binding::MouseLocation::Relative(mouse_binding::RelativeLocation {
                    millimeters: offset_mm,
                }) if mouse_event.phase == mouse_binding::MousePhase::Move => {
                    let offset = self.relative_movement_mm_to_phyical_pixel(offset_mm);
                    Some([offset.x, offset.y])
                }
                _ => None,
            };
            let events_to_send = &[self.create_pointer_sample_event(
                mouse_event,
                event_time,
                pointerinjector::EventPhase::Change,
                self.inner().current_position,
                relative_motion,
            )];
            let _ = injector.inject(events_to_send).await;

            Ok(())
        } else {
            Err(anyhow::format_err!(
                "No injector found for mouse device {}.",
                mouse_descriptor.device_id
            ))
        }
    }

    /// Creates a [`fidl_fuchsia_ui_pointerinjector::Event`] representing the given MouseEvent.
    ///
    /// # Parameters
    /// - `mouse_event`: The mouse event to send to Scenic.
    /// - `event_time`: The time in nanoseconds when the event was first recorded.
    /// - `phase`: The EventPhase to send to Scenic.
    /// - `current_position`: The current cursor position.
    /// - `relative_motion`: The relative motion to send to Scenic.
    fn create_pointer_sample_event(
        &self,
        mouse_event: &mouse_binding::MouseEvent,
        event_time: zx::MonotonicInstant,
        phase: pointerinjector::EventPhase,
        current_position: Position,
        relative_motion: Option<[f32; 2]>,
    ) -> pointerinjector::Event {
        let pointer_sample = pointerinjector::PointerSample {
            pointer_id: Some(0),
            phase: Some(phase),
            position_in_viewport: Some([current_position.x, current_position.y]),
            scroll_v: match mouse_event.wheel_delta_v {
                Some(mouse_binding::WheelDelta {
                    raw_data: mouse_binding::RawWheelDelta::Ticks(tick),
                    ..
                }) => Some(tick),
                _ => None,
            },
            scroll_h: match mouse_event.wheel_delta_h {
                Some(mouse_binding::WheelDelta {
                    raw_data: mouse_binding::RawWheelDelta::Ticks(tick),
                    ..
                }) => Some(tick),
                _ => None,
            },
            scroll_v_physical_pixel: match mouse_event.wheel_delta_v {
                Some(mouse_binding::WheelDelta { physical_pixel: Some(pixel), .. }) => {
                    Some(pixel.into())
                }
                _ => None,
            },
            scroll_h_physical_pixel: match mouse_event.wheel_delta_h {
                Some(mouse_binding::WheelDelta { physical_pixel: Some(pixel), .. }) => {
                    Some(pixel.into())
                }
                _ => None,
            },
            is_precision_scroll: match mouse_event.phase {
                mouse_binding::MousePhase::Wheel => match mouse_event.is_precision_scroll {
                    Some(mouse_binding::PrecisionScroll::Yes) => Some(true),
                    Some(mouse_binding::PrecisionScroll::No) => Some(false),
                    None => {
                        self.metrics_logger.log_error(
                            InputPipelineErrorMetricDimensionEvent::MouseInjectorMissingIsPrecisionScroll,
                            "mouse wheel event does not have value in is_precision_scroll.");
                        None
                    }
                },
                _ => None,
            },
            pressed_buttons: Some(Vec::from_iter(mouse_event.pressed_buttons.iter().cloned())),
            relative_motion,
            ..Default::default()
        };
        pointerinjector::Event {
            timestamp: Some(event_time.into_nanos()),
            data: Some(pointerinjector::Data::PointerSample(pointer_sample)),
            trace_flow_id: None,
            ..Default::default()
        }
    }

    /// Reports the given event_time to the activity service.
    async fn report_mouse_activity(
        &self,
        event_time: zx::MonotonicInstant,
    ) -> Result<(), fidl::Error> {
        self.aggregator_proxy.report_discrete_activity(event_time.into_nanos()).await
    }

    /// Watches for viewport updates from the scene manager.
    pub async fn watch_viewport(self: Rc<Self>) {
        let configuration_proxy = self.configuration_proxy.clone();
        let mut viewport_stream = HangingGetStream::new(
            configuration_proxy,
            pointerinjector_config::SetupProxy::watch_viewport,
        );
        loop {
            match viewport_stream.next().await {
                Some(Ok(new_viewport)) => {
                    // Update the viewport tracked by this handler.
                    self.inner_mut().viewport = Some(new_viewport.clone());

                    // Update Scenic with the latest viewport.
                    let injectors = self.inner().injectors.values().cloned().collect::<Vec<_>>();
                    for injector in injectors {
                        let events = &[pointerinjector::Event {
                            timestamp: Some(fuchsia_async::MonotonicInstant::now().into_nanos()),
                            data: Some(pointerinjector::Data::Viewport(new_viewport.clone())),
                            trace_flow_id: Some(fuchsia_trace::Id::new().into()),
                            ..Default::default()
                        }];
                        injector.inject(events).await.expect("Failed to inject updated viewport.");
                    }
                }
                Some(Err(e)) => {
                    self.metrics_logger.log_error(
                        InputPipelineErrorMetricDimensionEvent::MouseInjectorErrorWhileReadingViewportUpdate,
                        std::format!("Error while reading viewport update: {}", e));
                    return;
                }
                None => {
                    self.metrics_logger.log_error(
                        InputPipelineErrorMetricDimensionEvent::MouseInjectorViewportUpdateStreamTerminatedUnexpectedly,
                        "Viewport update stream terminated unexpectedly");
                    return;
                }
            }
        }
    }

    /// Converts a relative movement given in millimeters to movement in phyical pixel.
    /// Because pointer_display_scale_handler scaled for device pixel ratio, this method
    /// only need to apply phyical distance to logical pixel scale factor.
    fn relative_movement_mm_to_phyical_pixel(&self, movement_mm: Position) -> Position {
        Position {
            x: movement_mm.x * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
            y: movement_mm.y * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::testing_utilities::{
        assert_handler_ignores_input_event_sequence, create_mouse_event,
        create_mouse_event_with_handled, create_mouse_pointer_sample_event,
        create_mouse_pointer_sample_event_with_wheel_physical_pixel,
    };
    use assert_matches::assert_matches;
    use futures::channel::mpsc;
    use pretty_assertions::assert_eq;
    use std::collections::HashSet;
    use std::ops::Add;
    use test_case::test_case;
    use {
        fidl_fuchsia_input_report as fidl_input_report,
        fidl_fuchsia_ui_pointerinjector as pointerinjector, fuchsia_async as fasync,
    };

    const DISPLAY_WIDTH_IN_PHYSICAL_PX: f32 = 100.0;
    const DISPLAY_HEIGHT_IN_PHYSICAL_PX: f32 = 100.0;
    const COUNTS_PER_MM: u32 = 12;

    /// Returns an |input_device::InputDeviceDescriptor::MouseDescriptor|.
    const DESCRIPTOR: input_device::InputDeviceDescriptor =
        input_device::InputDeviceDescriptor::Mouse(mouse_binding::MouseDeviceDescriptor {
            device_id: 1,
            absolute_x_range: Some(fidl_input_report::Range { min: 0, max: 100 }),
            absolute_y_range: Some(fidl_input_report::Range { min: 0, max: 100 }),
            wheel_v_range: Some(fidl_input_report::Axis {
                range: fidl_input_report::Range { min: -1, max: 1 },
                unit: fidl_input_report::Unit {
                    type_: fidl_input_report::UnitType::Other,
                    exponent: 0,
                },
            }),
            wheel_h_range: Some(fidl_input_report::Axis {
                range: fidl_input_report::Range { min: -1, max: 1 },
                unit: fidl_input_report::Unit {
                    type_: fidl_input_report::UnitType::Other,
                    exponent: 0,
                },
            }),
            buttons: None,
            counts_per_mm: COUNTS_PER_MM,
        });

    /// Handles |fidl_fuchsia_pointerinjector_configuration::SetupRequest::GetViewRefs|.
    async fn handle_configuration_request_stream(
        stream: &mut pointerinjector_config::SetupRequestStream,
    ) {
        if let Some(Ok(request)) = stream.next().await {
            match request {
                pointerinjector_config::SetupRequest::GetViewRefs { responder, .. } => {
                    let context = fuchsia_scenic::ViewRefPair::new()
                        .expect("Failed to create viewrefpair.")
                        .view_ref;
                    let target = fuchsia_scenic::ViewRefPair::new()
                        .expect("Failed to create viewrefpair.")
                        .view_ref;
                    let _ = responder.send(context, target);
                }
                _ => {}
            };
        }
    }

    /// Handles |fidl_fuchsia_pointerinjector::RegistryRequest|s by forwarding the registered device
    /// over `injector_sender` to be handled by handle_device_request_stream().
    async fn handle_registry_request_stream(
        mut stream: pointerinjector::RegistryRequestStream,
        injector_sender: futures::channel::oneshot::Sender<pointerinjector::DeviceRequestStream>,
    ) {
        if let Some(request) = stream.next().await {
            match request {
                Ok(pointerinjector::RegistryRequest::Register {
                    config: _,
                    injector,
                    responder,
                    ..
                }) => {
                    let injector_stream = injector.into_stream();
                    let _ = injector_sender.send(injector_stream);
                    responder.send().expect("failed to respond");
                }
                _ => {}
            };
        } else {
            panic!("RegistryRequestStream failed.");
        }
    }

    // Handles |fidl_fuchsia_pointerinjector::RegistryRequest|s
    async fn handle_registry_request_stream2(
        mut stream: pointerinjector::RegistryRequestStream,
        injector_sender: mpsc::UnboundedSender<Vec<pointerinjector::Event>>,
    ) {
        let (injector, responder) = match stream.next().await {
            Some(Ok(pointerinjector::RegistryRequest::Register {
                config: _,
                injector,
                responder,
                ..
            })) => (injector, responder),
            other => panic!("expected register request, but got {:?}", other),
        };
        let injector_stream: pointerinjector::DeviceRequestStream = injector.into_stream();
        responder.send().expect("failed to respond");
        injector_stream
            .for_each(|request| {
                futures::future::ready({
                    match request {
                        Ok(pointerinjector::DeviceRequest::Inject {
                            events,
                            responder: device_injector_responder,
                        }) => {
                            let _ = injector_sender.unbounded_send(events);
                            device_injector_responder.send().expect("failed to respond")
                        }
                        Err(e) => panic!("FIDL error {}", e),
                    }
                })
            })
            .await;
    }

    /// Handles |fidl_fuchsia_pointerinjector::DeviceRequest|s by asserting the injector stream
    /// received on `injector_stream_receiver` gets `expected_events`.
    async fn handle_device_request_stream(
        injector_stream_receiver: futures::channel::oneshot::Receiver<
            pointerinjector::DeviceRequestStream,
        >,
        expected_events: Vec<pointerinjector::Event>,
    ) {
        let mut injector_stream =
            injector_stream_receiver.await.expect("Failed to get DeviceRequestStream.");
        for expected_event in expected_events {
            match injector_stream.next().await {
                Some(Ok(pointerinjector::DeviceRequest::Inject { events, responder })) => {
                    assert_eq!(events, vec![expected_event]);
                    responder.send().expect("failed to respond");
                }
                Some(Err(e)) => panic!("FIDL error {}", e),
                None => panic!("Expected another event."),
            }
        }
    }

    /// Handles |fidl_fuchsia_interaction_observation::AggregatorRequest|s.
    async fn handle_aggregator_request_stream(
        mut stream: interaction_observation::AggregatorRequestStream,
        expected_times: Vec<i64>,
    ) {
        for expected_time in expected_times {
            if let Some(request) = stream.next().await {
                match request {
                    Ok(interaction_observation::AggregatorRequest::ReportDiscreteActivity {
                        event_time,
                        responder,
                    }) => {
                        assert_eq!(event_time, expected_time);
                        responder.send().expect("failed to respond");
                    }
                    other => panic!("expected aggregator report request, but got {:?}", other),
                };
            } else {
                panic!("AggregatorRequestStream failed.");
            }
        }
    }

    // Creates a |pointerinjector::Viewport|.
    fn create_viewport(min: f32, max: f32) -> pointerinjector::Viewport {
        pointerinjector::Viewport {
            extents: Some([[min, min], [max, max]]),
            viewport_to_context_transform: None,
            ..Default::default()
        }
    }

    // Tests that MouseInjectorHandler::receives_viewport_updates() tracks viewport updates
    // and notifies injectors about said updates.
    #[fuchsia::test]
    fn receives_viewport_updates() {
        let mut exec = fasync::TestExecutor::new();

        // Set up fidl streams.
        let (aggregator_proxy, _) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, _) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let (sender, _) = futures::channel::mpsc::channel::<CursorMessage>(0);

        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");

        // Create mouse handler.
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);
        let (mouse_handler_res, _) = exec.run_singlethreaded(futures::future::join(
            mouse_handler_fut,
            config_request_stream_fut,
        ));
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        // Add an injector.
        let (injector_device_proxy, mut injector_device_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::DeviceMarker>();
        mouse_handler.inner_mut().injectors.insert(1, injector_device_proxy);

        // This nested block is used to bound the lifetime of `watch_viewport_fut`.
        {
            // Request a viewport update.
            let watch_viewport_fut = mouse_handler.clone().watch_viewport();
            futures::pin_mut!(watch_viewport_fut);
            assert!(exec.run_until_stalled(&mut watch_viewport_fut).is_pending());

            // Send a viewport update.
            match exec.run_singlethreaded(&mut configuration_request_stream.next()) {
                Some(Ok(pointerinjector_config::SetupRequest::WatchViewport {
                    responder, ..
                })) => {
                    responder.send(&create_viewport(0.0, 100.0)).expect("Failed to send viewport.");
                }
                other => panic!("Received unexpected value: {:?}", other),
            };
            assert!(exec.run_until_stalled(&mut watch_viewport_fut).is_pending());

            // Check that the injector received an updated viewport
            exec.run_singlethreaded(async {
                match injector_device_request_stream.next().await {
                    Some(Ok(pointerinjector::DeviceRequest::Inject { events, responder })) => {
                        assert_eq!(events.len(), 1);
                        assert!(events[0].data.is_some());
                        assert_eq!(
                            events[0].data,
                            Some(pointerinjector::Data::Viewport(create_viewport(0.0, 100.0)))
                        );
                        responder.send().expect("injector stream failed to respond.");
                    }
                    other => panic!("Received unexpected value: {:?}", other),
                }
            });

            // Request viewport update.
            assert!(exec.run_until_stalled(&mut watch_viewport_fut).is_pending());

            // Send viewport update.
            match exec.run_singlethreaded(&mut configuration_request_stream.next()) {
                Some(Ok(pointerinjector_config::SetupRequest::WatchViewport {
                    responder, ..
                })) => {
                    responder
                        .send(&create_viewport(100.0, 200.0))
                        .expect("Failed to send viewport.");
                }
                other => panic!("Received unexpected value: {:?}", other),
            };

            // Process viewport update.
            assert!(exec.run_until_stalled(&mut watch_viewport_fut).is_pending());
        }

        // Check that the injector received an updated viewport
        exec.run_singlethreaded(async {
            match injector_device_request_stream.next().await {
                Some(Ok(pointerinjector::DeviceRequest::Inject { events, responder })) => {
                    assert_eq!(events.len(), 1);
                    assert!(events[0].data.is_some());
                    assert_eq!(
                        events[0].data,
                        Some(pointerinjector::Data::Viewport(create_viewport(100.0, 200.0)))
                    );
                    responder.send().expect("injector stream failed to respond.");
                }
                other => panic!("Received unexpected value: {:?}", other),
            }
        });

        // Check the viewport on the handler is accurate.
        let expected_viewport = create_viewport(100.0, 200.0);
        assert_eq!(mouse_handler.inner().viewport, Some(expected_viewport));
    }

    fn wheel_delta_ticks(
        ticks: i64,
        physical_pixel: Option<f32>,
    ) -> Option<mouse_binding::WheelDelta> {
        Some(mouse_binding::WheelDelta {
            raw_data: mouse_binding::RawWheelDelta::Ticks(ticks),
            physical_pixel,
        })
    }

    fn wheel_delta_mm(mm: f32, physical_pixel: Option<f32>) -> Option<mouse_binding::WheelDelta> {
        Some(mouse_binding::WheelDelta {
            raw_data: mouse_binding::RawWheelDelta::Millimeters(mm),
            physical_pixel,
        })
    }

    // Tests that a mouse move event both sends an update to scenic and sends the current cursor
    // location via the cursor location sender.
    #[test_case(
        mouse_binding::MouseLocation::Relative(
            mouse_binding::RelativeLocation {
                millimeters: Position { x: 1.0, y: 2.0 }
            }),
        Position {
            x: DISPLAY_WIDTH_IN_PHYSICAL_PX / 2.0
                + 1.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
            y: DISPLAY_HEIGHT_IN_PHYSICAL_PX / 2.0
                + 2.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
        },
        [
            1.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
            2.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
        ]; "Valid move event."
    )]
    #[test_case(
        mouse_binding::MouseLocation::Relative(
            mouse_binding::RelativeLocation {
                millimeters: Position {
                    x: DISPLAY_WIDTH_IN_PHYSICAL_PX / MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL + 2.0,
                    y: DISPLAY_HEIGHT_IN_PHYSICAL_PX / MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL + 1.0,
                }}),
        Position {
          x: DISPLAY_WIDTH_IN_PHYSICAL_PX,
          y: DISPLAY_HEIGHT_IN_PHYSICAL_PX,
        },
        [
            DISPLAY_WIDTH_IN_PHYSICAL_PX + 2.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
            DISPLAY_HEIGHT_IN_PHYSICAL_PX + 1.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
        ]; "Move event exceeds max bounds."
    )]
    #[test_case(
        mouse_binding::MouseLocation::Relative(
            mouse_binding::RelativeLocation {
                millimeters: Position {
                    x: -(DISPLAY_WIDTH_IN_PHYSICAL_PX / MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL + 2.0),
                    y: -(DISPLAY_HEIGHT_IN_PHYSICAL_PX / MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL + 1.0),
                }}),
        Position { x: 0.0, y: 0.0 },
        [
            -(DISPLAY_WIDTH_IN_PHYSICAL_PX + 2.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL),
            -(DISPLAY_HEIGHT_IN_PHYSICAL_PX + 1.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL),
        ]; "Move event exceeds min bounds."
    )]
    #[fuchsia::test(allow_stalls = false)]
    async fn move_event(
        move_location: mouse_binding::MouseLocation,
        expected_position: Position,
        expected_relative_motion: [f32; 2],
    ) {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        let (sender, mut receiver) = futures::channel::mpsc::channel::<CursorMessage>(1);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        let event_time = zx::MonotonicInstant::get();
        let input_event = create_mouse_event(
            move_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Move,
            HashSet::new(),
            HashSet::new(),
            event_time,
            &DESCRIPTOR,
        );

        // Handle event.
        let handle_event_fut = mouse_handler.handle_input_event(input_event);
        let expected_events = vec![
            create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Add,
                vec![],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time,
            ),
            create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![],
                expected_position,
                Some(expected_relative_motion),
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time,
            ),
        ];

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            futures::channel::oneshot::channel::<pointerinjector::DeviceRequestStream>();
        let registry_fut = handle_registry_request_stream(
            injector_registry_request_stream,
            injector_stream_sender,
        );
        let device_fut = handle_device_request_stream(injector_stream_receiver, expected_events);
        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![event_time.into_nanos()],
        );

        // Await all futures concurrently. If this completes, then the mouse event was handled and
        // matches `expected_events`.
        let (handle_result, _, _, _) =
            futures::join!(handle_event_fut, registry_fut, device_fut, aggregator_fut);
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                pretty_assertions::assert_eq!(position, expected_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }

        // No unhandled events.
        assert_matches!(
            handle_result.as_slice(),
            [input_device::InputEvent { handled: input_device::Handled::Yes, .. }]
        );
    }

    // Tests that an absolute mouse move event scales the location from device coordinates to
    // between {0, 0} and the handler's maximum position.
    #[fuchsia::test(allow_stalls = false)]
    async fn move_absolute_event() {
        const DEVICE_ID: u32 = 1;

        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        let (sender, mut receiver) = futures::channel::mpsc::channel::<CursorMessage>(1);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        // The location is rescaled from the device coordinate system defined
        // by `absolute_x_range` and `absolute_y_range`, to the display coordinate
        // system defined by `max_position`.
        //
        //          -50 y              0 +------------------ w
        //            |                  |         .
        //            |                  |         .
        //            |                  |         .
        // -50 x -----o----- 50   ->     | . . . . . . . . .
        //            |                  |         .
        //         * { x: -25, y: 25 }   |    * { x: w * 0.25, y: h * 0.75 }
        //            |                  |         .
        //           50                h |         .
        //
        // Where w = DISPLAY_WIDTH, h = DISPLAY_HEIGHT
        let cursor_location =
            mouse_binding::MouseLocation::Absolute(Position { x: -25.0, y: 25.0 });
        let event_time = zx::MonotonicInstant::get();
        let descriptor =
            input_device::InputDeviceDescriptor::Mouse(mouse_binding::MouseDeviceDescriptor {
                device_id: DEVICE_ID,
                absolute_x_range: Some(fidl_input_report::Range { min: -50, max: 50 }),
                absolute_y_range: Some(fidl_input_report::Range { min: -50, max: 50 }),
                wheel_v_range: None,
                wheel_h_range: None,
                buttons: None,
                counts_per_mm: COUNTS_PER_MM,
            });
        let input_event = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Move,
            HashSet::new(),
            HashSet::new(),
            event_time,
            &descriptor,
        );

        // Handle event.
        let handle_event_fut = mouse_handler.handle_input_event(input_event);
        let expected_position = Position {
            x: DISPLAY_WIDTH_IN_PHYSICAL_PX * 0.25,
            y: DISPLAY_WIDTH_IN_PHYSICAL_PX * 0.75,
        };
        let expected_events = vec![
            create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Add,
                vec![],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time,
            ),
            create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time,
            ),
        ];

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            futures::channel::oneshot::channel::<pointerinjector::DeviceRequestStream>();
        let registry_fut = handle_registry_request_stream(
            injector_registry_request_stream,
            injector_stream_sender,
        );
        let device_fut = handle_device_request_stream(injector_stream_receiver, expected_events);
        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![event_time.into_nanos()],
        );

        // Await all futures concurrently. If this completes, then the mouse event was handled and
        // matches `expected_events`.
        let (handle_result, _, _, _) =
            futures::join!(handle_event_fut, registry_fut, device_fut, aggregator_fut);
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                assert_eq!(position, expected_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }

        // No unhandled events.
        assert_matches!(
            handle_result.as_slice(),
            [input_device::InputEvent { handled: input_device::Handled::Yes, .. }]
        );
    }

    // Tests that mouse down and up events inject button press state.
    #[test_case(
      mouse_binding::MousePhase::Down,
      vec![1], vec![1]; "Down event injects button press state."
    )]
    #[test_case(
      mouse_binding::MousePhase::Up,
      vec![1], vec![]; "Up event injects button press state."
    )]
    #[fuchsia::test(allow_stalls = false)]
    async fn button_state_event(
        phase: mouse_binding::MousePhase,
        affected_buttons: Vec<mouse_binding::MouseButton>,
        pressed_buttons: Vec<mouse_binding::MouseButton>,
    ) {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        let (sender, mut receiver) = futures::channel::mpsc::channel::<CursorMessage>(1);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        let cursor_location = mouse_binding::MouseLocation::Absolute(Position { x: 0.0, y: 0.0 });
        let event_time = zx::MonotonicInstant::get();

        let input_event = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            phase,
            HashSet::from_iter(affected_buttons.clone()),
            HashSet::from_iter(pressed_buttons.clone()),
            event_time,
            &DESCRIPTOR,
        );

        // Handle event.
        let handle_event_fut = mouse_handler.handle_input_event(input_event);
        let expected_position = Position { x: 0.0, y: 0.0 };
        let expected_events = vec![
            create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Add,
                pressed_buttons.clone(),
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time,
            ),
            create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                pressed_buttons.clone(),
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time,
            ),
        ];

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            futures::channel::oneshot::channel::<pointerinjector::DeviceRequestStream>();
        let registry_fut = handle_registry_request_stream(
            injector_registry_request_stream,
            injector_stream_sender,
        );
        let device_fut = handle_device_request_stream(injector_stream_receiver, expected_events);
        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![event_time.into_nanos()],
        );

        // Await all futures concurrently. If this completes, then the mouse event was handled and
        // matches `expected_events`.
        let (handle_result, _, _, _) =
            futures::join!(handle_event_fut, registry_fut, device_fut, aggregator_fut);
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                pretty_assertions::assert_eq!(position, expected_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }

        // No unhandled events.
        assert_matches!(
            handle_result.as_slice(),
            [input_device::InputEvent { handled: input_device::Handled::Yes, .. }]
        );
    }

    // Tests that mouse down followed by mouse up events inject button press state.
    #[fuchsia::test(allow_stalls = false)]
    async fn down_up_event() {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        // Note: The size of the CursorMessage channel's buffer is 2 to allow for one cursor
        // update for every input event being sent.
        let (sender, mut receiver) = futures::channel::mpsc::channel::<CursorMessage>(2);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        let cursor_location = mouse_binding::MouseLocation::Absolute(Position { x: 0.0, y: 0.0 });
        let event_time1 = zx::MonotonicInstant::get();
        let event_time2 = event_time1.add(zx::MonotonicDuration::from_micros(1));

        let event1 = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Down,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![1]),
            event_time1,
            &DESCRIPTOR,
        );

        let event2 = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Up,
            HashSet::from_iter(vec![1]),
            HashSet::new(),
            event_time2,
            &DESCRIPTOR,
        );

        let expected_position = Position { x: 0.0, y: 0.0 };

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            mpsc::unbounded::<Vec<pointerinjector::Event>>();
        // Up to 2 events per handle_input_event() call.
        let mut injector_stream_receiver = injector_stream_receiver.ready_chunks(2);
        let registry_fut = handle_registry_request_stream2(
            injector_registry_request_stream,
            injector_stream_sender,
        );
        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![event_time1.into_nanos(), event_time2.into_nanos()],
        );

        // Run all futures until the handler future completes.
        let _registry_task = fasync::Task::local(registry_fut);
        let _aggregator_task = fasync::Task::local(aggregator_fut);

        mouse_handler.clone().handle_input_event(event1).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Add,
                    vec![1],
                    expected_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                ),
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Change,
                    vec![1],
                    expected_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                )
            ])
        );

        // Send another input event.
        mouse_handler.clone().handle_input_event(event2).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time2,
            )])
        );

        // Wait until validation is complete.
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                assert_eq!(position, expected_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }
    }

    /// Tests that two staggered button presses followed by stagged releases generate four mouse
    /// events with distinct `affected_button` and `pressed_button`.
    /// Specifically, we test and expect the following in order:
    /// | Action           | MousePhase | Injected Phase | `pressed_buttons` |
    /// | ---------------- | ---------- | -------------- | ----------------- |
    /// | Press button 1   | Down       | Change         | [1]               |
    /// | Press button 2   | Down       | Change         | [1, 2]            |
    /// | Release button 1 | Up         | Change         | [2]               |
    /// | Release button 2 | Up         | Change         | []                |
    #[fuchsia::test(allow_stalls = false)]
    async fn down_down_up_up_event() {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        // Note: The size of the CursorMessage channel's buffer is 4 to allow for one cursor
        // update for every input event being sent.
        let (sender, mut receiver) = futures::channel::mpsc::channel::<CursorMessage>(4);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        let cursor_location = mouse_binding::MouseLocation::Absolute(Position { x: 0.0, y: 0.0 });
        let event_time1 = zx::MonotonicInstant::get();
        let event_time2 = event_time1.add(zx::MonotonicDuration::from_micros(1));
        let event_time3 = event_time2.add(zx::MonotonicDuration::from_micros(1));
        let event_time4 = event_time3.add(zx::MonotonicDuration::from_micros(1));

        let event1 = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Down,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![1]),
            event_time1,
            &DESCRIPTOR,
        );
        let event2 = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Down,
            HashSet::from_iter(vec![2]),
            HashSet::from_iter(vec![1, 2]),
            event_time2,
            &DESCRIPTOR,
        );
        let event3 = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Up,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![2]),
            event_time3,
            &DESCRIPTOR,
        );
        let event4 = create_mouse_event(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Up,
            HashSet::from_iter(vec![2]),
            HashSet::new(),
            event_time4,
            &DESCRIPTOR,
        );

        let expected_position = Position { x: 0.0, y: 0.0 };

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            mpsc::unbounded::<Vec<pointerinjector::Event>>();
        // Up to 2 events per handle_input_event() call.
        let mut injector_stream_receiver = injector_stream_receiver.ready_chunks(2);
        let registry_fut = handle_registry_request_stream2(
            injector_registry_request_stream,
            injector_stream_sender,
        );
        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![
                event_time1.into_nanos(),
                event_time2.into_nanos(),
                event_time3.into_nanos(),
                event_time4.into_nanos(),
            ],
        );

        // Run all futures until the handler future completes.
        let _registry_task = fasync::Task::local(registry_fut);
        let _aggregator_task = fasync::Task::local(aggregator_fut);
        mouse_handler.clone().handle_input_event(event1).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Add,
                    vec![1],
                    expected_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                ),
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Change,
                    vec![1],
                    expected_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                )
            ])
        );

        // Send another down event.
        mouse_handler.clone().handle_input_event(event2).await;
        let pointer_sample_event2 = injector_stream_receiver
            .next()
            .await
            .map(|events| events.concat())
            .expect("Failed to receive pointer sample event.");
        let expected_event_time: i64 = event_time2.into_nanos();
        assert_eq!(pointer_sample_event2.len(), 1);

        // We must break this event result apart for assertions since the
        // `pressed_buttons` can be given with elements in any order.
        match &pointer_sample_event2[0] {
            pointerinjector::Event {
                timestamp: Some(actual_event_time),
                data:
                    Some(pointerinjector::Data::PointerSample(pointerinjector::PointerSample {
                        pointer_id: Some(0),
                        phase: Some(pointerinjector::EventPhase::Change),
                        position_in_viewport: Some(actual_position),
                        scroll_v: None,
                        scroll_h: None,
                        pressed_buttons: Some(actual_buttons),
                        relative_motion: None,
                        ..
                    })),
                ..
            } => {
                assert_eq!(actual_event_time, &expected_event_time);
                assert_eq!(actual_position[0], expected_position.x);
                assert_eq!(actual_position[1], expected_position.y);
                assert_eq!(
                    HashSet::<mouse_binding::MouseButton>::from_iter(actual_buttons.clone()),
                    HashSet::from_iter(vec![1, 2])
                );
            }
            _ => panic!("Unexpected pointer sample event: {:?}", pointer_sample_event2[0]),
        }

        // Send another up event.
        mouse_handler.clone().handle_input_event(event3).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![2],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time3,
            )])
        );

        // Send another up event.
        mouse_handler.clone().handle_input_event(event4).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time4,
            )])
        );

        // Wait until validation is complete.
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                assert_eq!(position, expected_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }
    }

    /// Tests that button press, mouse move, and button release inject changes accordingly.
    #[fuchsia::test(allow_stalls = false)]
    async fn down_move_up_event() {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        // Note: The size of the CursorMessage channel's buffer is 3 to allow for one cursor
        // update for every input event being sent.
        let (sender, mut receiver) = futures::channel::mpsc::channel::<CursorMessage>(3);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        let event_time1 = zx::MonotonicInstant::get();
        let event_time2 = event_time1.add(zx::MonotonicDuration::from_micros(1));
        let event_time3 = event_time2.add(zx::MonotonicDuration::from_micros(1));
        let zero_position = Position { x: 0.0, y: 0.0 };
        let expected_position = Position {
            x: 10.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
            y: 5.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
        };
        let expected_relative_motion = [
            10.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
            5.0 * MOUSE_DISTANCE_IN_MM_TO_DISPLAY_LOGICAL_PIXEL,
        ];
        let event1 = create_mouse_event(
            mouse_binding::MouseLocation::Absolute(Position { x: 0.0, y: 0.0 }),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Down,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![1]),
            event_time1,
            &DESCRIPTOR,
        );
        let event2 = create_mouse_event(
            mouse_binding::MouseLocation::Relative(mouse_binding::RelativeLocation {
                millimeters: Position { x: 10.0, y: 5.0 },
            }),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Move,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![1]),
            event_time2,
            &DESCRIPTOR,
        );
        let event3 = create_mouse_event(
            mouse_binding::MouseLocation::Relative(mouse_binding::RelativeLocation {
                millimeters: Position { x: 0.0, y: 0.0 },
            }),
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Up,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![]),
            event_time3,
            &DESCRIPTOR,
        );

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            mpsc::unbounded::<Vec<pointerinjector::Event>>();
        // Up to 2 events per handle_input_event() call.
        let mut injector_stream_receiver = injector_stream_receiver.ready_chunks(2);
        let registry_fut = handle_registry_request_stream2(
            injector_registry_request_stream,
            injector_stream_sender,
        );
        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![event_time1.into_nanos(), event_time2.into_nanos(), event_time3.into_nanos()],
        );

        // Run all futures until the handler future completes.
        let _registry_task = fasync::Task::local(registry_fut);
        let _aggregator_task = fasync::Task::local(aggregator_fut);
        mouse_handler.clone().handle_input_event(event1).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Add,
                    vec![1],
                    zero_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                ),
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Change,
                    vec![1],
                    zero_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                )
            ])
        );

        // Wait until cursor position validation is complete.
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                assert_eq!(position, zero_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }

        // Send a move event.
        mouse_handler.clone().handle_input_event(event2).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![1],
                expected_position,
                Some(expected_relative_motion),
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time2,
            )])
        );

        // Wait until cursor position validation is complete.
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                assert_eq!(position, expected_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }

        // Send an up event.
        mouse_handler.clone().handle_input_event(event3).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time3,
            )])
        );

        // Wait until cursor position validation is complete.
        match receiver.next().await {
            Some(CursorMessage::SetPosition(position)) => {
                assert_eq!(position, expected_position);
            }
            Some(CursorMessage::SetVisibility(_)) => {
                panic!("Received unexpected cursor visibility update.")
            }
            None => panic!("Did not receive cursor update."),
        }
    }

    // Tests that a mouse move event that has already been handled is not forwarded to scenic.
    #[fuchsia::test(allow_stalls = false)]
    async fn handler_ignores_handled_events() {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        let (sender, mut receiver) = futures::channel::mpsc::channel::<CursorMessage>(1);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        let cursor_relative_position = Position { x: 50.0, y: 75.0 };
        let cursor_location =
            mouse_binding::MouseLocation::Relative(mouse_binding::RelativeLocation {
                millimeters: Position {
                    x: cursor_relative_position.x / COUNTS_PER_MM as f32,
                    y: cursor_relative_position.y / COUNTS_PER_MM as f32,
                },
            });
        let event_time = zx::MonotonicInstant::get();
        let input_events = vec![create_mouse_event_with_handled(
            cursor_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Move,
            HashSet::new(),
            HashSet::new(),
            event_time,
            &DESCRIPTOR,
            input_device::Handled::Yes,
        )];

        assert_handler_ignores_input_event_sequence(
            mouse_handler,
            input_events,
            injector_registry_request_stream,
            aggregator_request_stream,
        )
        .await;

        // The cursor location stream should not receive any position.
        assert!(receiver.next().await.is_none());
    }

    fn zero_relative_location() -> mouse_binding::MouseLocation {
        mouse_binding::MouseLocation::Relative(mouse_binding::RelativeLocation {
            millimeters: Position { x: 0.0, y: 0.0 },
        })
    }

    #[test_case(
        create_mouse_event(
            zero_relative_location(),
            wheel_delta_ticks(1, None),               /*wheel_delta_v*/
            None,                                     /*wheel_delta_h*/
            Some(mouse_binding::PrecisionScroll::No), /*is_precision_scroll*/
            mouse_binding::MousePhase::Wheel,
            HashSet::new(),
            HashSet::new(),
            zx::MonotonicInstant::ZERO,
            &DESCRIPTOR,
        ),
        create_mouse_pointer_sample_event(
            pointerinjector::EventPhase::Change,
            vec![],
            Position { x: 50.0, y: 50.0 },
            None,    /*relative_motion*/
            Some(1), /*wheel_delta_v*/
            None,    /*wheel_delta_h*/
            Some(false), /*is_precision_scroll*/
            zx::MonotonicInstant::ZERO,
        ); "v tick scroll"
    )]
    #[test_case(
        create_mouse_event(
            zero_relative_location(),
            None,                                     /*wheel_delta_v*/
            wheel_delta_ticks(1, None),               /*wheel_delta_h*/
            Some(mouse_binding::PrecisionScroll::No), /*is_precision_scroll*/
            mouse_binding::MousePhase::Wheel,
            HashSet::new(),
            HashSet::new(),
            zx::MonotonicInstant::ZERO,
            &DESCRIPTOR,
        ),
        create_mouse_pointer_sample_event(
            pointerinjector::EventPhase::Change,
            vec![],
            Position { x: 50.0, y: 50.0 },
            None,    /*relative_motion*/
            None,    /*wheel_delta_v*/
            Some(1), /*wheel_delta_h*/
            Some(false), /*is_precision_scroll*/
            zx::MonotonicInstant::ZERO,
        ); "h tick scroll"
    )]
    #[test_case(
        create_mouse_event(
            zero_relative_location(),
            wheel_delta_ticks(1, Some(120.0)),        /*wheel_delta_v*/
            None,                                     /*wheel_delta_h*/
            Some(mouse_binding::PrecisionScroll::No), /*is_precision_scroll*/
            mouse_binding::MousePhase::Wheel,
            HashSet::new(),
            HashSet::new(),
            zx::MonotonicInstant::ZERO,
            &DESCRIPTOR,
        ),
        create_mouse_pointer_sample_event_with_wheel_physical_pixel(
            pointerinjector::EventPhase::Change,
            vec![],
            Position { x: 50.0, y: 50.0 },
            None,        /*relative_motion*/
            Some(1),     /*wheel_delta_v*/
            None,        /*wheel_delta_h*/
            Some(120.0), /*wheel_delta_v_physical_pixel*/
            None,        /*wheel_delta_h_physical_pixel*/
            Some(false), /*is_precision_scroll*/
            zx::MonotonicInstant::ZERO,
        ); "v tick scroll with physical pixel"
    )]
    #[test_case(
        create_mouse_event(
            zero_relative_location(),
            None,                                     /*wheel_delta_v*/
            wheel_delta_ticks(1, Some(120.0)),        /*wheel_delta_h*/
            Some(mouse_binding::PrecisionScroll::No), /*is_precision_scroll*/
            mouse_binding::MousePhase::Wheel,
            HashSet::new(),
            HashSet::new(),
            zx::MonotonicInstant::ZERO,
            &DESCRIPTOR,
        ),
        create_mouse_pointer_sample_event_with_wheel_physical_pixel(
            pointerinjector::EventPhase::Change,
            vec![],
            Position { x: 50.0, y: 50.0 },
            None,        /*relative_motion*/
            None,        /*wheel_delta_v*/
            Some(1),     /*wheel_delta_h*/
            None,        /*wheel_delta_v_physical_pixel*/
            Some(120.0), /*wheel_delta_h_physical_pixel*/
            Some(false), /*is_precision_scroll*/
            zx::MonotonicInstant::ZERO,
        ); "h tick scroll with physical pixel"
    )]
    #[test_case(
        create_mouse_event(
            zero_relative_location(),
            wheel_delta_mm(1.0, Some(120.0)),          /*wheel_delta_v*/
            None,                                      /*wheel_delta_h*/
            Some(mouse_binding::PrecisionScroll::Yes), /*is_precision_scroll*/
            mouse_binding::MousePhase::Wheel,
            HashSet::new(),
            HashSet::new(),
            zx::MonotonicInstant::ZERO,
            &DESCRIPTOR,
        ),
        create_mouse_pointer_sample_event_with_wheel_physical_pixel(
            pointerinjector::EventPhase::Change,
            vec![],
            Position { x: 50.0, y: 50.0 },
            None,        /*relative_motion*/
            None,        /*wheel_delta_v*/
            None,        /*wheel_delta_h*/
            Some(120.0), /*wheel_delta_v_physical_pixel*/
            None,        /*wheel_delta_h_physical_pixel*/
            Some(true),  /*is_precision_scroll*/
            zx::MonotonicInstant::ZERO,
        ); "v mm scroll with physical pixel"
    )]
    #[test_case(
        create_mouse_event(
            zero_relative_location(),
            None,                                      /*wheel_delta_v*/
            wheel_delta_mm(1.0, Some(120.0)),          /*wheel_delta_h*/
            Some(mouse_binding::PrecisionScroll::Yes), /*is_precision_scroll*/
            mouse_binding::MousePhase::Wheel,
            HashSet::new(),
            HashSet::new(),
            zx::MonotonicInstant::ZERO,
            &DESCRIPTOR,
        ),
        create_mouse_pointer_sample_event_with_wheel_physical_pixel(
            pointerinjector::EventPhase::Change,
            vec![],
            Position { x: 50.0, y: 50.0 },
            None,        /*relative_motion*/
            None,        /*wheel_delta_v*/
            None,        /*wheel_delta_h*/
            None,        /*wheel_delta_v_physical_pixel*/
            Some(120.0), /*wheel_delta_h_physical_pixel*/
            Some(true),  /*is_precision_scroll*/
            zx::MonotonicInstant::ZERO,
        ); "h mm scroll with physical pixel"
    )]
    /// Test simple scroll in vertical and horizontal.
    #[fuchsia::test(allow_stalls = false)]
    async fn scroll(event: input_device::InputEvent, want_event: pointerinjector::Event) {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        let (sender, _) = futures::channel::mpsc::channel::<CursorMessage>(1);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            mpsc::unbounded::<Vec<pointerinjector::Event>>();
        // Up to 2 events per handle_input_event() call.
        let mut injector_stream_receiver = injector_stream_receiver.ready_chunks(2);
        let registry_fut = handle_registry_request_stream2(
            injector_registry_request_stream,
            injector_stream_sender,
        );

        let event_time = zx::MonotonicInstant::get();

        let event = input_device::InputEvent { event_time, ..event };

        let want_event =
            pointerinjector::Event { timestamp: Some(event_time.into_nanos()), ..want_event };

        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![event.event_time.into_nanos()],
        );

        // Run all futures until the handler future completes.
        let _registry_task = fasync::Task::local(registry_fut);
        let _aggregator_task = fasync::Task::local(aggregator_fut);

        mouse_handler.clone().handle_input_event(event).await;
        let got_events =
            injector_stream_receiver.next().await.map(|events| events.concat()).unwrap();
        pretty_assertions::assert_eq!(got_events.len(), 2);
        assert_matches!(
            got_events[0],
            pointerinjector::Event {
                data: Some(pointerinjector::Data::PointerSample(pointerinjector::PointerSample {
                    phase: Some(pointerinjector::EventPhase::Add),
                    ..
                })),
                ..
            }
        );

        pretty_assertions::assert_eq!(got_events[1], want_event);
    }

    /// Test button down -> scroll -> button up -> continue scroll.
    #[fuchsia::test(allow_stalls = false)]
    async fn down_scroll_up_scroll() {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        // Create MouseInjectorHandler.
        let (sender, _) = futures::channel::mpsc::channel::<CursorMessage>(1);
        let inspector = fuchsia_inspect::Inspector::default();
        let test_node = inspector.root().create_child("test_node");
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &test_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, injector_stream_receiver) =
            mpsc::unbounded::<Vec<pointerinjector::Event>>();
        // Up to 2 events per handle_input_event() call.
        let mut injector_stream_receiver = injector_stream_receiver.ready_chunks(2);
        let registry_fut = handle_registry_request_stream2(
            injector_registry_request_stream,
            injector_stream_sender,
        );

        let event_time1 = zx::MonotonicInstant::get();
        let event_time2 = event_time1.add(zx::MonotonicDuration::from_micros(1));
        let event_time3 = event_time2.add(zx::MonotonicDuration::from_micros(1));
        let event_time4 = event_time3.add(zx::MonotonicDuration::from_micros(1));

        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![
                event_time1.into_nanos(),
                event_time2.into_nanos(),
                event_time3.into_nanos(),
                event_time4.into_nanos(),
            ],
        );

        // Run all futures until the handler future completes.
        let _registry_task = fasync::Task::local(registry_fut);
        let _aggregator_task = fasync::Task::local(aggregator_fut);

        let zero_location =
            mouse_binding::MouseLocation::Relative(mouse_binding::RelativeLocation {
                millimeters: Position { x: 0.0, y: 0.0 },
            });
        let expected_position = Position { x: 50.0, y: 50.0 };

        let down_event = create_mouse_event(
            zero_location,
            None, /* wheel_delta_v */
            None, /* wheel_delta_h */
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Down,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![1]),
            event_time1,
            &DESCRIPTOR,
        );

        let wheel_event = create_mouse_event(
            zero_location,
            wheel_delta_ticks(1, None),               /* wheel_delta_v */
            None,                                     /* wheel_delta_h */
            Some(mouse_binding::PrecisionScroll::No), /* is_precision_scroll */
            mouse_binding::MousePhase::Wheel,
            HashSet::from_iter(vec![1]),
            HashSet::from_iter(vec![1]),
            event_time2,
            &DESCRIPTOR,
        );

        let up_event = create_mouse_event(
            zero_location,
            None,
            None,
            None, /* is_precision_scroll */
            mouse_binding::MousePhase::Up,
            HashSet::from_iter(vec![1]),
            HashSet::new(),
            event_time3,
            &DESCRIPTOR,
        );

        let continue_wheel_event = create_mouse_event(
            zero_location,
            wheel_delta_ticks(1, None),               /* wheel_delta_v */
            None,                                     /* wheel_delta_h */
            Some(mouse_binding::PrecisionScroll::No), /* is_precision_scroll */
            mouse_binding::MousePhase::Wheel,
            HashSet::new(),
            HashSet::new(),
            event_time4,
            &DESCRIPTOR,
        );

        // Handle button down event.
        mouse_handler.clone().handle_input_event(down_event).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Add,
                    vec![1],
                    expected_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                ),
                create_mouse_pointer_sample_event(
                    pointerinjector::EventPhase::Change,
                    vec![1],
                    expected_position,
                    None, /*relative_motion*/
                    None, /*wheel_delta_v*/
                    None, /*wheel_delta_h*/
                    None, /*is_precision_scroll*/
                    event_time1,
                ),
            ])
        );

        // Handle wheel event with button pressing.
        mouse_handler.clone().handle_input_event(wheel_event).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![1],
                expected_position,
                None,        /*relative_motion*/
                Some(1),     /*wheel_delta_v*/
                None,        /*wheel_delta_h*/
                Some(false), /*is_precision_scroll*/
                event_time2,
            )])
        );

        // Handle button up event.
        mouse_handler.clone().handle_input_event(up_event).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![],
                expected_position,
                None, /*relative_motion*/
                None, /*wheel_delta_v*/
                None, /*wheel_delta_h*/
                None, /*is_precision_scroll*/
                event_time3,
            )])
        );

        // Handle wheel event after button released.
        mouse_handler.clone().handle_input_event(continue_wheel_event).await;
        assert_eq!(
            injector_stream_receiver.next().await.map(|events| events.concat()),
            Some(vec![create_mouse_pointer_sample_event(
                pointerinjector::EventPhase::Change,
                vec![],
                expected_position,
                None,        /*relative_motion*/
                Some(1),     /*wheel_delta_v*/
                None,        /*wheel_delta_h*/
                Some(false), /*is_precision_scroll*/
                event_time4,
            )])
        );
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn mouse_injector_handler_initialized_with_inspect_node() {
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);
        let (sender, _) = futures::channel::mpsc::channel::<CursorMessage>(1);
        let inspector = fuchsia_inspect::Inspector::default();
        let fake_handlers_node = inspector.root().create_child("input_handlers_node");
        let mouse_handler_fut = MouseInjectorHandler::new_with_config_proxy(
            configuration_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &fake_handlers_node,
            metrics::MetricsLogger::default(),
        );
        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let _handler = mouse_handler_res.expect("Failed to create mouse handler");

        diagnostics_assertions::assert_data_tree!(inspector, root: {
            input_handlers_node: {
                mouse_injector_handler: {
                    events_received_count: 0u64,
                    events_handled_count: 0u64,
                    last_received_timestamp_ns: 0u64,
                    "fuchsia.inspect.Health": {
                        status: "STARTING_UP",
                        // Timestamp value is unpredictable and not relevant in this context,
                        // so we only assert that the property is present.
                        start_timestamp_nanos: diagnostics_assertions::AnyProperty
                    },
                }
            }
        });
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn mouse_injector_handler_inspect_counts_events() {
        // Set up fidl streams.
        let (aggregator_proxy, aggregator_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<interaction_observation::AggregatorMarker>();
        let (configuration_proxy, mut configuration_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector_config::SetupMarker>();
        let (injector_registry_proxy, injector_registry_request_stream) =
            fidl::endpoints::create_proxy_and_stream::<pointerinjector::RegistryMarker>();
        let (sender, _) = futures::channel::mpsc::channel::<CursorMessage>(1);

        let inspector = fuchsia_inspect::Inspector::default();
        let fake_handlers_node = inspector.root().create_child("input_handlers_node");

        // Create mouse handler.
        let mouse_handler_fut = MouseInjectorHandler::new_handler(
            aggregator_proxy,
            configuration_proxy,
            injector_registry_proxy,
            Size { width: DISPLAY_WIDTH_IN_PHYSICAL_PX, height: DISPLAY_HEIGHT_IN_PHYSICAL_PX },
            sender,
            &fake_handlers_node,
            metrics::MetricsLogger::default(),
        );
        let config_request_stream_fut =
            handle_configuration_request_stream(&mut configuration_request_stream);

        let (mouse_handler_res, _) = futures::join!(mouse_handler_fut, config_request_stream_fut);
        let mouse_handler = mouse_handler_res.expect("Failed to create mouse handler");

        let cursor_location = mouse_binding::MouseLocation::Absolute(Position { x: 0.0, y: 0.0 });
        let event_time1 = zx::MonotonicInstant::get();
        let event_time2 = event_time1.add(zx::MonotonicDuration::from_micros(1));
        let event_time3 = event_time2.add(zx::MonotonicDuration::from_micros(1));

        let aggregator_fut = handle_aggregator_request_stream(
            aggregator_request_stream,
            vec![event_time1.into_nanos(), event_time2.into_nanos(), event_time3.into_nanos()],
        );
        let input_events = vec![
            create_mouse_event(
                cursor_location,
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                mouse_binding::MousePhase::Down,
                HashSet::from_iter(vec![1]),
                HashSet::from_iter(vec![1]),
                event_time1,
                &DESCRIPTOR,
            ),
            create_mouse_event(
                cursor_location,
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                mouse_binding::MousePhase::Up,
                HashSet::from_iter(vec![1]),
                HashSet::new(),
                event_time2,
                &DESCRIPTOR,
            ),
            create_mouse_event_with_handled(
                cursor_location,
                None, /* wheel_delta_v */
                None, /* wheel_delta_h */
                None, /* is_precision_scroll */
                mouse_binding::MousePhase::Down,
                HashSet::from_iter(vec![1]),
                HashSet::from_iter(vec![1]),
                event_time3,
                &DESCRIPTOR,
                input_device::Handled::Yes,
            ),
        ];

        // Create a channel for the the registered device's handle to be forwarded to the
        // DeviceRequestStream handler. This allows the registry_fut to complete and allows
        // handle_input_event() to continue.
        let (injector_stream_sender, _) = mpsc::unbounded::<Vec<pointerinjector::Event>>();
        let registry_fut = handle_registry_request_stream2(
            injector_registry_request_stream,
            injector_stream_sender,
        );

        // Run all futures until the handler future completes.
        let _registry_task = fasync::Task::local(registry_fut);
        let _aggregator_task = fasync::Task::local(aggregator_fut);

        for input_event in input_events {
            mouse_handler.clone().handle_input_event(input_event).await;
        }

        let last_received_event_time: u64 = event_time2.into_nanos().try_into().unwrap();

        diagnostics_assertions::assert_data_tree!(inspector, root: {
            input_handlers_node: {
                mouse_injector_handler: {
                    events_received_count: 2u64,
                    events_handled_count: 2u64,
                    last_received_timestamp_ns: last_received_event_time,
                    "fuchsia.inspect.Health": {
                        status: "STARTING_UP",
                        // Timestamp value is unpredictable and not relevant in this context,
                        // so we only assert that the property is present.
                        start_timestamp_nanos: diagnostics_assertions::AnyProperty
                    },
                }
            }
        });
    }
}