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

use async_utils::event::Event as AsyncEvent;
use fidl_fuchsia_input::Key;
use fidl_fuchsia_input_injection::InputDeviceRegistryMarker;
use fidl_fuchsia_input_report::{
    ConsumerControlInputReport, ContactInputReport, DeviceInformation, InputReport,
    KeyboardInputReport, MouseInputReport, TouchInputReport,
};
use fidl_fuchsia_ui_input::KeyboardReport;
use fidl_fuchsia_ui_test_input::{
    CoordinateUnit, KeyboardMarker, KeyboardRequest, KeyboardRequestStream,
    MediaButtonsDeviceMarker, MediaButtonsDeviceRequest, MediaButtonsDeviceRequestStream,
    MouseMarker, MouseRequest, MouseRequestStream,
    RegistryRegisterKeyboardAndGetDeviceInfoResponse,
    RegistryRegisterMediaButtonsDeviceAndGetDeviceInfoResponse,
    RegistryRegisterMouseAndGetDeviceInfoResponse,
    RegistryRegisterTouchScreenAndGetDeviceInfoResponse, RegistryRequest, RegistryRequestStream,
    TouchScreenMarker, TouchScreenRequest, TouchScreenRequestStream,
};
use fuchsia_component::client::connect_to_protocol;
use futures::{StreamExt, TryStreamExt};
use keymaps::inverse_keymap::{InverseKeymap, Shift};
use keymaps::usages::{hid_usage_to_input3_key, Usages};
use std::time::Duration;
use tracing::{error, info, warn};
use {
    fidl_fuchsia_math as math, fidl_fuchsia_ui_display_singleton as display_info,
    fuchsia_async as fasync,
};

mod input_device;
mod input_device_registry;
mod input_reports_reader;

/// Use this to place required DeviceInformation into DeviceDescriptor.
fn new_fake_device_info() -> DeviceInformation {
    DeviceInformation {
        product_id: Some(42),
        vendor_id: Some(43),
        version: Some(u32::MAX),
        polling_rate: Some(1000),
        ..Default::default()
    }
}

/// Converts the `input` string into a key sequence under the `InverseKeymap` derived from `keymap`.
///
/// This is intended for end-to-end and input testing only; for production use cases and general
/// testing, IME injection should be used instead.
///
/// A translation from `input` to a sequence of keystrokes is not guaranteed to exist. If a
/// translation does not exist, `None` is returned.
///
/// The sequence does not contain pauses except between repeated keys or to clear a shift state,
/// though the sequence does terminate with an empty report (no keys pressed). A shift key
/// transition is sent in advance of each series of keys that needs it.
///
/// Note that there is currently no way to distinguish between particular key releases. As such,
/// only one key release report is generated even in combinations, e.g. Shift + A.
///
/// # Example
///
/// ```
/// let key_sequence = derive_key_sequence(&keymaps::US_QWERTY, "A").unwrap();
///
/// // [shift, A, clear]
/// assert_eq!(key_sequence.len(), 3);
/// ```
///
/// TODO(https://fxbug.dev/42059899): Simplify the logic in this test.
fn derive_key_sequence(keymap: &keymaps::Keymap<'_>, input: &str) -> Option<Vec<KeyboardReport>> {
    let inverse_keymap = InverseKeymap::new(keymap);
    let mut reports = vec![];
    let mut shift_pressed = false;
    let mut last_usage = None;

    for ch in input.chars() {
        let key_stroke = inverse_keymap.get(&ch)?;

        match key_stroke.shift {
            Shift::Yes if !shift_pressed => {
                shift_pressed = true;
                last_usage = Some(0);
            }
            Shift::No if shift_pressed => {
                shift_pressed = false;
                last_usage = Some(0);
            }
            _ => {
                if last_usage == Some(key_stroke.usage) {
                    last_usage = Some(0);
                }
            }
        }

        if let Some(0) = last_usage {
            reports.push(KeyboardReport {
                pressed_keys: if shift_pressed {
                    vec![Usages::HidUsageKeyLeftShift as u32]
                } else {
                    vec![]
                },
            });
        }

        last_usage = Some(key_stroke.usage);

        reports.push(KeyboardReport {
            pressed_keys: if shift_pressed {
                vec![key_stroke.usage, Usages::HidUsageKeyLeftShift as u32]
            } else {
                vec![key_stroke.usage]
            },
        });
    }

    reports.push(KeyboardReport { pressed_keys: vec![] });

    Some(reports)
}

