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<input_device::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<input_device::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<input_device::InputEvent>,
285        device_node: fuchsia_inspect::Node,
286        metrics_logger: metrics::MetricsLogger,
287    ) -> Result<Self, Error> {
288        let (device_binding, mut inspect_status) = Self::bind_device(
289            &device_proxy,
290            input_event_sender,
291            device_id,
292            device_node,
293            metrics_logger.clone(),
294        )
295        .await?;
296        inspect_status.health_node.set_ok();
297        input_device::initialize_report_stream(
298            device_proxy,
299            device_binding.get_device_descriptor(),
300            device_binding.input_event_sender(),
301            inspect_status,
302            metrics_logger,
303            Self::process_reports,
304        );
305
306        Ok(device_binding)
307    }
308
309    /// Converts a vector of keyboard keys to the appropriate [`fidl_ui_input3::Modifiers`] bitflags.
310    ///
311    /// For example, if `keys` contains `Key::CapsLock`, the bitflags will contain the corresponding
312    /// flags for `CapsLock`.
313    ///
314    /// # Parameters
315    /// - `keys`: The keys to check for modifiers.
316    ///
317    /// # Returns
318    /// Returns `None` if there are no modifier keys present.
319    pub fn to_modifiers(keys: &[&fidl_fuchsia_input::Key]) -> Option<fidl_ui_input3::Modifiers> {
320        let mut modifiers = fidl_ui_input3::Modifiers::empty();
321        for key in keys {
322            let modifier = match key {
323                fidl_fuchsia_input::Key::CapsLock => Some(fidl_ui_input3::Modifiers::CAPS_LOCK),
324                fidl_fuchsia_input::Key::NumLock => Some(fidl_ui_input3::Modifiers::NUM_LOCK),
325                fidl_fuchsia_input::Key::ScrollLock => Some(fidl_ui_input3::Modifiers::SCROLL_LOCK),
326                _ => None,
327            };
328            if let Some(modifier) = modifier {
329                modifiers.insert(modifier);
330            };
331        }
332        if modifiers.is_empty() {
333            return None;
334        }
335        Some(modifiers)
336    }
337
338    /// Binds the provided input device to a new instance of `Self`.
339    ///
340    /// # Parameters
341    /// - `device`: The device to use to initialize the binding.
342    /// - `input_event_sender`: The channel to send new InputEvents to.
343    /// - `device_id`: The device ID being bound.
344    /// - `device_node`: The inspect node for this device binding
345    ///
346    /// # Errors
347    /// If the device descriptor could not be retrieved, or the descriptor could not be parsed
348    /// correctly.
349    async fn bind_device(
350        device: &InputDeviceProxy,
351        input_event_sender: UnboundedSender<input_device::InputEvent>,
352        device_id: u32,
353        device_node: fuchsia_inspect::Node,
354        metrics_logger: metrics::MetricsLogger,
355    ) -> Result<(Self, InputDeviceStatus), Error> {
356        let mut input_device_status = InputDeviceStatus::new(device_node);
357        let descriptor = match device.get_descriptor().await {
358            Ok(descriptor) => descriptor,
359            Err(_) => {
360                input_device_status.health_node.set_unhealthy("Could not get device descriptor.");
361                return Err(format_err!("Could not get descriptor for device_id: {}", device_id));
362            }
363        };
364
365        let device_info = descriptor.device_information.ok_or_else(|| {
366            input_device_status.health_node.set_unhealthy("Empty device_information in descriptor");
367            // Logging in addition to returning an error, as in some test
368            // setups the error may never be displayed to the user.
369            metrics_logger.log_error(
370                InputPipelineErrorMetricDimensionEvent::KeyboardEmptyDeviceInfo,
371                std::format!("DRIVER BUG: empty device_information for device_id: {}", device_id),
372            );
373            format_err!("empty device info for device_id: {}", device_id)
374        })?;
375        match descriptor.keyboard {
376            Some(fidl_fuchsia_input_report::KeyboardDescriptor {
377                input: Some(fidl_fuchsia_input_report::KeyboardInputDescriptor { keys3, .. }),
378                output: _,
379                ..
380            }) => Ok((
381                KeyboardBinding {
382                    event_sender: input_event_sender,
383                    device_descriptor: KeyboardDeviceDescriptor {
384                        keys: keys3.unwrap_or_default(),
385                        device_information: device_info,
386                        device_id,
387                    },
388                },
389                input_device_status,
390            )),
391            device_descriptor => {
392                input_device_status
393                    .health_node
394                    .set_unhealthy("Keyboard Device Descriptor failed to parse.");
395                Err(format_err!(
396                    "Keyboard Device Descriptor failed to parse: \n {:?}",
397                    device_descriptor
398                ))
399            }
400        }
401    }
402
403    /// Parses an [`InputReport`] into one or more [`InputEvent`]s.
404    ///
405    /// The [`InputEvent`]s are sent to the device binding owner via [`input_event_sender`].
406    ///
407    /// # Parameters
408    /// `reports`: The incoming [`InputReport`].
409    /// `previous_report`: The previous [`InputReport`] seen for the same device. This can be
410    ///                    used to determine, for example, which keys are no longer present in
411    ///                    a keyboard report to generate key released events. If `None`, no
412    ///                    previous report was found.
413    /// `device_descriptor`: The descriptor for the input device generating the input reports.
414    /// `input_event_sender`: The sender for the device binding's input event stream.
415    ///
416    /// # Returns
417    /// An [`InputReport`] which will be passed to the next call to [`process_reports`], as
418    /// [`previous_report`]. If `None`, the next call's [`previous_report`] will be `None`.
419    /// A [`UnboundedReceiver<InputEvent>`] which will poll asynchronously generated events to be
420    /// recorded by `inspect_status` in `input_device::initialize_report_stream()`. If device
421    /// binding does not generate InputEvents asynchronously, this will be `None`.
422    ///
423    /// The returned [`InputReport`] is guaranteed to have no `wake_lease`.
424    fn process_reports(
425        reports: Vec<InputReport>,
426        mut previous_report: Option<InputReport>,
427        device_descriptor: &input_device::InputDeviceDescriptor,
428        input_event_sender: &mut UnboundedSender<input_device::InputEvent>,
429        inspect_status: &InputDeviceStatus,
430        metrics_logger: &metrics::MetricsLogger,
431    ) -> (Option<InputReport>, Option<UnboundedReceiver<InputEvent>>) {
432        fuchsia_trace::duration!("input", "keyboard-binding-process-report", "num_reports" => reports.len());
433        let (inspect_sender, inspect_receiver) = futures::channel::mpsc::unbounded();
434
435        for report in reports {
436            previous_report = Self::process_report(
437                report,
438                previous_report,
439                device_descriptor,
440                input_event_sender,
441                inspect_status,
442                metrics_logger,
443                inspect_sender.clone(),
444            );
445        }
446
447        (previous_report, Some(inspect_receiver))
448    }
449
450    fn process_report(
451        mut report: InputReport,
452        previous_report: Option<InputReport>,
453        device_descriptor: &input_device::InputDeviceDescriptor,
454        input_event_sender: &mut UnboundedSender<input_device::InputEvent>,
455        inspect_status: &InputDeviceStatus,
456        metrics_logger: &metrics::MetricsLogger,
457        inspect_sender: UnboundedSender<InputEvent>,
458    ) -> Option<InputReport> {
459        if let Some(trace_id) = report.trace_id {
460            fuchsia_trace::flow_end!("input", "input_report", trace_id.into());
461        }
462
463        let tracing_id = fuchsia_trace::Id::random();
464        fuchsia_trace::flow_begin!("input", "key_event_thread", tracing_id);
465
466        inspect_status.count_received_report(&report);
467        // Input devices can have multiple types so ensure `report` is a KeyboardInputReport.
468        match &report.keyboard {
469            None => {
470                inspect_status.count_filtered_report();
471                return previous_report;
472            }
473            _ => (),
474        };
475
476        // Keyboard events cannot handle wake leases, so we drop them here.
477        drop(report.wake_lease.take());
478
479        let new_keys = match KeyboardBinding::parse_pressed_keys(&report) {
480            Some(keys) => keys,
481            None => {
482                // It's OK for the report to contain an empty vector of keys, but it's not OK for
483                // the report to not have the appropriate fields set.
484                //
485                // In this case the report is treated as malformed, and the previous report is not
486                // updated.
487                metrics_logger.log_error(
488                    InputPipelineErrorMetricDimensionEvent::KeyboardFailedToParse,
489                    std::format!("Failed to parse keyboard keys: {:?}", report),
490                );
491                inspect_status.count_filtered_report();
492                return previous_report;
493            }
494        };
495
496        let previous_keys: Vec<fidl_fuchsia_input::Key> = previous_report
497            .as_ref()
498            .and_then(|unwrapped_report| KeyboardBinding::parse_pressed_keys(&unwrapped_report))
499            .unwrap_or_default();
500
501        KeyboardBinding::send_key_events(
502            &new_keys,
503            &previous_keys,
504            device_descriptor.clone(),
505            zx::MonotonicInstant::get(),
506            input_event_sender.clone(),
507            inspect_sender,
508            metrics_logger,
509            tracing_id,
510        );
511
512        Some(report)
513    }
514
515    /// Parses the currently pressed [`fidl_fuchsia_input3::Key`]s from an input report.
516    ///
517    /// # Parameters
518    /// - `input_report`: The input report to parse the keyboard keys from.
519    ///
520    /// # Returns
521    /// Returns `None` if any of the required input report fields are `None`. If all the
522    /// required report fields are present, but there are no pressed keys, an empty vector
523    /// is returned.
524    fn parse_pressed_keys(input_report: &InputReport) -> Option<Vec<fidl_fuchsia_input::Key>> {
525        input_report
526            .keyboard
527            .as_ref()
528            .and_then(|unwrapped_keyboard| unwrapped_keyboard.pressed_keys3.as_ref())
529            .and_then(|unwrapped_keys| Some(unwrapped_keys.iter().cloned().collect()))
530    }
531
532    /// Sends key events to clients based on the new and previously pressed keys.
533    ///
534    /// # Parameters
535    /// - `new_keys`: The input3 keys which are currently pressed, as reported by the bound device.
536    /// - `previous_keys`: The input3 keys which were pressed in the previous input report.
537    /// - `device_descriptor`: The descriptor for the input device generating the input reports.
538    /// - `event_time`: The time in nanoseconds when the event was first recorded.
539    /// - `input_event_sender`: The sender for the device binding's input event stream.
540    fn send_key_events(
541        new_keys: &Vec<fidl_fuchsia_input::Key>,
542        previous_keys: &Vec<fidl_fuchsia_input::Key>,
543        device_descriptor: input_device::InputDeviceDescriptor,
544        event_time: zx::MonotonicInstant,
545        input_event_sender: UnboundedSender<input_device::InputEvent>,
546        inspect_sender: UnboundedSender<input_device::InputEvent>,
547        metrics_logger: &metrics::MetricsLogger,
548        tracing_id: fuchsia_trace::Id,
549    ) {
550        // Dispatches all key events individually in a separate task.  This is done in a separate
551        // function so that the lifetime of `new_keys` above could be detached from that of the
552        // spawned task.
553        fn dispatch_events(
554            key_events: Vec<(fidl_fuchsia_input::Key, fidl_fuchsia_ui_input3::KeyEventType)>,
555            device_descriptor: input_device::InputDeviceDescriptor,
556            event_time: zx::MonotonicInstant,
557            input_event_sender: UnboundedSender<input_device::InputEvent>,
558            inspect_sender: UnboundedSender<input_device::InputEvent>,
559            metrics_logger: metrics::MetricsLogger,
560            tracing_id: fuchsia_trace::Id,
561        ) {
562            fasync::Task::local(async move {
563                fuchsia_trace::duration!("input", "key_event_thread");
564                fuchsia_trace::flow_end!("input", "key_event_thread", tracing_id);
565
566                let mut event_time = event_time;
567                for (key, event_type) in key_events.into_iter() {
568                    let trace_id = fuchsia_trace::Id::random();
569                    fuchsia_trace::duration!("input", "keyboard_event_in_binding");
570                    fuchsia_trace::flow_begin!("input", "event_in_input_pipeline", trace_id);
571
572                    let event = input_device::InputEvent {
573                        device_event: input_device::InputDeviceEvent::Keyboard(
574                            KeyboardEvent::new(key, event_type),
575                        ),
576                        device_descriptor: device_descriptor.clone(),
577                        event_time,
578                        handled: Handled::No,
579                        trace_id: Some(trace_id),
580                    };
581                    match input_event_sender.unbounded_send(event.clone()) {
582                        Err(error) => {
583                            metrics_logger.log_error(
584                                InputPipelineErrorMetricDimensionEvent::KeyboardFailedToSendKeyboardEvent,
585                                std::format!(
586                                    "Failed to send KeyboardEvent for key: {:?}, event_type: {:?}: {:?}",
587                                    &key,
588                                    &event_type,
589                                    error));
590                        }
591                        _ => { let _ = inspect_sender.unbounded_send(event).expect("Failed to count generated KeyboardEvent in Input Pipeline Inspect tree."); },
592                    }
593                    // If key events happen to have been reported at the same time,
594                    // we pull them apart artificially. A 1ns increment will likely
595                    // be enough of a difference that it is recognizable but that it
596                    // does not introduce confusion.
597                    event_time = event_time + zx::MonotonicDuration::from_nanos(1);
598                }
599            })
600            .detach();
601        }
602
603        // Filter out the keys which were present in the previous keyboard report to avoid sending
604        // multiple `KeyEventType::Pressed` events for a key.
605        let pressed_keys = new_keys
606            .iter()
607            .cloned()
608            .filter(|key| !previous_keys.contains(key))
609            .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Pressed));
610
611        // Any key which is not present in the new keys, but was present in the previous report
612        // is considered to be released.
613        let released_keys = previous_keys
614            .iter()
615            .cloned()
616            .filter(|key| !new_keys.contains(key))
617            .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Released));
618
619        // It is important that key releases are dispatched before key presses,
620        // so that modifier tracking would work correctly.  We collect the result
621        // into a vector since an iterator is not Send and can not be moved into
622        // a closure.
623        let all_keys = released_keys.chain(pressed_keys).collect::<Vec<_>>();
624
625        dispatch_events(
626            all_keys,
627            device_descriptor,
628            event_time,
629            input_event_sender,
630            inspect_sender,
631            metrics_logger.clone(),
632            tracing_id,
633        );
634    }
635}
636
637#[cfg(test)]
638mod tests {
639    use super::*;
640    use crate::testing_utilities;
641    use fuchsia_async as fasync;
642    use futures::StreamExt;
643
644    /// Tests that a key that is present in the new report, but was not present in the previous report
645    /// is propagated as pressed.
646    #[fasync::run_singlethreaded(test)]
647    async fn pressed_key() {
648        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
649            keys: vec![fidl_fuchsia_input::Key::A],
650            ..Default::default()
651        });
652        let (event_time_i64, _) = testing_utilities::event_times();
653
654        let reports = vec![testing_utilities::create_keyboard_input_report(
655            vec![fidl_fuchsia_input::Key::A],
656            event_time_i64,
657        )];
658        let expected_events = vec![testing_utilities::create_keyboard_event(
659            fidl_fuchsia_input::Key::A,
660            fidl_fuchsia_ui_input3::KeyEventType::Pressed,
661            None,
662            &descriptor,
663            /* keymap= */ None,
664        )];
665
666        assert_input_report_sequence_generates_events!(
667            input_reports: reports,
668            expected_events: expected_events,
669            device_descriptor: descriptor,
670            device_type: KeyboardBinding,
671        );
672    }
673
674    /// Tests that a key that is not present in the new report, but was present in the previous report
675    /// is propagated as released.
676    #[fasync::run_singlethreaded(test)]
677    async fn released_key() {
678        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
679            keys: vec![fidl_fuchsia_input::Key::A],
680            ..Default::default()
681        });
682        let (event_time_i64, _) = testing_utilities::event_times();
683
684        let reports = vec![
685            testing_utilities::create_keyboard_input_report(
686                vec![fidl_fuchsia_input::Key::A],
687                event_time_i64,
688            ),
689            testing_utilities::create_keyboard_input_report(vec![], event_time_i64),
690        ];
691
692        let expected_events = vec![
693            testing_utilities::create_keyboard_event(
694                fidl_fuchsia_input::Key::A,
695                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
696                None,
697                &descriptor,
698                /* keymap= */ None,
699            ),
700            testing_utilities::create_keyboard_event(
701                fidl_fuchsia_input::Key::A,
702                fidl_fuchsia_ui_input3::KeyEventType::Released,
703                None,
704                &descriptor,
705                /* keymap= */ None,
706            ),
707        ];
708
709        assert_input_report_sequence_generates_events!(
710            input_reports: reports,
711            expected_events: expected_events,
712            device_descriptor: descriptor.clone(),
713            device_type: KeyboardBinding,
714        );
715    }
716
717    /// Tests that a key that is present in multiple consecutive input reports is not propagated
718    /// as a pressed event more than once.
719    #[fasync::run_singlethreaded(test)]
720    async fn multiple_pressed_event_filtering() {
721        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
722            keys: vec![fidl_fuchsia_input::Key::A],
723            ..Default::default()
724        });
725        let (event_time_i64, _) = testing_utilities::event_times();
726
727        let reports = vec![
728            testing_utilities::create_keyboard_input_report(
729                vec![fidl_fuchsia_input::Key::A],
730                event_time_i64,
731            ),
732            testing_utilities::create_keyboard_input_report(
733                vec![fidl_fuchsia_input::Key::A],
734                event_time_i64,
735            ),
736        ];
737
738        let expected_events = vec![testing_utilities::create_keyboard_event(
739            fidl_fuchsia_input::Key::A,
740            fidl_fuchsia_ui_input3::KeyEventType::Pressed,
741            None,
742            &descriptor,
743            /* keymap= */ None,
744        )];
745
746        assert_input_report_sequence_generates_events!(
747            input_reports: reports,
748            expected_events: expected_events,
749            device_descriptor: descriptor,
750            device_type: KeyboardBinding,
751        );
752    }
753
754    /// Tests that both pressed and released keys are sent at once.
755    #[fasync::run_singlethreaded(test)]
756    async fn pressed_and_released_keys() {
757        let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
758            keys: vec![fidl_fuchsia_input::Key::A, fidl_fuchsia_input::Key::B],
759            ..Default::default()
760        });
761        let (event_time_i64, _) = testing_utilities::event_times();
762
763        let reports = vec![
764            testing_utilities::create_keyboard_input_report(
765                vec![fidl_fuchsia_input::Key::A],
766                event_time_i64,
767            ),
768            testing_utilities::create_keyboard_input_report(
769                vec![fidl_fuchsia_input::Key::B],
770                event_time_i64,
771            ),
772        ];
773
774        let expected_events = vec![
775            testing_utilities::create_keyboard_event(
776                fidl_fuchsia_input::Key::A,
777                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
778                None,
779                &descriptor,
780                /* keymap= */ None,
781            ),
782            testing_utilities::create_keyboard_event(
783                fidl_fuchsia_input::Key::A,
784                fidl_fuchsia_ui_input3::KeyEventType::Released,
785                None,
786                &descriptor,
787                /* keymap= */ None,
788            ),
789            testing_utilities::create_keyboard_event(
790                fidl_fuchsia_input::Key::B,
791                fidl_fuchsia_ui_input3::KeyEventType::Pressed,
792                None,
793                &descriptor,
794                /* keymap= */ None,
795            ),
796        ];
797
798        assert_input_report_sequence_generates_events!(
799            input_reports: reports,
800            expected_events: expected_events,
801            device_descriptor: descriptor,
802            device_type: KeyboardBinding,
803        );
804    }
805
806    #[fuchsia::test]
807    fn get_unsided_modifiers() {
808        use fidl_ui_input3::Modifiers;
809        let event = KeyboardEvent::new(fidl_fuchsia_input::Key::A, KeyEventType::Pressed)
810            .into_with_modifiers(Some(Modifiers::all()));
811        assert_eq!(
812            event.get_unsided_modifiers(),
813            Modifiers::CAPS_LOCK
814                | Modifiers::NUM_LOCK
815                | Modifiers::SCROLL_LOCK
816                | Modifiers::FUNCTION
817                | Modifiers::SYMBOL
818                | Modifiers::SHIFT
819                | Modifiers::ALT
820                | Modifiers::ALT_GRAPH
821                | Modifiers::META
822                | Modifiers::CTRL
823        )
824    }
825
826    #[fuchsia::test]
827    fn conversion_fills_out_all_fields() {
828        use fidl_fuchsia_input::Key;
829        use fidl_ui_input3::{KeyMeaning, LockState, Modifiers, NonPrintableKey};
830        let event = KeyboardEvent::new(Key::A, KeyEventType::Pressed)
831            .into_with_modifiers(Some(Modifiers::all()))
832            .into_with_lock_state(Some(LockState::all()))
833            .into_with_repeat_sequence(42)
834            .into_with_key_meaning(Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)));
835
836        let actual = event.from_key_event_at_time(zx::MonotonicInstant::from_nanos(42));
837        assert_eq!(
838            actual,
839            fidl_fuchsia_ui_input3::KeyEvent {
840                timestamp: Some(42),
841                type_: Some(KeyEventType::Pressed),
842                key: Some(Key::A),
843                modifiers: Some(Modifiers::all()),
844                key_meaning: Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)),
845                repeat_sequence: Some(42),
846                lock_state: Some(LockState::all()),
847                ..Default::default()
848            }
849        );
850    }
851}