1use crate::{
6 Dispatcher, Incoming, Transport, consumer_controls_binding, keyboard_binding,
7 light_sensor_binding, metrics, mouse_binding, touch_binding,
8};
9use anyhow::{Error, format_err};
10use async_trait::async_trait;
11use fidl_fuchsia_io as fio;
12use fidl_next_fuchsia_input_report::InputDevice;
13use fuchsia_inspect::health::Reporter;
14use fuchsia_inspect::{
15 ExponentialHistogramParams, HistogramProperty as _, NumericProperty, Property,
16};
17use fuchsia_trace as ftrace;
18use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
19use futures::stream::StreamExt;
20use metrics_registry::*;
21use sorted_vec_map::SortedVecSet;
22use std::path::Path;
23use strum_macros::{Display, EnumCount};
24
25pub use input_device_constants::InputDeviceType;
26
27#[derive(Debug, Clone, Default)]
28pub struct InputPipelineFeatureFlags {
29 pub enable_merge_touch_events: bool,
31}
32
33pub static INPUT_REPORT_PATH: &str = "/svc/fuchsia.input.report.Service";
35
36const LATENCY_HISTOGRAM_PROPERTIES: ExponentialHistogramParams<i64> = ExponentialHistogramParams {
37 floor: 0,
38 initial_step: 1,
39 step_multiplier: 10,
40 buckets: 7,
51};
52
53pub struct InputDeviceStatus {
56 now: Box<dyn Fn() -> zx::MonotonicInstant>,
59
60 _node: fuchsia_inspect::Node,
62
63 reports_received_count: fuchsia_inspect::UintProperty,
65
66 reports_filtered_count: fuchsia_inspect::UintProperty,
69
70 events_generated: fuchsia_inspect::UintProperty,
73
74 last_received_timestamp_ns: fuchsia_inspect::UintProperty,
76
77 last_generated_timestamp_ns: fuchsia_inspect::UintProperty,
79
80 pub health_node: fuchsia_inspect::health::Node,
82
83 driver_to_binding_latency_ms: fuchsia_inspect::IntExponentialHistogramProperty,
88
89 wake_lease_leak_count: fuchsia_inspect::UintProperty,
91}
92
93impl InputDeviceStatus {
94 pub fn new(device_node: fuchsia_inspect::Node) -> Self {
95 Self::new_internal(device_node, Box::new(zx::MonotonicInstant::get))
96 }
97
98 fn new_internal(
99 device_node: fuchsia_inspect::Node,
100 now: Box<dyn Fn() -> zx::MonotonicInstant>,
101 ) -> Self {
102 let mut health_node = fuchsia_inspect::health::Node::new(&device_node);
103 health_node.set_starting_up();
104
105 let reports_received_count = device_node.create_uint("reports_received_count", 0);
106 let reports_filtered_count = device_node.create_uint("reports_filtered_count", 0);
107 let events_generated = device_node.create_uint("events_generated", 0);
108 let last_received_timestamp_ns = device_node.create_uint("last_received_timestamp_ns", 0);
109 let last_generated_timestamp_ns = device_node.create_uint("last_generated_timestamp_ns", 0);
110 let driver_to_binding_latency_ms = device_node.create_int_exponential_histogram(
111 "driver_to_binding_latency_ms",
112 LATENCY_HISTOGRAM_PROPERTIES,
113 );
114 let wake_lease_leak_count = device_node.create_uint("wake_lease_leak_count", 0);
115
116 Self {
117 now,
118 _node: device_node,
119 reports_received_count,
120 reports_filtered_count,
121 events_generated,
122 last_received_timestamp_ns,
123 last_generated_timestamp_ns,
124 health_node,
125 driver_to_binding_latency_ms,
126 wake_lease_leak_count,
127 }
128 }
129
130 pub fn count_received_report_wire(
131 &self,
132 report: &fidl_next_fuchsia_input_report::wire::InputReport<'_>,
133 ) {
134 self.reports_received_count.add(1);
135 match report.event_time() {
136 Some(event_time) => {
137 self.driver_to_binding_latency_ms.insert(
138 ((self.now)() - zx::MonotonicInstant::from_nanos(event_time.0)).into_millis(),
139 );
140 self.last_received_timestamp_ns.set(event_time.0.try_into().unwrap());
141 }
142 None => (),
143 }
144 }
145
146 pub fn count_filtered_report(&self) {
147 self.reports_filtered_count.add(1);
148 }
149
150 pub fn count_generated_event(&self, event: InputEvent) {
151 self.events_generated.add(1);
152 self.last_generated_timestamp_ns.set(event.event_time.into_nanos().try_into().unwrap());
153 }
154
155 pub fn count_generated_events(&self, events: &Vec<InputEvent>) {
156 self.events_generated.add(events.len() as u64);
157 if let Some(last_event) = events.last() {
158 self.last_generated_timestamp_ns
159 .set(last_event.event_time.into_nanos().try_into().unwrap());
160 }
161 }
162
163 pub fn count_wake_lease_leak(&self) {
164 self.wake_lease_leak_count.add(1);
165 }
166}
167
168#[derive(Clone, Debug, PartialEq)]
169pub enum PreviousDeviceState {
170 Keyboard {
171 pressed_keys: Vec<fidl_fuchsia_input::Key>,
172 },
173 Mouse {
174 pressed_buttons: SortedVecSet<mouse_binding::MouseButton>,
175 },
176 TouchScreen {
177 active_contacts: Vec<touch_binding::TouchContact>,
178 pressed_buttons: Vec<fidl_next_fuchsia_input_report::TouchButton>,
179 },
180 ConsumerControls {
181 pressed_buttons: Vec<fidl_fuchsia_input::ConsumerControlButton>,
182 },
183 LightSensor,
184 #[cfg(test)]
185 Fake,
186}
187
188#[derive(Clone, Debug, PartialEq)]
190pub struct InputEvent {
191 pub device_event: InputDeviceEvent,
193
194 pub device_descriptor: InputDeviceDescriptor,
197
198 pub event_time: zx::MonotonicInstant,
200
201 pub handled: Handled,
203
204 pub trace_id: Option<ftrace::Id>,
205}
206
207#[derive(Clone, Debug, PartialEq)]
213pub struct UnhandledInputEvent {
214 pub device_event: InputDeviceEvent,
216
217 pub device_descriptor: InputDeviceDescriptor,
220
221 pub event_time: zx::MonotonicInstant,
223
224 pub trace_id: Option<ftrace::Id>,
225}
226
227impl UnhandledInputEvent {
228 pub fn get_event_type(&self) -> &'static str {
230 match self.device_event {
231 InputDeviceEvent::Keyboard(_) => "keyboard_event",
232 InputDeviceEvent::LightSensor(_) => "light_sensor_event",
233 InputDeviceEvent::ConsumerControls(_) => "consumer_controls_event",
234 InputDeviceEvent::Mouse(_) => "mouse_event",
235 InputDeviceEvent::TouchScreen(_) => "touch_screen_event",
236 InputDeviceEvent::Touchpad(_) => "touchpad_event",
237 #[cfg(test)]
238 InputDeviceEvent::Fake => "fake_event",
239 }
240 }
241}
242
243#[derive(Clone, Debug, PartialEq)]
252pub enum InputDeviceEvent {
253 Keyboard(keyboard_binding::KeyboardEvent),
254 LightSensor(light_sensor_binding::LightSensorEvent),
255 ConsumerControls(consumer_controls_binding::ConsumerControlsEvent),
256 Mouse(mouse_binding::MouseEvent),
257 TouchScreen(touch_binding::TouchScreenEvent),
258 Touchpad(touch_binding::TouchpadEvent),
259 #[cfg(test)]
260 Fake,
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, EnumCount, Display)]
265#[strum(serialize_all = "snake_case")]
266pub enum InputEventType {
267 Keyboard = 0,
268 LightSensor = 1,
269 ConsumerControls = 2,
270 Mouse = 3,
271 TouchScreen = 4,
272 Touchpad = 5,
273 #[cfg(test)]
274 Fake = 6,
275}
276
277impl From<&InputDeviceEvent> for InputEventType {
278 fn from(event: &InputDeviceEvent) -> Self {
279 match event {
280 InputDeviceEvent::Keyboard(_) => InputEventType::Keyboard,
281 InputDeviceEvent::LightSensor(_) => InputEventType::LightSensor,
282 InputDeviceEvent::ConsumerControls(_) => InputEventType::ConsumerControls,
283 InputDeviceEvent::Mouse(_) => InputEventType::Mouse,
284 InputDeviceEvent::TouchScreen(_) => InputEventType::TouchScreen,
285 InputDeviceEvent::Touchpad(_) => InputEventType::Touchpad,
286 #[cfg(test)]
287 InputDeviceEvent::Fake => InputEventType::Fake,
288 }
289 }
290}
291
292#[derive(Clone, Debug, PartialEq)]
302pub enum InputDeviceDescriptor {
303 Keyboard(keyboard_binding::KeyboardDeviceDescriptor),
304 LightSensor(light_sensor_binding::LightSensorDeviceDescriptor),
305 ConsumerControls(consumer_controls_binding::ConsumerControlsDeviceDescriptor),
306 Mouse(mouse_binding::MouseDeviceDescriptor),
307 TouchScreen(touch_binding::TouchScreenDeviceDescriptor),
308 Touchpad(touch_binding::TouchpadDeviceDescriptor),
309 #[cfg(test)]
310 Fake,
311}
312
313impl From<keyboard_binding::KeyboardDeviceDescriptor> for InputDeviceDescriptor {
314 fn from(b: keyboard_binding::KeyboardDeviceDescriptor) -> Self {
315 InputDeviceDescriptor::Keyboard(b)
316 }
317}
318
319impl InputDeviceDescriptor {
320 pub fn device_id(&self) -> u32 {
321 match self {
322 InputDeviceDescriptor::Keyboard(b) => b.device_id,
323 InputDeviceDescriptor::LightSensor(b) => b.device_id,
324 InputDeviceDescriptor::ConsumerControls(b) => b.device_id,
325 InputDeviceDescriptor::Mouse(b) => b.device_id,
326 InputDeviceDescriptor::TouchScreen(b) => b.device_id,
327 InputDeviceDescriptor::Touchpad(b) => b.device_id,
328 #[cfg(test)]
329 InputDeviceDescriptor::Fake => 0,
330 }
331 }
332}
333
334#[derive(Copy, Clone, Debug, PartialEq)]
336pub enum Handled {
337 Yes,
339 No,
341}
342
343#[async_trait]
352pub trait InputDeviceBinding: Send {
353 fn get_device_descriptor(&self) -> InputDeviceDescriptor;
355
356 fn input_event_sender(&self) -> UnboundedSender<Vec<InputEvent>>;
358}
359
360pub fn initialize_report_stream<InputDeviceProcessReportsFn>(
377 device_proxy: fidl_next::Client<InputDevice, Transport>,
378 device_descriptor: InputDeviceDescriptor,
379 mut event_sender: UnboundedSender<Vec<InputEvent>>,
380 inspect_status: InputDeviceStatus,
381 metrics_logger: metrics::MetricsLogger,
382 feature_flags: InputPipelineFeatureFlags,
383 mut process_reports: InputDeviceProcessReportsFn,
384) where
385 InputDeviceProcessReportsFn: 'static
386 + Send
387 + for<'de> FnMut(
388 &[fidl_next_fuchsia_input_report::wire::InputReport<'_>],
389 Option<PreviousDeviceState>,
390 &InputDeviceDescriptor,
391 &mut UnboundedSender<Vec<InputEvent>>,
392 &InputDeviceStatus,
393 &metrics::MetricsLogger,
394 &InputPipelineFeatureFlags,
395 )
396 -> (Option<PreviousDeviceState>, Option<UnboundedReceiver<InputEvent>>),
397{
398 Dispatcher::spawn_local(async move {
399 let mut previous_state: Option<PreviousDeviceState> = None;
400 let (report_reader, server_end) = fidl_next::fuchsia::create_channel();
401 let report_reader = Dispatcher::client_from_zx_channel(report_reader);
402 let result = device_proxy.get_input_reports_reader(server_end).await;
403 if result.is_err() {
404 metrics_logger.log_error(
405 InputPipelineErrorMetricDimensionEvent::InputDeviceGetInputReportsReaderError,
406 std::format!("error on GetInputReportsReader: {:?}", result),
407 );
408 return; }
410 let report_reader = report_reader.spawn();
411 loop {
412 let read_result = {
413 fuchsia_trace::duration!("input", "read_input_reports");
414 report_reader.read_input_reports().wire().await
415 };
416 match read_result {
417 Err(_fidl_error) => break,
418 Ok(decoded) => match decoded.as_ref() {
419 Err(_service_error) => break,
420 Ok(response) => {
421 fuchsia_trace::duration!("input", "input-device-process-reports");
422 let (prev_state, inspect_receiver) = process_reports(
425 response.reports.as_slice(),
426 previous_state,
427 &device_descriptor,
428 &mut event_sender,
429 &inspect_status,
430 &metrics_logger,
431 &feature_flags,
432 );
433 previous_state = prev_state;
434
435 match inspect_receiver {
439 Some(mut receiver) => {
440 while let Some(event) = receiver.next().await {
441 inspect_status.count_generated_event(event);
442 }
443 }
444 None => (),
445 };
446 }
447 },
448 }
449 }
450 log::warn!("initialize_report_stream exited - device binding no longer works");
453 })
454 .detach();
455}
456
457pub async fn is_device_type(
463 device_descriptor: &fidl_next_fuchsia_input_report::DeviceDescriptor,
464 device_type: InputDeviceType,
465) -> bool {
466 match device_type {
468 InputDeviceType::ConsumerControls => device_descriptor.consumer_control.is_some(),
469 InputDeviceType::Mouse => device_descriptor.mouse.is_some(),
470 InputDeviceType::Touch => device_descriptor.touch.is_some(),
471 InputDeviceType::Keyboard => device_descriptor.keyboard.is_some(),
472 InputDeviceType::LightSensor => device_descriptor.sensor.is_some(),
473 }
474}
475
476pub async fn get_device_binding(
484 device_type: InputDeviceType,
485 device_proxy: fidl_next::Client<fidl_next_fuchsia_input_report::InputDevice, Transport>,
486 device_id: u32,
487 input_event_sender: UnboundedSender<Vec<InputEvent>>,
488 device_node: fuchsia_inspect::Node,
489 feature_flags: InputPipelineFeatureFlags,
490 metrics_logger: metrics::MetricsLogger,
491 is_injected: bool,
492) -> Result<Box<dyn InputDeviceBinding>, Error> {
493 match device_type {
494 InputDeviceType::ConsumerControls => {
495 let binding = consumer_controls_binding::ConsumerControlsBinding::new(
496 device_proxy,
497 device_id,
498 input_event_sender,
499 device_node,
500 feature_flags.clone(),
501 metrics_logger,
502 is_injected,
503 )
504 .await?;
505 Ok(Box::new(binding))
506 }
507 InputDeviceType::Mouse => {
508 let binding = mouse_binding::MouseBinding::new(
509 device_proxy,
510 device_id,
511 input_event_sender,
512 device_node,
513 feature_flags.clone(),
514 metrics_logger,
515 )
516 .await?;
517 Ok(Box::new(binding))
518 }
519 InputDeviceType::Touch => {
520 let binding = touch_binding::TouchBinding::new(
521 device_proxy,
522 device_id,
523 input_event_sender,
524 device_node,
525 feature_flags.clone(),
526 metrics_logger,
527 )
528 .await?;
529 Ok(Box::new(binding))
530 }
531 InputDeviceType::Keyboard => {
532 let binding = keyboard_binding::KeyboardBinding::new(
533 device_proxy,
534 device_id,
535 input_event_sender,
536 device_node,
537 feature_flags.clone(),
538 metrics_logger,
539 )
540 .await?;
541 Ok(Box::new(binding))
542 }
543 InputDeviceType::LightSensor => {
544 let binding = light_sensor_binding::LightSensorBinding::new(
545 device_proxy,
546 device_id,
547 input_event_sender,
548 device_node,
549 feature_flags.clone(),
550 metrics_logger,
551 )
552 .await?;
553 Ok(Box::new(binding))
554 }
555 }
556}
557
558pub fn get_device_from_dir_entry_path(
567 dir_proxy: &fio::DirectoryProxy,
568 entry_path: &Path,
569) -> Result<fidl_next::Client<fidl_next_fuchsia_input_report::InputDevice, Transport>, Error> {
570 let input_device_path =
571 entry_path.to_str().ok_or_else(|| format_err!("Failed to get entry path as a string."))?;
572
573 let input_device = Incoming::connect_protocol_next_at(dir_proxy, input_device_path)
574 .map_err(|e| format_err!("Failed to connect to InputDevice: {:?}", e))?;
575 Ok(input_device.spawn())
576}
577
578pub fn event_time_or_now(event_time: Option<i64>) -> zx::MonotonicInstant {
583 match event_time {
584 Some(time) => zx::MonotonicInstant::from_nanos(time),
585 None => zx::MonotonicInstant::get(),
586 }
587}
588
589impl std::convert::From<UnhandledInputEvent> for InputEvent {
590 fn from(event: UnhandledInputEvent) -> Self {
591 Self {
592 device_event: event.device_event,
593 device_descriptor: event.device_descriptor,
594 event_time: event.event_time,
595 handled: Handled::No,
596 trace_id: event.trace_id,
597 }
598 }
599}
600
601#[cfg(test)]
608impl std::convert::TryFrom<InputEvent> for UnhandledInputEvent {
609 type Error = anyhow::Error;
610 fn try_from(event: InputEvent) -> Result<UnhandledInputEvent, Self::Error> {
611 match event.handled {
612 Handled::Yes => {
613 Err(format_err!("Attempted to treat a handled InputEvent as unhandled"))
614 }
615 Handled::No => Ok(UnhandledInputEvent {
616 device_event: event.device_event,
617 device_descriptor: event.device_descriptor,
618 event_time: event.event_time,
619 trace_id: event.trace_id,
620 }),
621 }
622 }
623}
624
625impl InputEvent {
626 pub(crate) fn into_handled_if(self, predicate: bool) -> Self {
629 if predicate { Self { handled: Handled::Yes, ..self } } else { self }
630 }
631
632 pub(crate) fn into_handled(self) -> Self {
634 Self { handled: Handled::Yes, ..self }
635 }
636
637 pub fn into_with_event_time(self, event_time: zx::MonotonicInstant) -> Self {
639 Self { event_time, ..self }
640 }
641
642 #[cfg(test)]
644 pub fn into_with_device_descriptor(self, device_descriptor: InputDeviceDescriptor) -> Self {
645 Self { device_descriptor, ..self }
646 }
647
648 pub fn is_handled(&self) -> bool {
650 self.handled == Handled::Yes
651 }
652
653 pub fn get_event_type(&self) -> &'static str {
655 match self.device_event {
656 InputDeviceEvent::Keyboard(_) => "keyboard_event",
657 InputDeviceEvent::LightSensor(_) => "light_sensor_event",
658 InputDeviceEvent::ConsumerControls(_) => "consumer_controls_event",
659 InputDeviceEvent::Mouse(_) => "mouse_event",
660 InputDeviceEvent::TouchScreen(_) => "touch_screen_event",
661 InputDeviceEvent::Touchpad(_) => "touchpad_event",
662 #[cfg(test)]
663 InputDeviceEvent::Fake => "fake_event",
664 }
665 }
666
667 pub fn record_inspect(&self, node: &fuchsia_inspect::Node) {
668 node.record_int("event_time", self.event_time.into_nanos());
669 match &self.device_event {
670 InputDeviceEvent::LightSensor(e) => e.record_inspect(node),
671 InputDeviceEvent::ConsumerControls(e) => e.record_inspect(node),
672 InputDeviceEvent::Mouse(e) => e.record_inspect(node),
673 InputDeviceEvent::TouchScreen(e) => e.record_inspect(node),
674 InputDeviceEvent::Touchpad(e) => e.record_inspect(node),
675 InputDeviceEvent::Keyboard(_) => (),
677 #[cfg(test)] InputDeviceEvent::Fake => (),
679 }
680 }
681}
682
683#[cfg(test)]
684mod tests {
685 use super::*;
686 use crate::testing_utilities::spawn_input_stream_handler;
687 use assert_matches::assert_matches;
688 use diagnostics_assertions::AnyProperty;
689 use fidl_fuchsia_input_report as fidl_input_report;
690 use fidl_next_fuchsia_input_report::InputReport;
691 use pretty_assertions::assert_eq;
692 use std::convert::TryFrom as _;
693 use test_case::test_case;
694
695 #[test]
696 fn max_event_time() {
697 let event_time = event_time_or_now(Some(i64::MAX));
698 assert_eq!(event_time, zx::MonotonicInstant::INFINITE);
699 }
700
701 #[test]
702 fn min_event_time() {
703 let event_time = event_time_or_now(Some(std::i64::MIN));
704 assert_eq!(event_time, zx::MonotonicInstant::INFINITE_PAST);
705 }
706
707 #[fuchsia::test]
708 async fn input_device_status_initialized_with_correct_properties() {
709 let inspector = fuchsia_inspect::Inspector::default();
710 let input_pipeline_node = inspector.root().create_child("input_pipeline");
711 let input_devices_node = input_pipeline_node.create_child("input_devices");
712 let device_node = input_devices_node.create_child("001_keyboard");
713 let _input_device_status = InputDeviceStatus::new(device_node);
714 diagnostics_assertions::assert_data_tree!(inspector, root: {
715 input_pipeline: {
716 input_devices: {
717 "001_keyboard": {
718 reports_received_count: 0u64,
719 reports_filtered_count: 0u64,
720 events_generated: 0u64,
721 last_received_timestamp_ns: 0u64,
722 last_generated_timestamp_ns: 0u64,
723 "fuchsia.inspect.Health": {
724 status: "STARTING_UP",
725 start_timestamp_nanos: AnyProperty
728 },
729 driver_to_binding_latency_ms: diagnostics_assertions::HistogramAssertion::exponential(super::LATENCY_HISTOGRAM_PROPERTIES),
730 wake_lease_leak_count: 0u64,
731 }
732 }
733 }
734 });
735 }
736
737 #[test_case(i64::MIN; "min value")]
738 #[test_case(-1; "negative value")]
739 #[test_case(0; "zero")]
740 #[test_case(1; "positive value")]
741 #[test_case(i64::MAX; "max value")]
742 #[fuchsia::test(allow_stalls = false)]
743 async fn input_device_status_updates_latency_histogram_on_count_received_report_wire(
744 latency_nsec: i64,
745 ) {
746 let mut expected_histogram = diagnostics_assertions::HistogramAssertion::exponential(
747 super::LATENCY_HISTOGRAM_PROPERTIES,
748 );
749 let inspector = fuchsia_inspect::Inspector::default();
750 let input_device_status = InputDeviceStatus::new_internal(
751 inspector.root().clone_weak(),
752 Box::new(move || zx::MonotonicInstant::from_nanos(latency_nsec)),
753 );
754 let decoded = crate::testing_utilities::report_to_wire(InputReport {
755 event_time: Some(0),
756 ..InputReport::default()
757 });
758 input_device_status.count_received_report_wire(&decoded);
759 expected_histogram.insert_values([latency_nsec / 1000 / 1000]);
760 diagnostics_assertions::assert_data_tree!(inspector, root: contains {
761 driver_to_binding_latency_ms: expected_histogram,
762 });
763 }
764
765 #[fuchsia::test]
768 async fn consumer_controls_input_device_exists() {
769 let (input_device_proxy, _task) =
770 spawn_input_stream_handler(move |input_device_request| async move {
771 match input_device_request {
772 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
773 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
774 device_information: None,
775 mouse: None,
776 sensor: None,
777 touch: None,
778 keyboard: None,
779 consumer_control: Some(fidl_input_report::ConsumerControlDescriptor {
780 input: Some(fidl_input_report::ConsumerControlInputDescriptor {
781 buttons: Some(vec![
782 fidl_fuchsia_input::ConsumerControlButton::VolumeUp,
783 fidl_fuchsia_input::ConsumerControlButton::VolumeDown,
784 ]),
785 ..Default::default()
786 }),
787 ..Default::default()
788 }),
789 ..Default::default()
790 });
791 }
792 _ => panic!("InputDevice handler received an unexpected request"),
793 }
794 });
795
796 assert!(
797 is_device_type(
798 &input_device_proxy
799 .get_descriptor()
800 .await
801 .expect("Failed to get device descriptor")
802 .descriptor,
803 InputDeviceType::ConsumerControls
804 )
805 .await
806 );
807 }
808
809 #[fuchsia::test]
811 async fn mouse_input_device_exists() {
812 let (input_device_proxy, _task) =
813 spawn_input_stream_handler(move |input_device_request| async move {
814 match input_device_request {
815 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
816 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
817 device_information: None,
818 mouse: Some(fidl_input_report::MouseDescriptor {
819 input: Some(fidl_input_report::MouseInputDescriptor {
820 movement_x: None,
821 movement_y: None,
822 position_x: None,
823 position_y: None,
824 scroll_v: None,
825 scroll_h: None,
826 buttons: None,
827 ..Default::default()
828 }),
829 ..Default::default()
830 }),
831 sensor: None,
832 touch: None,
833 keyboard: None,
834 consumer_control: None,
835 ..Default::default()
836 });
837 }
838 _ => panic!("InputDevice handler received an unexpected request"),
839 }
840 });
841
842 assert!(
843 is_device_type(
844 &input_device_proxy
845 .get_descriptor()
846 .await
847 .expect("Failed to get device descriptor")
848 .descriptor,
849 InputDeviceType::Mouse
850 )
851 .await
852 );
853 }
854
855 #[fuchsia::test]
858 async fn mouse_input_device_doesnt_exist() {
859 let (input_device_proxy, _task) =
860 spawn_input_stream_handler(move |input_device_request| async move {
861 match input_device_request {
862 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
863 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
864 device_information: None,
865 mouse: None,
866 sensor: None,
867 touch: None,
868 keyboard: None,
869 consumer_control: None,
870 ..Default::default()
871 });
872 }
873 _ => panic!("InputDevice handler received an unexpected request"),
874 }
875 });
876
877 assert!(
878 !is_device_type(
879 &input_device_proxy
880 .get_descriptor()
881 .await
882 .expect("Failed to get device descriptor")
883 .descriptor,
884 InputDeviceType::Mouse
885 )
886 .await
887 );
888 }
889
890 #[fuchsia::test]
893 async fn touch_input_device_exists() {
894 let (input_device_proxy, _task) =
895 spawn_input_stream_handler(move |input_device_request| async move {
896 match input_device_request {
897 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
898 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
899 device_information: None,
900 mouse: None,
901 sensor: None,
902 touch: Some(fidl_input_report::TouchDescriptor {
903 input: Some(fidl_input_report::TouchInputDescriptor {
904 contacts: None,
905 max_contacts: None,
906 touch_type: None,
907 buttons: None,
908 ..Default::default()
909 }),
910 ..Default::default()
911 }),
912 keyboard: None,
913 consumer_control: None,
914 ..Default::default()
915 });
916 }
917 _ => panic!("InputDevice handler received an unexpected request"),
918 }
919 });
920
921 assert!(
922 is_device_type(
923 &input_device_proxy
924 .get_descriptor()
925 .await
926 .expect("Failed to get device descriptor")
927 .descriptor,
928 InputDeviceType::Touch
929 )
930 .await
931 );
932 }
933
934 #[fuchsia::test]
937 async fn touch_input_device_doesnt_exist() {
938 let (input_device_proxy, _task) =
939 spawn_input_stream_handler(move |input_device_request| async move {
940 match input_device_request {
941 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
942 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
943 device_information: None,
944 mouse: None,
945 sensor: None,
946 touch: None,
947 keyboard: None,
948 consumer_control: None,
949 ..Default::default()
950 });
951 }
952 _ => panic!("InputDevice handler received an unexpected request"),
953 }
954 });
955
956 assert!(
957 !is_device_type(
958 &input_device_proxy
959 .get_descriptor()
960 .await
961 .expect("Failed to get device descriptor")
962 .descriptor,
963 InputDeviceType::Touch
964 )
965 .await
966 );
967 }
968
969 #[fuchsia::test]
972 async fn keyboard_input_device_exists() {
973 let (input_device_proxy, _task) =
974 spawn_input_stream_handler(move |input_device_request| async move {
975 match input_device_request {
976 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
977 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
978 device_information: None,
979 mouse: None,
980 sensor: None,
981 touch: None,
982 keyboard: Some(fidl_input_report::KeyboardDescriptor {
983 input: Some(fidl_input_report::KeyboardInputDescriptor {
984 keys3: None,
985 ..Default::default()
986 }),
987 output: None,
988 ..Default::default()
989 }),
990 consumer_control: None,
991 ..Default::default()
992 });
993 }
994 _ => panic!("InputDevice handler received an unexpected request"),
995 }
996 });
997
998 assert!(
999 is_device_type(
1000 &input_device_proxy
1001 .get_descriptor()
1002 .await
1003 .expect("Failed to get device descriptor")
1004 .descriptor,
1005 InputDeviceType::Keyboard
1006 )
1007 .await
1008 );
1009 }
1010
1011 #[fuchsia::test]
1014 async fn keyboard_input_device_doesnt_exist() {
1015 let (input_device_proxy, _task) =
1016 spawn_input_stream_handler(move |input_device_request| async move {
1017 match input_device_request {
1018 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
1019 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
1020 device_information: None,
1021 mouse: None,
1022 sensor: None,
1023 touch: None,
1024 keyboard: None,
1025 consumer_control: None,
1026 ..Default::default()
1027 });
1028 }
1029 _ => panic!("InputDevice handler received an unexpected request"),
1030 }
1031 });
1032
1033 assert!(
1034 !is_device_type(
1035 &input_device_proxy
1036 .get_descriptor()
1037 .await
1038 .expect("Failed to get device descriptor")
1039 .descriptor,
1040 InputDeviceType::Keyboard
1041 )
1042 .await
1043 );
1044 }
1045
1046 #[fuchsia::test]
1048 async fn no_input_device_match() {
1049 let (input_device_proxy, _task) =
1050 spawn_input_stream_handler(move |input_device_request| async move {
1051 match input_device_request {
1052 fidl_input_report::InputDeviceRequest::GetDescriptor { responder } => {
1053 let _ = responder.send(&fidl_input_report::DeviceDescriptor {
1054 device_information: None,
1055 mouse: Some(fidl_input_report::MouseDescriptor {
1056 input: Some(fidl_input_report::MouseInputDescriptor {
1057 movement_x: None,
1058 movement_y: None,
1059 position_x: None,
1060 position_y: None,
1061 scroll_v: None,
1062 scroll_h: None,
1063 buttons: None,
1064 ..Default::default()
1065 }),
1066 ..Default::default()
1067 }),
1068 sensor: None,
1069 touch: Some(fidl_input_report::TouchDescriptor {
1070 input: Some(fidl_input_report::TouchInputDescriptor {
1071 contacts: None,
1072 max_contacts: None,
1073 touch_type: None,
1074 buttons: None,
1075 ..Default::default()
1076 }),
1077 ..Default::default()
1078 }),
1079 keyboard: Some(fidl_input_report::KeyboardDescriptor {
1080 input: Some(fidl_input_report::KeyboardInputDescriptor {
1081 keys3: None,
1082 ..Default::default()
1083 }),
1084 output: None,
1085 ..Default::default()
1086 }),
1087 consumer_control: Some(fidl_input_report::ConsumerControlDescriptor {
1088 input: Some(fidl_input_report::ConsumerControlInputDescriptor {
1089 buttons: Some(vec![
1090 fidl_fuchsia_input::ConsumerControlButton::VolumeUp,
1091 fidl_fuchsia_input::ConsumerControlButton::VolumeDown,
1092 ]),
1093 ..Default::default()
1094 }),
1095 ..Default::default()
1096 }),
1097 ..Default::default()
1098 });
1099 }
1100 _ => panic!("InputDevice handler received an unexpected request"),
1101 }
1102 });
1103
1104 let device_descriptor = &input_device_proxy
1105 .get_descriptor()
1106 .await
1107 .expect("Failed to get device descriptor")
1108 .descriptor;
1109 assert!(is_device_type(&device_descriptor, InputDeviceType::ConsumerControls).await);
1110 assert!(is_device_type(&device_descriptor, InputDeviceType::Mouse).await);
1111 assert!(is_device_type(&device_descriptor, InputDeviceType::Touch).await);
1112 assert!(is_device_type(&device_descriptor, InputDeviceType::Keyboard).await);
1113 }
1114
1115 #[fuchsia::test]
1116 fn unhandled_to_generic_conversion_sets_handled_flag_to_no() {
1117 assert_eq!(
1118 InputEvent::from(UnhandledInputEvent {
1119 device_event: InputDeviceEvent::Fake,
1120 device_descriptor: InputDeviceDescriptor::Fake,
1121 event_time: zx::MonotonicInstant::from_nanos(1),
1122 trace_id: None,
1123 })
1124 .handled,
1125 Handled::No
1126 );
1127 }
1128
1129 #[fuchsia::test]
1130 fn unhandled_to_generic_conversion_preserves_fields() {
1131 const EVENT_TIME: zx::MonotonicInstant = zx::MonotonicInstant::from_nanos(42);
1132 let expected_trace_id: Option<ftrace::Id> = Some(1234.into());
1133 assert_eq!(
1134 InputEvent::from(UnhandledInputEvent {
1135 device_event: InputDeviceEvent::Fake,
1136 device_descriptor: InputDeviceDescriptor::Fake,
1137 event_time: EVENT_TIME,
1138 trace_id: expected_trace_id,
1139 }),
1140 InputEvent {
1141 device_event: InputDeviceEvent::Fake,
1142 device_descriptor: InputDeviceDescriptor::Fake,
1143 event_time: EVENT_TIME,
1144 handled: Handled::No,
1145 trace_id: expected_trace_id,
1146 },
1147 );
1148 }
1149
1150 #[fuchsia::test]
1151 fn generic_to_unhandled_conversion_fails_for_handled_events() {
1152 assert_matches!(
1153 UnhandledInputEvent::try_from(InputEvent {
1154 device_event: InputDeviceEvent::Fake,
1155 device_descriptor: InputDeviceDescriptor::Fake,
1156 event_time: zx::MonotonicInstant::from_nanos(1),
1157 handled: Handled::Yes,
1158 trace_id: None,
1159 }),
1160 Err(_)
1161 )
1162 }
1163
1164 #[fuchsia::test]
1165 fn generic_to_unhandled_conversion_preserves_fields_for_unhandled_events() {
1166 const EVENT_TIME: zx::MonotonicInstant = zx::MonotonicInstant::from_nanos(42);
1167 let expected_trace_id: Option<ftrace::Id> = Some(1234.into());
1168 assert_eq!(
1169 UnhandledInputEvent::try_from(InputEvent {
1170 device_event: InputDeviceEvent::Fake,
1171 device_descriptor: InputDeviceDescriptor::Fake,
1172 event_time: EVENT_TIME,
1173 handled: Handled::No,
1174 trace_id: expected_trace_id,
1175 })
1176 .unwrap(),
1177 UnhandledInputEvent {
1178 device_event: InputDeviceEvent::Fake,
1179 device_descriptor: InputDeviceDescriptor::Fake,
1180 event_time: EVENT_TIME,
1181 trace_id: expected_trace_id,
1182 },
1183 )
1184 }
1185
1186 #[test_case(Handled::No; "initially not handled")]
1187 #[test_case(Handled::Yes; "initially handled")]
1188 fn into_handled_if_yields_handled_yes_on_true(initially_handled: Handled) {
1189 let event = InputEvent {
1190 device_event: InputDeviceEvent::Fake,
1191 device_descriptor: InputDeviceDescriptor::Fake,
1192 event_time: zx::MonotonicInstant::from_nanos(1),
1193 handled: initially_handled,
1194 trace_id: None,
1195 };
1196 pretty_assertions::assert_eq!(event.into_handled_if(true).handled, Handled::Yes);
1197 }
1198
1199 #[test_case(Handled::No; "initially not handled")]
1200 #[test_case(Handled::Yes; "initially handled")]
1201 fn into_handled_if_leaves_handled_unchanged_on_false(initially_handled: Handled) {
1202 let event = InputEvent {
1203 device_event: InputDeviceEvent::Fake,
1204 device_descriptor: InputDeviceDescriptor::Fake,
1205 event_time: zx::MonotonicInstant::from_nanos(1),
1206 handled: initially_handled.clone(),
1207 trace_id: None,
1208 };
1209 pretty_assertions::assert_eq!(event.into_handled_if(false).handled, initially_handled);
1210 }
1211
1212 #[test_case(Handled::No; "initially not handled")]
1213 #[test_case(Handled::Yes; "initially handled")]
1214 fn into_handled_yields_handled_yes(initially_handled: Handled) {
1215 let event = InputEvent {
1216 device_event: InputDeviceEvent::Fake,
1217 device_descriptor: InputDeviceDescriptor::Fake,
1218 event_time: zx::MonotonicInstant::from_nanos(1),
1219 handled: initially_handled,
1220 trace_id: None,
1221 };
1222 pretty_assertions::assert_eq!(event.into_handled().handled, Handled::Yes);
1223 }
1224}