fn convert_keyboard_report_to_keys(report: &KeyboardReport) -> Vec<Key> {
    report
        .pressed_keys
        .iter()
        .map(|&usage| {
            hid_usage_to_input3_key(usage.try_into().expect("failed to convert usage to u16"))
                .unwrap_or_else(|| panic!("no Key for usage {:?}", usage))
        })
        .collect()
}

async fn register_touch_screen(
    mut registry: input_device_registry::InputDeviceRegistry,
    task_group: &mut fasync::TaskGroup,
    device_server_end: fidl::endpoints::ServerEnd<TouchScreenMarker>,
    got_input_reports_reader: AsyncEvent,
    min_x: i64,
    max_x: i64,
    min_y: i64,
    max_y: i64,
) -> input_device::DeviceId {
    let device = registry
        .add_touchscreen_device(min_x, max_x, min_y, max_y)
        .await
        .expect("failed to create fake touchscreen device");
    let device_id = device.device_id;

    task_group.spawn(async move {
        handle_touchscreen_request_stream(
            device,
            device_server_end
                .into_stream()
                .expect("failed to convert touchscreen device to stream"),
        )
        .await;
    });

    info!("wait for input-pipeline setup input-reader");
    let _ = got_input_reports_reader.wait().await;
    info!("input-pipeline setup input-reader.");

    device_id
}

async fn register_media_button(
    mut registry: input_device_registry::InputDeviceRegistry,
    task_group: &mut fasync::TaskGroup,
    device_server_end: fidl::endpoints::ServerEnd<MediaButtonsDeviceMarker>,
    got_input_reports_reader: AsyncEvent,
) -> input_device::DeviceId {
    let device = registry
        .add_media_buttons_device()
        .await
        .expect("failed to create fake media buttons device");
    let device_id = device.device_id;

    task_group.spawn(async move {
        handle_media_buttons_device_request_stream(
            device,
            device_server_end
                .into_stream()
                .expect("failed to convert media buttons device to stream"),
        )
        .await;
    });

    info!("wait for input-pipeline setup input-reader");
    let _ = got_input_reports_reader.wait().await;
    info!("input-pipeline setup input-reader.");

    device_id
}

async fn register_keyboard(
    mut registry: input_device_registry::InputDeviceRegistry,
    task_group: &mut fasync::TaskGroup,
    device_server_end: fidl::endpoints::ServerEnd<KeyboardMarker>,
    got_input_reports_reader: AsyncEvent,
) -> input_device::DeviceId {
    let device = registry.add_keyboard_device().await.expect("failed to create fake keyboard");
    let device_id = device.device_id;

    task_group.spawn(async move {
        handle_keyboard_request_stream(
            device,
            device_server_end.into_stream().expect("failed to convert keyboard to stream"),
        )
        .await;
    });

    info!("wait for input-pipeline setup input-reader");
    let _ = got_input_reports_reader.wait().await;
    info!("input-pipeline setup input-reader.");

    device_id
}

async fn register_mouse(
    mut registry: input_device_registry::InputDeviceRegistry,
    task_group: &mut fasync::TaskGroup,
    device_server_end: fidl::endpoints::ServerEnd<MouseMarker>,
    got_input_reports_reader: AsyncEvent,
) -> input_device::DeviceId {
    let device = registry.add_mouse_device().await.expect("failed to create fake mouse");
    let device_id = device.device_id;

    task_group.spawn(async move {
        handle_mouse_request_stream(
            device,
            device_server_end.into_stream().expect("failed to convert media mouse to stream"),
        )
        .await;
    });

    info!("wait for input-pipeline setup input-reader");
    let _ = got_input_reports_reader.wait().await;
    info!("input-pipeline setup input-reader.");

    device_id
}

