Skip to main content

input_pipeline/
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::metrics;
7use anyhow::{Error, Result, format_err};
8use async_trait::async_trait;
9use fidl_fuchsia_input_report::{InputDeviceProxy, InputReport};
10use fidl_fuchsia_ui_input3::KeyEventType;
11use fuchsia_inspect::health::Reporter;
12use futures::channel::mpsc::{UnboundedReceiver, UnboundedSender};
13use metrics_registry::*;
14use {fidl_fuchsia_ui_input3 as fidl_ui_input3, fuchsia_async as fasync};
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        inspect_status.count_received_report(&report);
469        // Input devices can have multiple types so ensure `report` is a KeyboardInputReport.
470        match &report.keyboard {
471            None => {
472                inspect_status.count_filtered_report();
473                return previous_report;
474            }
475            _ => (),
476        };
477
478        // Keyboard events cannot handle wake leases, so we drop them here.
479        drop(report.wake_lease.take());
480
481        let new_keys = match KeyboardBinding::parse_pressed_keys(&report) {
482            Some(keys) => keys,
483            None => {
484                // It's OK for the report to contain an empty vector of keys, but it's not OK for
485                // the report to not have the appropriate fields set.
486                //
487                // In this case the report is treated as malformed, and the previous report is not
488                // updated.
489                metrics_logger.log_error(
490                    InputPipelineErrorMetricDimensionEvent::KeyboardFailedToParse,
491                    std::format!("Failed to parse keyboard keys: {:?}", report),
492                );
493                inspect_status.count_filtered_report();
494                return previous_report;
495            }
496        };
497
498        let previous_keys: Vec<fidl_fuchsia_input::Key> = previous_report
499            .as_ref()
500            .and_then(|unwrapped_report| KeyboardBinding::parse_pressed_keys(&unwrapped_report))
501            .unwrap_or_default();
502
503        KeyboardBinding::send_key_events(
504            &new_keys,
505            &previous_keys,
506            device_descriptor.clone(),
507            zx::MonotonicInstant::get(),
508            input_event_sender.clone(),
509            inspect_sender,
510            metrics_logger,
511            tracing_id,
512        );
513
514        Some(report)
515    }
516
517    /// Parses the currently pressed [`fidl_fuchsia_input3::Key`]s from an input report.
518    ///
519    /// # Parameters
520    /// - `input_report`: The input report to parse the keyboard keys from.
521    ///
522    /// # Returns
523    /// Returns `None` if any of the required input report fields are `None`. If all the
524    /// required report fields are present, but there are no pressed keys, an empty vector
525    /// is returned.
526    fn parse_pressed_keys(input_report: &InputReport) -> Option<Vec<fidl_fuchsia_input::Key>> {
527        input_report
528            .keyboard
529            .as_ref()
530            .and_then(|unwrapped_keyboard| unwrapped_keyboard.pressed_keys3.as_ref())
531            .and_then(|unwrapped_keys| Some(unwrapped_keys.iter().cloned().collect()))
532    }
533
534    /// Sends key events to clients based on the new and previously pressed keys.
535    ///
536    /// # Parameters
537    /// - `new_keys`: The input3 keys which are currently pressed, as reported by the bound device.
538    /// - `previous_keys`: The input3 keys which were pressed in the previous input report.
539    /// - `device_descriptor`: The descriptor for the input device generating the input reports.
540    /// - `event_time`: The time in nanoseconds when the event was first recorded.
541    /// - `input_event_sender`: The sender for the device binding's input event stream.
542    fn send_key_events(
543        new_keys: &Vec<fidl_fuchsia_input::Key>,
544        previous_keys: &Vec<fidl_fuchsia_input::Key>,
545        device_descriptor: input_device::InputDeviceDescriptor,
546        event_time: zx::MonotonicInstant,
547        input_event_sender: UnboundedSender<Vec<InputEvent>>,
548        inspect_sender: UnboundedSender<input_device::InputEvent>,
549        metrics_logger: &metrics::MetricsLogger,
550        tracing_id: fuchsia_trace::Id,
551    ) {
552        // Dispatches all key events individually in a separate task.  This is done in a separate
553        // function so that the lifetime of `new_keys` above could be detached from that of the
554        // spawned task.
555        fn dispatch_events(
556            key_events: Vec<(fidl_fuchsia_input::Key, fidl_fuchsia_ui_input3::KeyEventType)>,
557            device_descriptor: input_device::InputDeviceDescriptor,
558            event_time: zx::MonotonicInstant,
559            input_event_sender: UnboundedSender<Vec<input_device::InputEvent>>,
560            inspect_sender: UnboundedSender<input_device::InputEvent>,
561            metrics_logger: metrics::MetricsLogger,
562            tracing_id: fuchsia_trace::Id,
563        ) {
564            fasync::Task::local(async move {
565                fuchsia_trace::duration!("input", "key_event_thread");
566                fuchsia_trace::flow_end!("input", "key_event_thread", tracing_id);
567
568                let mut event_time = event_time;
569                for (key, event_type) in key_events.into_iter() {
570                    let trace_id = fuchsia_trace::Id::random();
571                    fuchsia_trace::duration!("input", "keyboard_event_in_binding");
572                    fuchsia_trace::flow_begin!("input", "event_in_input_pipeline", trace_id);
573
574                    let event = input_device::InputEvent {
575                        device_event: input_device::InputDeviceEvent::Keyboard(
576                            KeyboardEvent::new(key, event_type),
577                        ),
578                        device_descriptor: device_descriptor.clone(),
579                        event_time,
580                        handled: Handled::No,
581                        trace_id: Some(trace_id),
582                    };
583                    match input_event_sender.unbounded_send(vec![event.clone()]) {
584                        Err(error) => {
585                            metrics_logger.log_error(
586                                InputPipelineErrorMetricDimensionEvent::KeyboardFailedToSendKeyboardEvent,
587                                std::format!(
588                                    "Failed to send KeyboardEvent for key: {:?}, event_type: {:?}: {:?}",
589                                    &key,
590                                    &event_type,
591                                    error));
592                        }
593                        _ => { let _ = inspect_sender.unbounded_send(event).expect("Failed to count generated KeyboardEvent in Input Pipeline Inspect tree."); },
594                    }
595                    // If key events happen to have been reported at the same time,
596                    // we pull them apart artificially. A 1ns increment will likely
597                    // be enough of a difference that it is recognizable but that it
598                    // does not introduce confusion.
599                    event_time = event_time + zx::MonotonicDuration::from_nanos(1);
600                }
601            })
602            .detach();
603        }
604
605        // Filter out the keys which were present in the previous keyboard report to avoid sending
606        // multiple `KeyEventType::Pressed` events for a key.
607        let pressed_keys = new_keys
608            .iter()
609            .cloned()
610            .filter(|key| !previous_keys.contains(key))
611            .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Pressed));
612
613        // Any key which is not present in the new keys, but was present in the previous report
614        // is considered to be released.
615        let released_keys = previous_keys
616            .iter()
617            .cloned()
618            .filter(|key| !new_keys.contains(key))
619            .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Released));
620
621        // It is important that key releases are dispatched before key presses,
622        // so that modifier tracking would work correctly.  We collect the result
623        // into a vector since an iterator is not Send and can not be moved into
624        // a closure.
625        let all_keys = released_keys.chain(pressed_keys).collect::<Vec<_>>();
626
627        dispatch_events(
628            all_keys,
629            device_descriptor,
630            event_time,
631            input_event_sender,
632            inspect_sender,
633            metrics_logger.clone(),
634            tracing_id,
635        );
636    }
637}
638
639#[cfg(test)]
640mod tests {
641    use super::*;
642    use crate::testing_utilities;
643    use fuchsia_async as fasync;
644    use futures::StreamExt;
645
646    /// Tests that a key that is present in the new report, but was not present in the previous report
647    /// is propagated as pressed.
648    #[fasync::run_singlethreaded(test)]
649    async fn pressed_key() {
650        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
651            keys: vec![fidl_fuchsia_input::Key::A],
652            ..Default::default()
653        });
654        let (event_time_i64, _) = testing_utilities::event_times();
655
656        let reports = vec![testing_utilities::create_keyboard_input_report(
657            vec![fidl_fuchsia_input::Key::A],
658            event_time_i64,
659        )];
660        let expected_events = vec![testing_utilities::create_keyboard_event(
661            fidl_fuchsia_input::Key::A,
662            fidl_fuchsia_ui_input3::KeyEventType::Pressed,
663            None,
664            &descriptor,
665            /* keymap= */ None,
666        )];
667
668        assert_input_report_sequence_generates_events!(
669            input_reports: reports,
670            expected_events: expected_events,
671            device_descriptor: descriptor,
672            device_type: KeyboardBinding,
673        );
674    }
675
676    /// Tests that a key that is not present in the new report, but was present in the previous report
677    /// is propagated as released.
678    #[fasync::run_singlethreaded(test)]
679    async fn released_key() {
680        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
681            keys: vec![fidl_fuchsia_input::Key::A],
682            ..Default::default()
683        });
684        let (event_time_i64, _) = testing_utilities::event_times();
685
686        let reports = vec![
687            testing_utilities::create_keyboard_input_report(
688                vec![fidl_fuchsia_input::Key::A],
689                event_time_i64,
690            ),
691            testing_utilities::create_keyboard_input_report(vec![], event_time_i64),
692        ];
693
694        let expected_events = vec![
695            testing_utilities::create_keyboard_event(
696                fidl_fuchsia_input::Key::A,
697                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
698                None,
699                &descriptor,
700                /* keymap= */ None,
701            ),
702            testing_utilities::create_keyboard_event(
703                fidl_fuchsia_input::Key::A,
704                fidl_fuchsia_ui_input3::KeyEventType::Released,
705                None,
706                &descriptor,
707                /* keymap= */ None,
708            ),
709        ];
710
711        assert_input_report_sequence_generates_events!(
712            input_reports: reports,
713            expected_events: expected_events,
714            device_descriptor: descriptor.clone(),
715            device_type: KeyboardBinding,
716        );
717    }
718
719    /// Tests that a key that is present in multiple consecutive input reports is not propagated
720    /// as a pressed event more than once.
721    #[fasync::run_singlethreaded(test)]
722    async fn multiple_pressed_event_filtering() {
723        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
724            keys: vec![fidl_fuchsia_input::Key::A],
725            ..Default::default()
726        });
727        let (event_time_i64, _) = testing_utilities::event_times();
728
729        let reports = vec![
730            testing_utilities::create_keyboard_input_report(
731                vec![fidl_fuchsia_input::Key::A],
732                event_time_i64,
733            ),
734            testing_utilities::create_keyboard_input_report(
735                vec![fidl_fuchsia_input::Key::A],
736                event_time_i64,
737            ),
738        ];
739
740        let expected_events = vec![testing_utilities::create_keyboard_event(
741            fidl_fuchsia_input::Key::A,
742            fidl_fuchsia_ui_input3::KeyEventType::Pressed,
743            None,
744            &descriptor,
745            /* keymap= */ None,
746        )];
747
748        assert_input_report_sequence_generates_events!(
749            input_reports: reports,
750            expected_events: expected_events,
751            device_descriptor: descriptor,
752            device_type: KeyboardBinding,
753        );
754    }
755
756    /// Tests that both pressed and released keys are sent at once.
757    #[fasync::run_singlethreaded(test)]
758    async fn pressed_and_released_keys() {
759        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
760            keys: vec![fidl_fuchsia_input::Key::A, fidl_fuchsia_input::Key::B],
761            ..Default::default()
762        });
763        let (event_time_i64, _) = testing_utilities::event_times();
764
765        let reports = vec![
766            testing_utilities::create_keyboard_input_report(
767                vec![fidl_fuchsia_input::Key::A],
768                event_time_i64,
769            ),
770            testing_utilities::create_keyboard_input_report(
771                vec![fidl_fuchsia_input::Key::B],
772                event_time_i64,
773            ),
774        ];
775
776        let expected_events = vec![
777            testing_utilities::create_keyboard_event(
778                fidl_fuchsia_input::Key::A,
779                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
780                None,
781                &descriptor,
782                /* keymap= */ None,
783            ),
784            testing_utilities::create_keyboard_event(
785                fidl_fuchsia_input::Key::A,
786                fidl_fuchsia_ui_input3::KeyEventType::Released,
787                None,
788                &descriptor,
789                /* keymap= */ None,
790            ),
791            testing_utilities::create_keyboard_event(
792                fidl_fuchsia_input::Key::B,
793                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
794                None,
795                &descriptor,
796                /* keymap= */ None,
797            ),
798        ];
799
800        assert_input_report_sequence_generates_events!(
801            input_reports: reports,
802            expected_events: expected_events,
803            device_descriptor: descriptor,
804            device_type: KeyboardBinding,
805        );
806    }
807
808    #[fuchsia::test]
809    fn get_unsided_modifiers() {
810        use fidl_ui_input3::Modifiers;
811        let event = KeyboardEvent::new(fidl_fuchsia_input::Key::A, KeyEventType::Pressed)
812            .into_with_modifiers(Some(Modifiers::all()));
813        assert_eq!(
814            event.get_unsided_modifiers(),
815            Modifiers::CAPS_LOCK
816                | Modifiers::NUM_LOCK
817                | Modifiers::SCROLL_LOCK
818                | Modifiers::FUNCTION
819                | Modifiers::SYMBOL
820                | Modifiers::SHIFT
821                | Modifiers::ALT
822                | Modifiers::ALT_GRAPH
823                | Modifiers::META
824                | Modifiers::CTRL
825        )
826    }
827
828    #[fuchsia::test]
829    fn conversion_fills_out_all_fields() {
830        use fidl_fuchsia_input::Key;
831        use fidl_ui_input3::{KeyMeaning, LockState, Modifiers, NonPrintableKey};
832        let event = KeyboardEvent::new(Key::A, KeyEventType::Pressed)
833            .into_with_modifiers(Some(Modifiers::all()))
834            .into_with_lock_state(Some(LockState::all()))
835            .into_with_repeat_sequence(42)
836            .into_with_key_meaning(Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)));
837
838        let actual = event.from_key_event_at_time(zx::MonotonicInstant::from_nanos(42));
839        assert_eq!(
840            actual,
841            fidl_fuchsia_ui_input3::KeyEvent {
842                timestamp: Some(42),
843                type_: Some(KeyEventType::Pressed),
844                key: Some(Key::A),
845                modifiers: Some(Modifiers::all()),
846                key_meaning: Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)),
847                repeat_sequence: Some(42),
848                lock_state: Some(LockState::all()),
849                ..Default::default()
850            }
851        );
852    }
853}