Skip to main content

input_pipeline_dso/
keyboard_binding.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::input_device::{self, Handled, InputDeviceBinding, InputDeviceStatus, InputEvent};
6use crate::{Dispatcher, metrics};
7use anyhow::{Error, Result, format_err};
8use async_trait::async_trait;
9use fidl_fuchsia_input_report::{InputDeviceProxy, InputReport};
10use fidl_fuchsia_ui_input3 as fidl_ui_input3;
11use fidl_fuchsia_ui_input3::KeyEventType;
12use fuchsia_inspect::health::Reporter;
13use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
14use metrics_registry::*;
15
16/// A [`KeyboardEvent`] represents an input event from a keyboard device.
17///
18/// The keyboard event contains information about a key event.  A key event represents a change in
19/// the key state. Clients can expect the following sequence of events for a given key:
20///
21/// 1. [`KeyEventType::Pressed`]: the key has transitioned to being pressed.
22/// 2. [`KeyEventType::Released`]: the key has transitioned to being released.
23///
24/// No duplicate [`KeyEventType::Pressed`] events will be sent for keys, even if the
25/// key is present in a subsequent [`InputReport`]. Clients can assume that
26/// a key is pressed for all received input events until the key is present in
27/// the [`KeyEventType::Released`] entry of [`keys`].
28///
29/// Use `new` to create.  Use `get_*` methods to read fields.  Use `into_with_*`
30/// methods to add optional information.
31#[derive(Clone, Debug, PartialEq)]
32pub struct KeyboardEvent {
33    /// The key that changed state in this [KeyboardEvent].
34    key: fidl_fuchsia_input::Key,
35
36    /// A description of what happened to `key`.
37    event_type: KeyEventType,
38
39    /// The [`fidl_ui_input3::Modifiers`] associated with the pressed keys.
40    modifiers: Option<fidl_ui_input3::Modifiers>,
41
42    /// The [`fidl_ui_input3::LockState`] currently computed.
43    lock_state: Option<fidl_ui_input3::LockState>,
44
45    /// If set, contains the unique identifier of the keymap to be used when or
46    /// if remapping the keypresses.
47    keymap: Option<String>,
48
49    /// If set, denotes the meaning of `key` in terms of the key effect.
50    /// A `KeyboardEvent` starts off with `key_meaning` unset, and the key
51    /// meaning is added in the input pipeline by the appropriate
52    /// keymap-aware input handlers.
53    key_meaning: Option<fidl_fuchsia_ui_input3::KeyMeaning>,
54
55    /// If this keyboard event has been generated as a result of a repeated
56    /// generation of the same key, then this will be a nonzero. A nonzero
57    /// value N here means that this is Nth generated autorepeat for this
58    /// keyboard event.  The counter is reset for each new autorepeat key
59    /// span.
60    repeat_sequence: u32,
61}
62
63impl KeyboardEvent {
64    /// Creates a new KeyboardEvent, with required fields filled out.  Use the
65    /// `into_with_*` methods to add optional information.
66    pub fn new(key: fidl_fuchsia_input::Key, event_type: KeyEventType) -> Self {
67        KeyboardEvent {
68            key,
69            event_type,
70            modifiers: None,
71            lock_state: None,
72            keymap: None,
73            key_meaning: None,
74            repeat_sequence: 0,
75        }
76    }
77
78    pub fn get_key(&self) -> fidl_fuchsia_input::Key {
79        self.key
80    }
81
82    /// Converts [KeyboardEvent] into the same one, but with specified key.
83    pub fn into_with_key(self, key: fidl_fuchsia_input::Key) -> Self {
84        Self { key, ..self }
85    }
86
87    pub fn get_event_type(&self) -> KeyEventType {
88        self.event_type
89    }
90
91    /// Converts [KeyboardEvent] into the same one, but with specified event type.
92    pub fn into_with_event_type(self, event_type: KeyEventType) -> Self {
93        Self { event_type, ..self }
94    }
95
96    /// Folds the key event type into an active event (Pressed, Released).
97    pub fn into_with_folded_event(self) -> Self {
98        Self { event_type: self.get_event_type_folded(), ..self }
99    }
100
101    /// Gets [KeyEventType], folding `SYNC` into `PRESSED` and `CANCEL` into `RELEASED`.
102    pub fn get_event_type_folded(&self) -> KeyEventType {
103        match self.event_type {
104            KeyEventType::Pressed | KeyEventType::Sync => KeyEventType::Pressed,
105            KeyEventType::Released | KeyEventType::Cancel => KeyEventType::Released,
106        }
107    }
108
109    /// Converts [KeyboardEvent] into the same one, but with specified modifiers.
110    pub fn into_with_modifiers(self, modifiers: Option<fidl_ui_input3::Modifiers>) -> Self {
111        Self { modifiers, ..self }
112    }
113
114    /// Returns the currently applicable modifiers.
115    pub fn get_modifiers(&self) -> Option<fidl_ui_input3::Modifiers> {
116        self.modifiers
117    }
118
119    /// Returns the currently applicable modifiers, with the sided modifiers removed.
120    ///
121    /// For example, if LEFT_SHIFT is pressed, returns SHIFT, rather than SHIFT | LEFT_SHIFT
122    pub fn get_unsided_modifiers(&self) -> fidl_fuchsia_ui_input3::Modifiers {
123        use fidl_fuchsia_ui_input3::Modifiers;
124        let mut modifiers = self.modifiers.unwrap_or(Modifiers::empty());
125        modifiers.set(
126            Modifiers::LEFT_ALT
127                | Modifiers::LEFT_CTRL
128                | Modifiers::LEFT_SHIFT
129                | Modifiers::LEFT_META
130                | Modifiers::RIGHT_ALT
131                | Modifiers::RIGHT_CTRL
132                | Modifiers::RIGHT_SHIFT
133                | Modifiers::RIGHT_META,
134            false,
135        );
136        modifiers
137    }
138
139    /// Converts [KeyboardEvent] into the same one, but with the specified lock state.
140    pub fn into_with_lock_state(self, lock_state: Option<fidl_ui_input3::LockState>) -> Self {
141        Self { lock_state, ..self }
142    }
143
144    /// Returns the currently applicable lock state.
145    pub fn get_lock_state(&self) -> Option<fidl_ui_input3::LockState> {
146        self.lock_state
147    }
148
149    /// Converts [KeyboardEvent] into the same one, but with the specified keymap
150    /// applied.
151    pub fn into_with_keymap(self, keymap: Option<String>) -> Self {
152        Self { keymap, ..self }
153    }
154
155    /// Returns the currently applied keymap.
156    pub fn get_keymap(&self) -> Option<String> {
157        self.keymap.clone()
158    }
159
160    /// Converts [KeyboardEvent] into the same one, but with the key meaning applied.
161    pub fn into_with_key_meaning(
162        self,
163        key_meaning: Option<fidl_fuchsia_ui_input3::KeyMeaning>,
164    ) -> Self {
165        Self { key_meaning, ..self }
166    }
167
168    /// Returns the currently valid key meaning.
169    pub fn get_key_meaning(&self) -> Option<fidl_fuchsia_ui_input3::KeyMeaning> {
170        self.key_meaning
171    }
172
173    /// Returns the repeat sequence number.  If a nonzero number N is returned,
174    /// that means this [KeyboardEvent] is the N-th generated autorepeat event.
175    /// A zero means this is an event that came from the keyboard driver.
176    pub fn get_repeat_sequence(&self) -> u32 {
177        self.repeat_sequence
178    }
179
180    /// Converts [KeyboardEvent] into the same one, but with the repeat sequence
181    /// changed.
182    pub fn into_with_repeat_sequence(self, repeat_sequence: u32) -> Self {
183        Self { repeat_sequence, ..self }
184    }
185
186    /// Centralizes the conversion from [KeyboardEvent] to `KeyEvent`.
187    #[cfg(test)]
188    pub(crate) fn from_key_event_at_time(
189        &self,
190        event_time: zx::MonotonicInstant,
191    ) -> fidl_ui_input3::KeyEvent {
192        fidl_ui_input3::KeyEvent {
193            timestamp: Some(event_time.into_nanos()),
194            type_: Some(self.event_type),
195            key: Some(self.key),
196            modifiers: self.modifiers,
197            lock_state: self.lock_state,
198            repeat_sequence: Some(self.repeat_sequence),
199            key_meaning: self.key_meaning,
200            ..Default::default()
201        }
202    }
203}
204
205impl KeyboardEvent {
206    /// Returns true if the two keyboard events are about the same key.
207    pub fn same_key(this: &KeyboardEvent, that: &KeyboardEvent) -> bool {
208        this.get_key() == that.get_key()
209    }
210}
211
212/// A [`KeyboardDeviceDescriptor`] contains information about a specific keyboard device.
213#[derive(Clone, Debug, PartialEq)]
214pub struct KeyboardDeviceDescriptor {
215    /// All the [`fidl_fuchsia_input::Key`]s available on the keyboard device.
216    pub keys: Vec<fidl_fuchsia_input::Key>,
217
218    /// The vendor ID, product ID and version.
219    pub device_information: fidl_fuchsia_input_report::DeviceInformation,
220
221    /// The unique identifier of this device.
222    pub device_id: u32,
223}
224
225#[cfg(test)]
226impl Default for KeyboardDeviceDescriptor {
227    fn default() -> Self {
228        KeyboardDeviceDescriptor {
229            keys: vec![],
230            device_information: fidl_fuchsia_input_report::DeviceInformation {
231                vendor_id: Some(0),
232                product_id: Some(0),
233                version: Some(0),
234                polling_rate: Some(0),
235                ..Default::default()
236            },
237            device_id: 0,
238        }
239    }
240}
241
242/// A [`KeyboardBinding`] represents a connection to a keyboard input device.
243///
244/// The [`KeyboardBinding`] parses and exposes keyboard device descriptor properties (e.g., the
245/// available keyboard keys) for the device it is associated with. It also parses [`InputReport`]s
246/// from the device, and sends them to the device binding owner over `event_sender`.
247pub struct KeyboardBinding {
248    /// The channel to stream InputEvents to.
249    event_sender: UnboundedSender<Vec<InputEvent>>,
250
251    /// Holds information about this device.
252    device_descriptor: KeyboardDeviceDescriptor,
253}
254
255#[async_trait]
256impl input_device::InputDeviceBinding for KeyboardBinding {
257    fn input_event_sender(&self) -> UnboundedSender<Vec<InputEvent>> {
258        self.event_sender.clone()
259    }
260
261    fn get_device_descriptor(&self) -> input_device::InputDeviceDescriptor {
262        input_device::InputDeviceDescriptor::Keyboard(self.device_descriptor.clone())
263    }
264}
265
266impl KeyboardBinding {
267    /// Creates a new [`InputDeviceBinding`] from the `device_proxy`.
268    ///
269    /// The binding will start listening for input reports immediately and send new InputEvents
270    /// to the device binding owner over `input_event_sender`.
271    ///
272    /// # Parameters
273    /// - `device_proxy`: The proxy to bind the new [`InputDeviceBinding`] to.
274    /// - `device_id`: The unique identifier of this device.
275    /// - `input_event_sender`: The channel to send new InputEvents to.
276    /// - `device_node`: The inspect node for this device binding
277    /// - `metrics_logger`: The metrics logger.
278    ///
279    /// # Errors
280    /// If there was an error binding to the proxy.
281    pub async fn new(
282        device_proxy: InputDeviceProxy,
283        device_id: u32,
284        input_event_sender: UnboundedSender<Vec<InputEvent>>,
285        device_node: fuchsia_inspect::Node,
286        feature_flags: input_device::InputPipelineFeatureFlags,
287        metrics_logger: metrics::MetricsLogger,
288    ) -> Result<Self, Error> {
289        let (device_binding, mut inspect_status) = Self::bind_device(
290            &device_proxy,
291            input_event_sender,
292            device_id,
293            device_node,
294            metrics_logger.clone(),
295        )
296        .await?;
297        inspect_status.health_node.set_ok();
298        input_device::initialize_report_stream(
299            device_proxy,
300            device_binding.get_device_descriptor(),
301            device_binding.input_event_sender(),
302            inspect_status,
303            metrics_logger.clone(),
304            feature_flags,
305            Self::process_reports,
306        );
307
308        Ok(device_binding)
309    }
310
311    /// Converts a vector of keyboard keys to the appropriate [`fidl_ui_input3::Modifiers`] bitflags.
312    ///
313    /// For example, if `keys` contains `Key::CapsLock`, the bitflags will contain the corresponding
314    /// flags for `CapsLock`.
315    ///
316    /// # Parameters
317    /// - `keys`: The keys to check for modifiers.
318    ///
319    /// # Returns
320    /// Returns `None` if there are no modifier keys present.
321    pub fn to_modifiers(keys: &[&fidl_fuchsia_input::Key]) -> Option<fidl_ui_input3::Modifiers> {
322        let mut modifiers = fidl_ui_input3::Modifiers::empty();
323        for key in keys {
324            let modifier = match key {
325                fidl_fuchsia_input::Key::CapsLock => Some(fidl_ui_input3::Modifiers::CAPS_LOCK),
326                fidl_fuchsia_input::Key::NumLock => Some(fidl_ui_input3::Modifiers::NUM_LOCK),
327                fidl_fuchsia_input::Key::ScrollLock => Some(fidl_ui_input3::Modifiers::SCROLL_LOCK),
328                _ => None,
329            };
330            if let Some(modifier) = modifier {
331                modifiers.insert(modifier);
332            };
333        }
334        if modifiers.is_empty() {
335            return None;
336        }
337        Some(modifiers)
338    }
339
340    /// Binds the provided input device to a new instance of `Self`.
341    ///
342    /// # Parameters
343    /// - `device`: The device to use to initialize the binding.
344    /// - `input_event_sender`: The channel to send new InputEvents to.
345    /// - `device_id`: The device ID being bound.
346    /// - `device_node`: The inspect node for this device binding
347    ///
348    /// # Errors
349    /// If the device descriptor could not be retrieved, or the descriptor could not be parsed
350    /// correctly.
351    async fn bind_device(
352        device: &InputDeviceProxy,
353        input_event_sender: UnboundedSender<Vec<InputEvent>>,
354        device_id: u32,
355        device_node: fuchsia_inspect::Node,
356        metrics_logger: metrics::MetricsLogger,
357    ) -> Result<(Self, InputDeviceStatus), Error> {
358        let mut input_device_status = InputDeviceStatus::new(device_node);
359        let descriptor = match device.get_descriptor().await {
360            Ok(descriptor) => descriptor,
361            Err(_) => {
362                input_device_status.health_node.set_unhealthy("Could not get device descriptor.");
363                return Err(format_err!("Could not get descriptor for device_id: {}", device_id));
364            }
365        };
366
367        let device_info = descriptor.device_information.ok_or_else(|| {
368            input_device_status.health_node.set_unhealthy("Empty device_information in descriptor");
369            // Logging in addition to returning an error, as in some test
370            // setups the error may never be displayed to the user.
371            metrics_logger.log_error(
372                InputPipelineErrorMetricDimensionEvent::KeyboardEmptyDeviceInfo,
373                std::format!("DRIVER BUG: empty device_information for device_id: {}", device_id),
374            );
375            format_err!("empty device info for device_id: {}", device_id)
376        })?;
377        match descriptor.keyboard {
378            Some(fidl_fuchsia_input_report::KeyboardDescriptor {
379                input: Some(fidl_fuchsia_input_report::KeyboardInputDescriptor { keys3, .. }),
380                output: _,
381                ..
382            }) => Ok((
383                KeyboardBinding {
384                    event_sender: input_event_sender,
385                    device_descriptor: KeyboardDeviceDescriptor {
386                        keys: keys3.unwrap_or_default(),
387                        device_information: device_info,
388                        device_id,
389                    },
390                },
391                input_device_status,
392            )),
393            device_descriptor => {
394                input_device_status
395                    .health_node
396                    .set_unhealthy("Keyboard Device Descriptor failed to parse.");
397                Err(format_err!(
398                    "Keyboard Device Descriptor failed to parse: \n {:?}",
399                    device_descriptor
400                ))
401            }
402        }
403    }
404
405    /// Parses an [`InputReport`] into one or more [`InputEvent`]s.
406    ///
407    /// The [`InputEvent`]s are sent to the device binding owner via [`input_event_sender`].
408    ///
409    /// # Parameters
410    /// `reports`: The incoming [`InputReport`].
411    /// `previous_report`: The previous [`InputReport`] seen for the same device. This can be
412    ///                    used to determine, for example, which keys are no longer present in
413    ///                    a keyboard report to generate key released events. If `None`, no
414    ///                    previous report was found.
415    /// `device_descriptor`: The descriptor for the input device generating the input reports.
416    /// `input_event_sender`: The sender for the device binding's input event stream.
417    ///
418    /// # Returns
419    /// An [`InputReport`] which will be passed to the next call to [`process_reports`], as
420    /// [`previous_report`]. If `None`, the next call's [`previous_report`] will be `None`.
421    /// A [`UnboundedReceiver<InputEvent>`] which will poll asynchronously generated events to be
422    /// recorded by `inspect_status` in `input_device::initialize_report_stream()`. If device
423    /// binding does not generate InputEvents asynchronously, this will be `None`.
424    ///
425    /// The returned [`InputReport`] is guaranteed to have no `wake_lease`.
426    fn process_reports(
427        reports: Vec<InputReport>,
428        mut previous_report: Option<InputReport>,
429        device_descriptor: &input_device::InputDeviceDescriptor,
430        input_event_sender: &mut UnboundedSender<Vec<InputEvent>>,
431        inspect_status: &InputDeviceStatus,
432        metrics_logger: &metrics::MetricsLogger,
433        _feature_flags: &input_device::InputPipelineFeatureFlags,
434    ) -> (Option<InputReport>, Option<UnboundedReceiver<InputEvent>>) {
435        fuchsia_trace::duration!("input", "keyboard-binding-process-report", "num_reports" => reports.len());
436        let (inspect_sender, inspect_receiver) = futures::channel::mpsc::unbounded();
437
438        for report in reports {
439            previous_report = Self::process_report(
440                report,
441                previous_report,
442                device_descriptor,
443                input_event_sender,
444                inspect_status,
445                metrics_logger,
446                inspect_sender.clone(),
447            );
448        }
449        (previous_report, Some(inspect_receiver))
450    }
451
452    fn process_report(
453        mut report: InputReport,
454        previous_report: Option<InputReport>,
455        device_descriptor: &input_device::InputDeviceDescriptor,
456        input_event_sender: &mut UnboundedSender<Vec<InputEvent>>,
457        inspect_status: &InputDeviceStatus,
458        metrics_logger: &metrics::MetricsLogger,
459        inspect_sender: UnboundedSender<InputEvent>,
460    ) -> Option<InputReport> {
461        if let Some(trace_id) = report.trace_id {
462            fuchsia_trace::flow_end!("input", "input_report", trace_id.into());
463        }
464
465        let tracing_id = fuchsia_trace::Id::random();
466        fuchsia_trace::flow_begin!("input", "key_event_thread", tracing_id);
467
468        // Extract the wake_lease early to prevent it from leaking. If this is moved
469        // below an early return, the lease could accidentally be stored inside
470        // `previous_report`, which would prevent the system from suspending.
471        // Keyboard events cannot handle wake leases, so we drop them here.
472        drop(report.wake_lease.take());
473
474        inspect_status.count_received_report(&report);
475        // Input devices can have multiple types so ensure `report` is a KeyboardInputReport.
476        match &report.keyboard {
477            None => {
478                inspect_status.count_filtered_report();
479                return previous_report;
480            }
481            _ => (),
482        };
483
484        let new_keys = match KeyboardBinding::parse_pressed_keys(&report) {
485            Some(keys) => keys,
486            None => {
487                // It's OK for the report to contain an empty vector of keys, but it's not OK for
488                // the report to not have the appropriate fields set.
489                //
490                // In this case the report is treated as malformed, and the previous report is not
491                // updated.
492                metrics_logger.log_error(
493                    InputPipelineErrorMetricDimensionEvent::KeyboardFailedToParse,
494                    std::format!("Failed to parse keyboard keys: {:?}", report),
495                );
496                inspect_status.count_filtered_report();
497                return previous_report;
498            }
499        };
500
501        let previous_keys: Vec<fidl_fuchsia_input::Key> = previous_report
502            .as_ref()
503            .and_then(|unwrapped_report| KeyboardBinding::parse_pressed_keys(&unwrapped_report))
504            .unwrap_or_default();
505
506        KeyboardBinding::send_key_events(
507            &new_keys,
508            &previous_keys,
509            device_descriptor.clone(),
510            zx::MonotonicInstant::get(),
511            input_event_sender.clone(),
512            inspect_sender,
513            metrics_logger,
514            tracing_id,
515        );
516
517        Some(report)
518    }
519
520    /// Parses the currently pressed [`fidl_fuchsia_input3::Key`]s from an input report.
521    ///
522    /// # Parameters
523    /// - `input_report`: The input report to parse the keyboard keys from.
524    ///
525    /// # Returns
526    /// Returns `None` if any of the required input report fields are `None`. If all the
527    /// required report fields are present, but there are no pressed keys, an empty vector
528    /// is returned.
529    fn parse_pressed_keys(input_report: &InputReport) -> Option<Vec<fidl_fuchsia_input::Key>> {
530        input_report
531            .keyboard
532            .as_ref()
533            .and_then(|unwrapped_keyboard| unwrapped_keyboard.pressed_keys3.as_ref())
534            .and_then(|unwrapped_keys| Some(unwrapped_keys.iter().cloned().collect()))
535    }
536
537    /// Sends key events to clients based on the new and previously pressed keys.
538    ///
539    /// # Parameters
540    /// - `new_keys`: The input3 keys which are currently pressed, as reported by the bound device.
541    /// - `previous_keys`: The input3 keys which were pressed in the previous input report.
542    /// - `device_descriptor`: The descriptor for the input device generating the input reports.
543    /// - `event_time`: The time in nanoseconds when the event was first recorded.
544    /// - `input_event_sender`: The sender for the device binding's input event stream.
545    fn send_key_events(
546        new_keys: &Vec<fidl_fuchsia_input::Key>,
547        previous_keys: &Vec<fidl_fuchsia_input::Key>,
548        device_descriptor: input_device::InputDeviceDescriptor,
549        event_time: zx::MonotonicInstant,
550        input_event_sender: UnboundedSender<Vec<InputEvent>>,
551        inspect_sender: UnboundedSender<input_device::InputEvent>,
552        metrics_logger: &metrics::MetricsLogger,
553        tracing_id: fuchsia_trace::Id,
554    ) {
555        // Dispatches all key events individually in a separate task.  This is done in a separate
556        // function so that the lifetime of `new_keys` above could be detached from that of the
557        // spawned task.
558        fn dispatch_events(
559            key_events: Vec<(fidl_fuchsia_input::Key, fidl_fuchsia_ui_input3::KeyEventType)>,
560            device_descriptor: input_device::InputDeviceDescriptor,
561            event_time: zx::MonotonicInstant,
562            input_event_sender: UnboundedSender<Vec<input_device::InputEvent>>,
563            inspect_sender: UnboundedSender<input_device::InputEvent>,
564            metrics_logger: metrics::MetricsLogger,
565            tracing_id: fuchsia_trace::Id,
566        ) {
567            Dispatcher::spawn_local(async move {
568                fuchsia_trace::duration!("input", "key_event_thread");
569                fuchsia_trace::flow_end!("input", "key_event_thread", tracing_id);
570
571                let mut event_time = event_time;
572                for (key, event_type) in key_events.into_iter() {
573                    let trace_id = fuchsia_trace::Id::random();
574                    fuchsia_trace::duration!("input", "keyboard_event_in_binding");
575                    fuchsia_trace::flow_begin!("input", "event_in_input_pipeline", trace_id);
576
577                    let event = input_device::InputEvent {
578                        device_event: input_device::InputDeviceEvent::Keyboard(KeyboardEvent::new(
579                            key, event_type,
580                        )),
581                        device_descriptor: device_descriptor.clone(),
582                        event_time,
583                        handled: Handled::No,
584                        trace_id: Some(trace_id),
585                    };
586                    match input_event_sender.unbounded_send(vec![event.clone()]) {
587                        Err(error) => {
588                            metrics_logger.log_error(
589                                InputPipelineErrorMetricDimensionEvent::KeyboardFailedToSendKeyboardEvent,
590                                std::format!(
591                                    "Failed to send KeyboardEvent for key: {:?}, event_type: {:?}: {:?}",
592                                    &key,
593                                    &event_type,
594                                    error));
595                        }
596                        _ => {
597                            let _ = inspect_sender.unbounded_send(event).expect("Failed to count generated KeyboardEvent in Input Pipeline Inspect tree.");
598                        }
599                    }
600                    // If key events happen to have been reported at the same time,
601                    // we pull them apart artificially. A 1ns increment will likely
602                    // be enough of a difference that it is recognizable but that it
603                    // does not introduce confusion.
604                    event_time = event_time + zx::MonotonicDuration::from_nanos(1);
605                }
606            }).detach();
607        }
608
609        // Filter out the keys which were present in the previous keyboard report to avoid sending
610        // multiple `KeyEventType::Pressed` events for a key.
611        let pressed_keys = new_keys
612            .iter()
613            .cloned()
614            .filter(|key| !previous_keys.contains(key))
615            .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Pressed));
616
617        // Any key which is not present in the new keys, but was present in the previous report
618        // is considered to be released.
619        let released_keys = previous_keys
620            .iter()
621            .cloned()
622            .filter(|key| !new_keys.contains(key))
623            .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Released));
624
625        // It is important that key releases are dispatched before key presses,
626        // so that modifier tracking would work correctly.  We collect the result
627        // into a vector since an iterator is not Send and can not be moved into
628        // a closure.
629        let all_keys = released_keys.chain(pressed_keys).collect::<Vec<_>>();
630
631        dispatch_events(
632            all_keys,
633            device_descriptor,
634            event_time,
635            input_event_sender,
636            inspect_sender,
637            metrics_logger.clone(),
638            tracing_id,
639        );
640    }
641}
642
643#[cfg(test)]
644mod tests {
645    use super::*;
646    use crate::testing_utilities;
647    use fuchsia_async as fasync;
648    use futures::StreamExt;
649
650    /// Tests that a key that is present in the new report, but was not present in the previous report
651    /// is propagated as pressed.
652    #[fasync::run_singlethreaded(test)]
653    async fn pressed_key() {
654        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
655            keys: vec![fidl_fuchsia_input::Key::A],
656            ..Default::default()
657        });
658        let (event_time_i64, _) = testing_utilities::event_times();
659
660        let reports = vec![testing_utilities::create_keyboard_input_report(
661            vec![fidl_fuchsia_input::Key::A],
662            event_time_i64,
663        )];
664        let expected_events = vec![testing_utilities::create_keyboard_event(
665            fidl_fuchsia_input::Key::A,
666            fidl_fuchsia_ui_input3::KeyEventType::Pressed,
667            None,
668            &descriptor,
669            /* keymap= */ None,
670        )];
671
672        assert_input_report_sequence_generates_events!(
673            input_reports: reports,
674            expected_events: expected_events,
675            device_descriptor: descriptor,
676            device_type: KeyboardBinding,
677        );
678    }
679
680    /// Tests that a key that is not present in the new report, but was present in the previous report
681    /// is propagated as released.
682    #[fasync::run_singlethreaded(test)]
683    async fn released_key() {
684        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
685            keys: vec![fidl_fuchsia_input::Key::A],
686            ..Default::default()
687        });
688        let (event_time_i64, _) = testing_utilities::event_times();
689
690        let reports = vec![
691            testing_utilities::create_keyboard_input_report(
692                vec![fidl_fuchsia_input::Key::A],
693                event_time_i64,
694            ),
695            testing_utilities::create_keyboard_input_report(vec![], event_time_i64),
696        ];
697
698        let expected_events = vec![
699            testing_utilities::create_keyboard_event(
700                fidl_fuchsia_input::Key::A,
701                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
702                None,
703                &descriptor,
704                /* keymap= */ None,
705            ),
706            testing_utilities::create_keyboard_event(
707                fidl_fuchsia_input::Key::A,
708                fidl_fuchsia_ui_input3::KeyEventType::Released,
709                None,
710                &descriptor,
711                /* keymap= */ None,
712            ),
713        ];
714
715        assert_input_report_sequence_generates_events!(
716            input_reports: reports,
717            expected_events: expected_events,
718            device_descriptor: descriptor.clone(),
719            device_type: KeyboardBinding,
720        );
721    }
722
723    /// Tests that a key that is present in multiple consecutive input reports is not propagated
724    /// as a pressed event more than once.
725    #[fasync::run_singlethreaded(test)]
726    async fn multiple_pressed_event_filtering() {
727        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
728            keys: vec![fidl_fuchsia_input::Key::A],
729            ..Default::default()
730        });
731        let (event_time_i64, _) = testing_utilities::event_times();
732
733        let reports = vec![
734            testing_utilities::create_keyboard_input_report(
735                vec![fidl_fuchsia_input::Key::A],
736                event_time_i64,
737            ),
738            testing_utilities::create_keyboard_input_report(
739                vec![fidl_fuchsia_input::Key::A],
740                event_time_i64,
741            ),
742        ];
743
744        let expected_events = vec![testing_utilities::create_keyboard_event(
745            fidl_fuchsia_input::Key::A,
746            fidl_fuchsia_ui_input3::KeyEventType::Pressed,
747            None,
748            &descriptor,
749            /* keymap= */ None,
750        )];
751
752        assert_input_report_sequence_generates_events!(
753            input_reports: reports,
754            expected_events: expected_events,
755            device_descriptor: descriptor,
756            device_type: KeyboardBinding,
757        );
758    }
759
760    /// Tests that both pressed and released keys are sent at once.
761    #[fasync::run_singlethreaded(test)]
762    async fn pressed_and_released_keys() {
763        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
764            keys: vec![fidl_fuchsia_input::Key::A, fidl_fuchsia_input::Key::B],
765            ..Default::default()
766        });
767        let (event_time_i64, _) = testing_utilities::event_times();
768
769        let reports = vec![
770            testing_utilities::create_keyboard_input_report(
771                vec![fidl_fuchsia_input::Key::A],
772                event_time_i64,
773            ),
774            testing_utilities::create_keyboard_input_report(
775                vec![fidl_fuchsia_input::Key::B],
776                event_time_i64,
777            ),
778        ];
779
780        let expected_events = vec![
781            testing_utilities::create_keyboard_event(
782                fidl_fuchsia_input::Key::A,
783                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
784                None,
785                &descriptor,
786                /* keymap= */ None,
787            ),
788            testing_utilities::create_keyboard_event(
789                fidl_fuchsia_input::Key::A,
790                fidl_fuchsia_ui_input3::KeyEventType::Released,
791                None,
792                &descriptor,
793                /* keymap= */ None,
794            ),
795            testing_utilities::create_keyboard_event(
796                fidl_fuchsia_input::Key::B,
797                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
798                None,
799                &descriptor,
800                /* keymap= */ None,
801            ),
802        ];
803
804        assert_input_report_sequence_generates_events!(
805            input_reports: reports,
806            expected_events: expected_events,
807            device_descriptor: descriptor,
808            device_type: KeyboardBinding,
809        );
810    }
811
812    #[fuchsia::test]
813    fn get_unsided_modifiers() {
814        use fidl_ui_input3::Modifiers;
815        let event = KeyboardEvent::new(fidl_fuchsia_input::Key::A, KeyEventType::Pressed)
816            .into_with_modifiers(Some(Modifiers::all()));
817        assert_eq!(
818            event.get_unsided_modifiers(),
819            Modifiers::CAPS_LOCK
820                | Modifiers::NUM_LOCK
821                | Modifiers::SCROLL_LOCK
822                | Modifiers::FUNCTION
823                | Modifiers::SYMBOL
824                | Modifiers::SHIFT
825                | Modifiers::ALT
826                | Modifiers::ALT_GRAPH
827                | Modifiers::META
828                | Modifiers::CTRL
829        )
830    }
831
832    #[fuchsia::test]
833    fn conversion_fills_out_all_fields() {
834        use fidl_fuchsia_input::Key;
835        use fidl_ui_input3::{KeyMeaning, LockState, Modifiers, NonPrintableKey};
836        let event = KeyboardEvent::new(Key::A, KeyEventType::Pressed)
837            .into_with_modifiers(Some(Modifiers::all()))
838            .into_with_lock_state(Some(LockState::all()))
839            .into_with_repeat_sequence(42)
840            .into_with_key_meaning(Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)));
841
842        let actual = event.from_key_event_at_time(zx::MonotonicInstant::from_nanos(42));
843        assert_eq!(
844            actual,
845            fidl_fuchsia_ui_input3::KeyEvent {
846                timestamp: Some(42),
847                type_: Some(KeyEventType::Pressed),
848                key: Some(Key::A),
849                modifiers: Some(Modifiers::all()),
850                key_meaning: Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)),
851                repeat_sequence: Some(42),
852                lock_state: Some(LockState::all()),
853                ..Default::default()
854            }
855        );
856    }
857}