/// Serves `fuchsia.ui.test.input.Registry`.
pub async fn handle_registry_request_stream(request_stream: RegistryRequestStream) {
    request_stream
        .try_for_each_concurrent(None, |request| async {
            let input_device_registry = connect_to_protocol::<InputDeviceRegistryMarker>()
                .expect("connect to input_device_registry");
            let got_input_reports_reader = AsyncEvent::new();

            let registry = input_device_registry::InputDeviceRegistry::new(
                input_device_registry,
                got_input_reports_reader.clone(),
            );
            let mut task_group = fasync::TaskGroup::new();

            match request {
                RegistryRequest::RegisterTouchScreen { payload, responder, .. } => {
                    info!("register touchscreen");
                    let device = payload
                        .device
                        .expect("no touchscreen device provided in registration request");
                    let (min_x, max_x, min_y, max_y) = match payload.coordinate_unit {
                        Some(CoordinateUnit::PhysicalPixels) => {
                            let display_info_proxy =
                                connect_to_protocol::<display_info::InfoMarker>()
                                    .expect("failed to connect to display info service");
                            let display_dimensions = display_info_proxy
                                .get_metrics()
                                .await
                                .expect("failed to get display metrics")
                                .extent_in_px
                                .expect("display metrics missing extent in px");
                            (
                                0,
                                display_dimensions.width as i64,
                                0,
                                display_dimensions.height as i64,
                            )
                        }
                        _ => (-1000, 1000, -1000, 1000),
                    };

                    register_touch_screen(
                        registry,
                        &mut task_group,
                        device,
                        got_input_reports_reader,
                        min_x,
                        max_x,
                        min_y,
                        max_y,
                    )
                    .await;

                    responder.send().expect("Failed to respond to RegisterTouchScreen request");
                }
                RegistryRequest::RegisterTouchScreenAndGetDeviceInfo {
                    payload, responder, ..
                } => {
                    info!("register touchscreen");
                    let device = payload
                        .device
                        .expect("no touchscreen device provided in registration request");
                    let (min_x, max_x, min_y, max_y) = match payload.coordinate_unit {
                        Some(CoordinateUnit::PhysicalPixels) => {
                            let display_info_proxy =
                                connect_to_protocol::<display_info::InfoMarker>()
                                    .expect("failed to connect to display info service");
                            let display_dimensions = display_info_proxy
                                .get_metrics()
                                .await
                                .expect("failed to get display metrics")
                                .extent_in_px
                                .expect("display metrics missing extent in px");
                            (
                                0,
                                display_dimensions.width as i64,
                                0,
                                display_dimensions.height as i64,
                            )
                        }
                        _ => (-1000, 1000, -1000, 1000),
                    };

                    let device_id = register_touch_screen(
                        registry,
                        &mut task_group,
                        device,
                        got_input_reports_reader,
                        min_x,
                        max_x,
                        min_y,
                        max_y,
                    )
                    .await;

                    responder
                        .send(RegistryRegisterTouchScreenAndGetDeviceInfoResponse {
                            device_id: Some(device_id),
                            ..Default::default()
                        })
                        .expect("Failed to respond to RegisterTouchScreenAndGetDeviceInfo request");
                }
                RegistryRequest::RegisterMediaButtonsDevice { payload, responder, .. } => {
                    info!("register media buttons device");
                    let device = payload
                        .device
                        .expect("no media buttons device provided in registration request");

                    register_media_button(
                        registry,
                        &mut task_group,
                        device,
                        got_input_reports_reader,
                    )
                    .await;

                    responder
                        .send()
                        .expect("Failed to respond to RegisterMediaButtonsDevice request");
                }
                RegistryRequest::RegisterMediaButtonsDeviceAndGetDeviceInfo {
                    payload,
                    responder,
                    ..
                } => {
                    info!("register media buttons device");
                    let device = payload
                        .device
                        .expect("no media buttons device provided in registration request");

                    let device_id = register_media_button(
                        registry,
                        &mut task_group,
                        device,
                        got_input_reports_reader,
                    )
                    .await;

                    responder.send(RegistryRegisterMediaButtonsDeviceAndGetDeviceInfoResponse {
                        device_id: Some(device_id),
                        ..Default::default()
                    }).expect(
                        "Failed to respond to RegisterMediaButtonsDeviceAndGetDeviceInfo request",
                    );
                }
                RegistryRequest::RegisterKeyboard { payload, responder, .. } => {
                    info!("register keyboard device");
                    let device = payload
                        .device
                        .expect("no keyboard device provided in registration request");

                    register_keyboard(registry, &mut task_group, device, got_input_reports_reader)
                        .await;

                    responder.send().expect("Failed to respond to RegisterKeyboard request");
                }
                RegistryRequest::RegisterKeyboardAndGetDeviceInfo {
                    payload, responder, ..
                } => {
                    info!("register keyboard device");
                    let device = payload
                        .device
                        .expect("no keyboard device provided in registration request");

                    let device_id = register_keyboard(
                        registry,
                        &mut task_group,
                        device,
                        got_input_reports_reader,
                    )
                    .await;

                    responder
                        .send(RegistryRegisterKeyboardAndGetDeviceInfoResponse {
                            device_id: Some(device_id),
                            ..Default::default()
                        })
                        .expect("Failed to respond to RegisterKeyboardAndGetDeviceInfo request");
                }
                RegistryRequest::RegisterMouse { payload, responder } => {
                    info!("register mouse device");
                    let device = payload.device.expect("no mouse provided in registration request");

                    register_mouse(registry, &mut task_group, device, got_input_reports_reader)
                        .await;

                    responder.send().expect("Failed to respond to RegisterMouse request");
                }
                RegistryRequest::RegisterMouseAndGetDeviceInfo { payload, responder } => {
                    info!("register mouse device");
                    let device = payload.device.expect("no mouse provided in registration request");

                    let device_id =
                        register_mouse(registry, &mut task_group, device, got_input_reports_reader)
                            .await;

                    responder
                        .send(RegistryRegisterMouseAndGetDeviceInfoResponse {
                            device_id: Some(device_id),
                            ..Default::default()
                        })
                        .expect("Failed to respond to RegisterMouse request");
                }
            }

            task_group.join().await;
            Ok(())
        })
        .await
        .expect("failed to serve test realm factory request stream");
}

