Skip to main content

input_pipeline/
input_device.rs

1// Copyright 2019 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use 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    /// Merge touch events in same InputReport frame if they are same contact and movement only.
30    pub enable_merge_touch_events: bool,
31}
32
33/// The path to the input-report service directory.
34pub 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    // Seven buckets allows us to report
41    // *      < 0 msec (added automatically by Inspect)
42    // *      0-1 msec
43    // *     1-10 msec
44    // *   10-100 msec
45    // * 100-1000 msec
46    // *     1-10 sec
47    // *   10-100 sec
48    // * 100-1000 sec
49    // *    >1000 sec (added automatically by Inspect)
50    buckets: 7,
51};
52
53/// An [`InputDeviceStatus`] is tied to an [`InputDeviceBinding`] and provides properties
54/// detailing its Inspect status.
55pub struct InputDeviceStatus {
56    /// Function for getting the current timestamp. Enables unit testing
57    /// of the latency histogram.
58    now: Box<dyn Fn() -> zx::MonotonicInstant>,
59
60    /// A node that contains the state below.
61    _node: fuchsia_inspect::Node,
62
63    /// The total number of reports received by the device driver.
64    reports_received_count: fuchsia_inspect::UintProperty,
65
66    /// The number of reports received by the device driver that did
67    /// not get converted into InputEvents processed by InputPipeline.
68    reports_filtered_count: fuchsia_inspect::UintProperty,
69
70    /// The total number of events generated from received
71    /// InputReports that were sent to InputPipeline.
72    events_generated: fuchsia_inspect::UintProperty,
73
74    /// The event time the last received InputReport was generated.
75    last_received_timestamp_ns: fuchsia_inspect::UintProperty,
76
77    /// The event time the last InputEvent was generated.
78    last_generated_timestamp_ns: fuchsia_inspect::UintProperty,
79
80    // This node records the health status of the `InputDevice`.
81    pub health_node: fuchsia_inspect::health::Node,
82
83    /// Histogram of latency from the driver timestamp for an `InputReport` until
84    /// the time at which the report was seen by the respective binding. Reported
85    /// in milliseconds, because values less than 1 msec aren't especially
86    /// interesting.
87    driver_to_binding_latency_ms: fuchsia_inspect::IntExponentialHistogramProperty,
88
89    /// The number of times a wake lease was leaked by this device.
90    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/// An [`InputEvent`] holds information about an input event and the device that produced the event.
189#[derive(Clone, Debug, PartialEq)]
190pub struct InputEvent {
191    /// The `device_event` contains the device-specific input event information.
192    pub device_event: InputDeviceEvent,
193
194    /// The `device_descriptor` contains static information about the device that generated the
195    /// input event.
196    pub device_descriptor: InputDeviceDescriptor,
197
198    /// The time in nanoseconds when the event was first recorded.
199    pub event_time: zx::MonotonicInstant,
200
201    /// The handled state of the event.
202    pub handled: Handled,
203
204    pub trace_id: Option<ftrace::Id>,
205}
206
207/// An [`UnhandledInputEvent`] is like an [`InputEvent`], except that the data represents an
208/// event that has not been handled.
209/// * Event producers must not use this type to carry data for an event that was already
210///   handled.
211/// * Event consumers should assume that the event has not been handled.
212#[derive(Clone, Debug, PartialEq)]
213pub struct UnhandledInputEvent {
214    /// The `device_event` contains the device-specific input event information.
215    pub device_event: InputDeviceEvent,
216
217    /// The `device_descriptor` contains static information about the device that generated the
218    /// input event.
219    pub device_descriptor: InputDeviceDescriptor,
220
221    /// The time in nanoseconds when the event was first recorded.
222    pub event_time: zx::MonotonicInstant,
223
224    pub trace_id: Option<ftrace::Id>,
225}
226
227impl UnhandledInputEvent {
228    // Returns event type as string.
229    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/// An [`InputDeviceEvent`] represents an input event from an input device.
244///
245/// [`InputDeviceEvent`]s contain more context than the raw [`InputReport`] they are parsed from.
246/// For example, [`KeyboardEvent`] contains all the pressed keys, as well as the key's
247/// phase (pressed, released, etc.).
248///
249/// Each [`InputDeviceBinding`] generates the type of [`InputDeviceEvent`]s that are appropriate
250/// for their device.
251#[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/// An [`InputEventType`] represents the type of an input event.
264#[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/// An [`InputDescriptor`] describes the ranges of values a particular input device can generate.
293///
294/// For example, a [`InputDescriptor::Keyboard`] contains the keys available on the keyboard,
295/// and a [`InputDescriptor::Touch`] contains the maximum number of touch contacts and the
296/// range of x- and y-values each contact can take on.
297///
298/// The descriptor is sent alongside [`InputDeviceEvent`]s so clients can, for example, convert a
299/// touch coordinate to a display coordinate. The descriptor is not expected to change for the
300/// lifetime of a device binding.
301#[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// Whether the event is consumed by an [`InputHandler`].
335#[derive(Copy, Clone, Debug, PartialEq)]
336pub enum Handled {
337    // The event has been handled.
338    Yes,
339    // The event has not been handled.
340    No,
341}
342
343/// An [`InputDeviceBinding`] represents a binding to an input device (e.g., a mouse).
344///
345/// [`InputDeviceBinding`]s expose information about the bound device. For example, a
346/// [`MouseBinding`] exposes the ranges of possible x and y values the device can generate.
347///
348/// An [`InputPipeline`] manages [`InputDeviceBinding`]s and holds the receiving end of a channel
349/// that an [`InputDeviceBinding`]s send [`InputEvent`]s over.
350/// ```
351#[async_trait]
352pub trait InputDeviceBinding: Send {
353    /// Returns information about the input device.
354    fn get_device_descriptor(&self) -> InputDeviceDescriptor;
355
356    /// Returns the input event stream's sender.
357    fn input_event_sender(&self) -> UnboundedSender<Vec<InputEvent>>;
358}
359
360/// Initializes the input report stream for the device bound to `device_proxy`.
361///
362/// Spawns a future which awaits input reports from the device and forwards them to
363/// clients via `event_sender`.
364///
365/// # Parameters
366/// - `device_proxy`: The device proxy which is used to get input reports.
367/// - `device_descriptor`: The descriptor of the device bound to `device_proxy`.
368/// - `event_sender`: The channel to send InputEvents to.
369/// - `metrics_logger`: The metrics logger.
370/// - `process_reports`: A function that generates InputEvent(s) from an InputReport and the
371///                      InputReport that precedes it. Each type of input device defines how it
372///                      processes InputReports.
373///                      The [`InputReport`] returned by `process_reports` must have no
374///                      `wake_lease`.
375///
376pub 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; // TODO(https://fxbug.dev/42131965): signal error
409        }
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                        // TODO: b/513602239 - use InputEvent instead of InputReport for previous
423                        // report. To avoid wire to natural type conversion.
424                        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                        // If a report generates multiple events asynchronously, we send them over a mpsc channel
436                        // to inspect_receiver. We update the event count on inspect_status here since we cannot
437                        // pass a reference to inspect_status to an async task in process_reports().
438                        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        // TODO(https://fxbug.dev/42131965): Add signaling for when this loop exits, since it means the device
451        // binding is no longer functional.
452        log::warn!("initialize_report_stream exited - device binding no longer works");
453    })
454    .detach();
455}
456
457/// Returns true if the device type of `input_device` matches `device_type`.
458///
459/// # Parameters
460/// - `input_device`: The InputDevice to check the type of.
461/// - `device_type`: The type of the device to compare to.
462pub async fn is_device_type(
463    device_descriptor: &fidl_next_fuchsia_input_report::DeviceDescriptor,
464    device_type: InputDeviceType,
465) -> bool {
466    // Return if the device type matches the desired `device_type`.
467    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
476/// Returns a new [`InputDeviceBinding`] of the given device type.
477///
478/// # Parameters
479/// - `device_type`: The type of the input device.
480/// - `device_proxy`: The device proxy which is used to get input reports.
481/// - `device_id`: The id of the connected input device.
482/// - `input_event_sender`: The channel to send generated InputEvents to.
483pub 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
558/// Returns a proxy to the InputDevice in `entry_path` if it exists.
559///
560/// # Parameters
561/// - `dir_proxy`: The directory containing InputDevice connections.
562/// - `entry_path`: The directory entry that contains an InputDevice.
563///
564/// # Errors
565/// If there is an error connecting to the InputDevice in `entry_path`.
566pub 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
578/// Returns the event time if it exists, otherwise returns the current time.
579///
580/// # Parameters
581/// - `event_time`: The event time from an InputReport.
582pub 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// Fallible conversion from an InputEvent to an UnhandledInputEvent.
602//
603// Useful to adapt various functions in the [`testing_utilities`] module
604// to work with tests for [`UnhandledInputHandler`]s.
605//
606// Production code however, should probably just match on the [`InputEvent`].
607#[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    /// Marks the event as handled, if `predicate` is `true`.
627    /// Otherwise, leaves the event unchanged.
628    pub(crate) fn into_handled_if(self, predicate: bool) -> Self {
629        if predicate { Self { handled: Handled::Yes, ..self } } else { self }
630    }
631
632    /// Marks the event as handled.
633    pub(crate) fn into_handled(self) -> Self {
634        Self { handled: Handled::Yes, ..self }
635    }
636
637    /// Returns the same event, with modified event time.
638    pub fn into_with_event_time(self, event_time: zx::MonotonicInstant) -> Self {
639        Self { event_time, ..self }
640    }
641
642    /// Returns the same event, with modified device descriptor.
643    #[cfg(test)]
644    pub fn into_with_device_descriptor(self, device_descriptor: InputDeviceDescriptor) -> Self {
645        Self { device_descriptor, ..self }
646    }
647
648    /// Returns true if this event is marked as handled.
649    pub fn is_handled(&self) -> bool {
650        self.handled == Handled::Yes
651    }
652
653    // Returns event type as string.
654    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            // No-op for KeyboardEvent, since we don't want to potentially record sensitive information to Inspect.
676            InputDeviceEvent::Keyboard(_) => (),
677            #[cfg(test)] // No-op for Fake InputDeviceEvent.
678            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                            // Timestamp value is unpredictable and not relevant in this context,
726                            // so we only assert that the property is present.
727                            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    // Tests that is_device_type() returns true for InputDeviceType::ConsumerControls when a
766    // consumer controls device exists.
767    #[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    // Tests that is_device_type() returns true for InputDeviceType::Mouse when a mouse exists.
810    #[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    // Tests that is_device_type() returns true for InputDeviceType::Mouse when a mouse doesn't
856    // exist.
857    #[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    // Tests that is_device_type() returns true for InputDeviceType::Touch when a touchscreen
891    // exists.
892    #[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    // Tests that is_device_type() returns true for InputDeviceType::Touch when a touchscreen
935    // exists.
936    #[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    // Tests that is_device_type() returns true for InputDeviceType::Keyboard when a keyboard
970    // exists.
971    #[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    // Tests that is_device_type() returns true for InputDeviceType::Keyboard when a keyboard
1012    // exists.
1013    #[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    // Tests that is_device_type() returns true for every input device type that exists.
1047    #[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}