fn input_report_for_touch_contacts(contacts: Vec<(u32, math::Vec_)>) -> InputReport {
    let contact_input_reports = contacts
        .into_iter()
        .map(|(contact_id, location)| ContactInputReport {
            contact_id: Some(contact_id),
            position_x: Some(location.x as i64),
            position_y: Some(location.y as i64),
            contact_width: Some(0),
            contact_height: Some(0),
            ..Default::default()
        })
        .collect();

    let touch_input_report = TouchInputReport {
        contacts: Some(contact_input_reports),
        pressed_buttons: Some(vec![]),
        ..Default::default()
    };

    InputReport {
        event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
        touch: Some(touch_input_report),
        ..Default::default()
    }
}

/// Serves `fuchsia.ui.test.input.TouchScreen`.
async fn handle_touchscreen_request_stream(
    touchscreen_device: input_device::InputDevice,
    mut request_stream: TouchScreenRequestStream,
) {
    while let Some(request) = request_stream.next().await {
        match request {
            Ok(TouchScreenRequest::SimulateTap { payload, responder }) => {
                if let Some(tap_location) = payload.tap_location {
                    touchscreen_device
                        .send_input_report(input_report_for_touch_contacts(vec![(1, tap_location)]))
                        .expect("Failed to send tap input report");

                    // Send a report with an empty set of touch contacts, so that input
                    // pipeline generates a pointer event with phase == UP.
                    touchscreen_device
                        .send_input_report(input_report_for_touch_contacts(vec![]))
                        .expect("failed to send empty input report");

                    responder.send().expect("Failed to send SimulateTap response");
                } else {
                    warn!("SimulateTap request missing tap location");
                }
            }
            Ok(TouchScreenRequest::SimulateSwipe { payload, responder }) => {
                // Compute the x- and y- displacements between successive touch events.
                let start_location = payload.start_location.expect("missing start location");
                let end_location = payload.end_location.expect("missing end location");
                let move_event_count = payload.move_event_count.expect("missing move event count");
                assert_ne!(move_event_count, 0);

                let start_x_f = start_location.x as f64;
                let start_y_f = start_location.y as f64;
                let end_x_f = end_location.x as f64;
                let end_y_f = end_location.y as f64;
                let move_event_count_f = move_event_count as f64;
                let step_size_x = (end_x_f - start_x_f) / move_event_count_f;
                let step_size_y = (end_y_f - start_y_f) / move_event_count_f;

                // Generate an event at `start_location`, followed by `move_event_count - 1`
                // evenly-spaced events, followed by an event at `end_location`.
                for i in 0..move_event_count + 1 {
                    let i_f = i as f64;
                    let event_x = start_x_f + (i_f * step_size_x);
                    let event_y = start_y_f + (i_f * step_size_y);
                    touchscreen_device
                        .send_input_report(input_report_for_touch_contacts(vec![(
                            1,
                            math::Vec_ { x: event_x as i32, y: event_y as i32 },
                        )]))
                        .expect("Failed to send tap input report");
                }

                // Send a report with an empty set of touch contacts, so that input
                // pipeline generates a pointer event with phase == UP.
                touchscreen_device
                    .send_input_report(input_report_for_touch_contacts(vec![]))
                    .expect("failed to send empty input report");

                responder.send().expect("Failed to send SimulateSwipe response");
            }
            Ok(TouchScreenRequest::SimulateMultiTap { payload, responder }) => {
                let tap_locations = payload.tap_locations.expect("missing tap locations");
                touchscreen_device
                    .send_input_report(input_report_for_touch_contacts(
                        tap_locations
                            .into_iter()
                            .enumerate()
                            .map(|(i, it)| (i as u32, it))
                            .collect(),
                    ))
                    .expect("Failed to send tap input report");

                // Send a report with an empty set of touch contacts, so that input
                // pipeline generates a pointer event with phase == UP.
                touchscreen_device
                    .send_input_report(input_report_for_touch_contacts(vec![]))
                    .expect("failed to send empty input report");
                responder.send().expect("Failed to send SimulateMultiTap response");
            }
            Ok(TouchScreenRequest::SimulateMultiFingerGesture { payload, responder }) => {
                // Compute the x- and y- displacements between successive touch events.
                let start_locations = payload.start_locations.expect("missing start locations");
                let end_locations = payload.end_locations.expect("missing end locations");
                let move_event_count = payload.move_event_count.expect("missing move event count");
                let finger_count = payload.finger_count.expect("missing finger count") as usize;

                let move_event_count_f = move_event_count as f32;

                let mut steps: Vec<math::VecF> = vec![];

                for finger in 0..finger_count {
                    let start_x = start_locations[finger].x as f32;
                    let start_y = start_locations[finger].y as f32;
                    let end_x = end_locations[finger].x as f32;
                    let end_y = end_locations[finger].y as f32;
                    let step_x = (end_x - start_x) / move_event_count_f;
                    let step_y = (end_y - start_y) / move_event_count_f;
                    steps.push(math::VecF { x: step_x, y: step_y });
                }

                // Generate an event at `start_location`, followed by `move_event_count - 1`
                // evenly-spaced events, followed by an event at `end_location`.
                for i in 0..move_event_count {
                    let i_f = i as f32;

                    let mut contacts: Vec<(u32, math::Vec_)> = vec![];

                    for finger in 0..finger_count {
                        let start_x = start_locations[finger].x as f32;
                        let start_y = start_locations[finger].y as f32;
                        let event_x = (start_x + i_f * steps[finger].x) as i32;
                        let event_y = (start_y + i_f * steps[finger].y) as i32;
                        contacts.push((finger as u32, math::Vec_ { x: event_x, y: event_y }));
                    }

                    touchscreen_device
                        .send_input_report(input_report_for_touch_contacts(contacts))
                        .expect("Failed to send tap input report");
                }

                // Send a report with an empty set of touch contacts, so that input
                // pipeline generates a pointer event with phase == UP.
                touchscreen_device
                    .send_input_report(input_report_for_touch_contacts(vec![]))
                    .expect("failed to send empty input report");

                responder.send().expect("Failed to send SimulateMultiFingerGesture response");
            }
            Ok(TouchScreenRequest::SimulateTouchEvent { report, responder }) => {
                let input_report = InputReport {
                    event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
                    touch: Some(report),
                    ..Default::default()
                };
                touchscreen_device
                    .send_input_report(input_report)
                    .expect("failed to send empty input report");
                responder.send().expect("Failed to send SimulateTouchEvent response");
            }
            Err(e) => {
                error!("Error on touchscreen channel: {}", e);
                return;
            }
        }
    }
}

/// Serves `fuchsia.ui.test.input.MediaButtonsDevice`.
async fn handle_media_buttons_device_request_stream(
    media_buttons_device: input_device::InputDevice,
    mut request_stream: MediaButtonsDeviceRequestStream,
) {
    while let Some(request) = request_stream.next().await {
        match request {
            Ok(MediaButtonsDeviceRequest::SimulateButtonPress { payload, responder }) => {
                if let Some(button) = payload.button {
                    let media_buttons_input_report = ConsumerControlInputReport {
                        pressed_buttons: Some(vec![button]),
                        ..Default::default()
                    };

                    let input_report = InputReport {
                        event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
                        consumer_control: Some(media_buttons_input_report),
                        ..Default::default()
                    };

                    media_buttons_device
                        .send_input_report(input_report)
                        .expect("Failed to send button press input report");

                    // Send a report with an empty set of pressed buttons,
                    // so that input pipeline generates a media buttons
                    // event with the target button being released.
                    let empty_report = InputReport {
                        event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
                        consumer_control: Some(ConsumerControlInputReport {
                            pressed_buttons: Some(vec![]),
                            ..Default::default()
                        }),
                        ..Default::default()
                    };

                    media_buttons_device
                        .send_input_report(empty_report)
                        .expect("Failed to send button release input report");

                    responder.send().expect("Failed to send SimulateButtonPress response");
                } else {
                    warn!("SimulateButtonPress request missing button");
                }
            }
            Ok(MediaButtonsDeviceRequest::SendButtonsState { payload, responder }) => {
                let buttons = match payload.buttons {
                    Some(buttons) => buttons,
                    None => vec![],
                };
                let input_report = InputReport {
                    event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
                    consumer_control: Some(ConsumerControlInputReport {
                        pressed_buttons: Some(buttons),
                        ..Default::default()
                    }),
                    ..Default::default()
                };

                media_buttons_device
                    .send_input_report(input_report)
                    .expect("Failed to send button press input report");

                responder.send().expect("Failed to send SimulateButtonsPress response");
            }
            Err(e) => {
                error!("Error on media buttons device channel: {}", e);
                return;
            }
        }
    }
}

/// Serves `fuchsia.ui.test.input.Keyboard`.
async fn handle_keyboard_request_stream(
    keyboard_device: input_device::InputDevice,
    mut request_stream: KeyboardRequestStream,
) {
    while let Some(request) = request_stream.next().await {
        match request {
            Ok(KeyboardRequest::SimulateUsAsciiTextEntry { payload, responder }) => {
                if let Some(text) = payload.text {
                    let key_sequence = derive_key_sequence(&keymaps::US_QWERTY, &text)
                        .expect("Failed to derive key sequence");

                    let mut key_iter = key_sequence.into_iter().peekable();
                    while let Some(keyboard_report) = key_iter.next() {
                        let input_report = InputReport {
                            event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
                            keyboard: Some(KeyboardInputReport {
                                pressed_keys3: Some(convert_keyboard_report_to_keys(
                                    &keyboard_report,
                                )),
                                ..Default::default()
                            }),
                            ..Default::default()
                        };

                        keyboard_device
                            .send_input_report(input_report)
                            .expect("Failed to send key event report");

                        if key_iter.peek().is_some() {
                            fuchsia_async::Timer::new(Duration::from_millis(100)).await;
                        }
                    }

                    responder.send().expect("Failed to send SimulateTextEntry response");
                } else {
                    warn!("SimulateTextEntry request missing text");
                }
            }
            Ok(KeyboardRequest::SimulateKeyEvent { payload, responder }) => {
                let keyboard_report = payload.report.expect("no report");
                let input_report = InputReport {
                    event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
                    keyboard: Some(keyboard_report),
                    ..Default::default()
                };

                keyboard_device
                    .send_input_report(input_report)
                    .expect("Failed to send key event report");

                responder.send().expect("Failed to send SimulateKeyEvent response");
            }
            Err(e) => {
                error!("Error on keyboard device channel: {}", e);
                return;
            }
        }
    }
}

/// Serves `fuchsia.ui.test.input.Mouse`.
async fn handle_mouse_request_stream(
    mouse_device: input_device::InputDevice,
    mut request_stream: MouseRequestStream,
) {
    while let Some(request) = request_stream.next().await {
        match request {
            Ok(MouseRequest::SimulateMouseEvent { payload, responder }) => {
                let mut mouse_input_report = MouseInputReport {
                    movement_x: payload.movement_x,
                    movement_y: payload.movement_y,
                    scroll_v: payload.scroll_v_detent,
                    scroll_h: payload.scroll_h_detent,
                    ..Default::default()
                };
                if let Some(pressed_buttons) = payload.pressed_buttons {
                    mouse_input_report.pressed_buttons = Some(
                        pressed_buttons
                            .into_iter()
                            .map(|b| {
                                b.into_primitive()
                                    .try_into()
                                    .expect("failed to convert MouseButton to u8")
                            })
                            .collect(),
                    );
                }

                let input_report = InputReport {
                    event_time: Some(fasync::MonotonicInstant::now().into_nanos()),
                    mouse: Some(mouse_input_report),
                    ..Default::default()
                };

                mouse_device
                    .send_input_report(input_report)
                    .expect("Failed to send key event report");

                responder.send().expect("Failed to send SimulateMouseEvent response");
            }
            Err(e) => {
                error!("Error on keyboard device channel: {}", e);
                return;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    // Most of the functions in this file need to bind to FIDL services in
    // this component's environment to do their work, but a component can't
    // modify its own environment. Hence, we can't validate those functions.
    //
    // However, we can (and do) validate derive_key_sequence().

    use super::{derive_key_sequence, KeyboardReport, Usages};
    use pretty_assertions::assert_eq;

    // TODO(https://fxbug.dev/42059899): Remove this macro.
    macro_rules! reports {
        ( $( [ $( $usages:expr ),* ] ),* $( , )? ) => {
            Some(vec![
                $(
                    KeyboardReport {
                        pressed_keys: vec![$($usages as u32),*]
                    }
                ),*
            ])
        }
    }

    #[test]
    fn lowercase() {
        assert_eq!(
            derive_key_sequence(&keymaps::US_QWERTY, "lowercase"),
            reports![
                [Usages::HidUsageKeyL],
                [Usages::HidUsageKeyO],
                [Usages::HidUsageKeyW],
                [Usages::HidUsageKeyE],
                [Usages::HidUsageKeyR],
                [Usages::HidUsageKeyC],
                [Usages::HidUsageKeyA],
                [Usages::HidUsageKeyS],
                [Usages::HidUsageKeyE],
                [],
            ]
        );
    }

    #[test]
    fn numerics() {
        assert_eq!(
            derive_key_sequence(&keymaps::US_QWERTY, "0123456789"),
            reports![
                [Usages::HidUsageKey0],
                [Usages::HidUsageKey1],
                [Usages::HidUsageKey2],
                [Usages::HidUsageKey3],
                [Usages::HidUsageKey4],
                [Usages::HidUsageKey5],
                [Usages::HidUsageKey6],
                [Usages::HidUsageKey7],
                [Usages::HidUsageKey8],
                [Usages::HidUsageKey9],
                [],
            ]
        );
    }

    #[test]
    fn internet_text_entry() {
        assert_eq!(
            derive_key_sequence(&keymaps::US_QWERTY, "http://127.0.0.1:8080"),
            reports![
                [Usages::HidUsageKeyH],
                [Usages::HidUsageKeyT],
                [],
                [Usages::HidUsageKeyT],
                [Usages::HidUsageKeyP],
                // ':'
                // Shift is actuated first on its own, then together with
                // the key.
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeySemicolon, Usages::HidUsageKeyLeftShift],
                [],
                [Usages::HidUsageKeySlash],
                [],
                [Usages::HidUsageKeySlash],
                [Usages::HidUsageKey1],
                [Usages::HidUsageKey2],
                [Usages::HidUsageKey7],
                [Usages::HidUsageKeyDot],
                [Usages::HidUsageKey0],
                [Usages::HidUsageKeyDot],
                [Usages::HidUsageKey0],
                [Usages::HidUsageKeyDot],
                [Usages::HidUsageKey1],
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeySemicolon, Usages::HidUsageKeyLeftShift],
                [],
                [Usages::HidUsageKey8],
                [Usages::HidUsageKey0],
                [Usages::HidUsageKey8],
                [Usages::HidUsageKey0],
                [],
            ]
        );
    }

    #[test]
    fn sentence() {
        assert_eq!(
            derive_key_sequence(&keymaps::US_QWERTY, "Hello, world!"),
            reports![
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyH, Usages::HidUsageKeyLeftShift],
                [],
                [Usages::HidUsageKeyE],
                [Usages::HidUsageKeyL],
                [],
                [Usages::HidUsageKeyL],
                [Usages::HidUsageKeyO],
                [Usages::HidUsageKeyComma],
                [Usages::HidUsageKeySpace],
                [Usages::HidUsageKeyW],
                [Usages::HidUsageKeyO],
                [Usages::HidUsageKeyR],
                [Usages::HidUsageKeyL],
                [Usages::HidUsageKeyD],
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKey1, Usages::HidUsageKeyLeftShift],
                [],
            ]
        );
    }

    #[test]
    fn hold_shift() {
        assert_eq!(
            derive_key_sequence(&keymaps::US_QWERTY, "ALL'S WELL!"),
            reports![
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyA, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyL, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyL, Usages::HidUsageKeyLeftShift],
                [],
                [Usages::HidUsageKeyApostrophe],
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyS, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeySpace, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyW, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyE, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyL, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyL, Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKey1, Usages::HidUsageKeyLeftShift],
                [],
            ]
        );
    }

    #[test]
    fn tab_and_newline() {
        assert_eq!(
            derive_key_sequence(&keymaps::US_QWERTY, "\tHello\n"),
            reports![
                [Usages::HidUsageKeyTab],
                [Usages::HidUsageKeyLeftShift],
                [Usages::HidUsageKeyH, Usages::HidUsageKeyLeftShift],
                [],
                [Usages::HidUsageKeyE],
                [Usages::HidUsageKeyL],
                [],
                [Usages::HidUsageKeyL],
                [Usages::HidUsageKeyO],
                [Usages::HidUsageKeyEnter],
                [],
            ]
        );
    }
}