1use crate::input_device::{self, Handled, InputDeviceBinding, InputDeviceStatus, InputEvent};
6use crate::{autorepeater, metrics};
7use anyhow::{format_err, Error, Result};
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#[derive(Clone, Debug, PartialEq)]
32pub struct KeyboardEvent {
33 key: fidl_fuchsia_input::Key,
35
36 event_type: KeyEventType,
38
39 modifiers: Option<fidl_ui_input3::Modifiers>,
41
42 lock_state: Option<fidl_ui_input3::LockState>,
44
45 keymap: Option<String>,
48
49 key_meaning: Option<fidl_fuchsia_ui_input3::KeyMeaning>,
54
55 repeat_sequence: u32,
61
62 autorepeat_settings: Option<autorepeater::Settings>,
64}
65
66impl KeyboardEvent {
67 pub fn new(key: fidl_fuchsia_input::Key, event_type: KeyEventType) -> Self {
70 KeyboardEvent {
71 key,
72 event_type,
73 modifiers: None,
74 lock_state: None,
75 keymap: None,
76 key_meaning: None,
77 repeat_sequence: 0,
78 autorepeat_settings: Default::default(),
79 }
80 }
81
82 pub fn into_with_autorepeat_settings(
84 self,
85 autorepeat_settings: Option<autorepeater::Settings>,
86 ) -> Self {
87 Self { autorepeat_settings, ..self }
88 }
89
90 pub fn get_autorepeat_settings(&self) -> autorepeater::Settings {
91 self.autorepeat_settings.unwrap_or(Default::default())
92 }
93
94 pub fn get_key(&self) -> fidl_fuchsia_input::Key {
95 self.key
96 }
97
98 pub fn into_with_key(self, key: fidl_fuchsia_input::Key) -> Self {
100 Self { key, ..self }
101 }
102
103 pub fn get_event_type(&self) -> KeyEventType {
104 self.event_type
105 }
106
107 pub fn into_with_event_type(self, event_type: KeyEventType) -> Self {
109 Self { event_type, ..self }
110 }
111
112 pub fn into_with_folded_event(self) -> Self {
114 Self { event_type: self.get_event_type_folded(), ..self }
115 }
116
117 pub fn get_event_type_folded(&self) -> KeyEventType {
119 match self.event_type {
120 KeyEventType::Pressed | KeyEventType::Sync => KeyEventType::Pressed,
121 KeyEventType::Released | KeyEventType::Cancel => KeyEventType::Released,
122 }
123 }
124
125 pub fn into_with_modifiers(self, modifiers: Option<fidl_ui_input3::Modifiers>) -> Self {
127 Self { modifiers, ..self }
128 }
129
130 pub fn get_modifiers(&self) -> Option<fidl_ui_input3::Modifiers> {
132 self.modifiers
133 }
134
135 pub fn get_unsided_modifiers(&self) -> fidl_fuchsia_ui_input3::Modifiers {
139 use fidl_fuchsia_ui_input3::Modifiers;
140 let mut modifiers = self.modifiers.unwrap_or(Modifiers::empty());
141 modifiers.set(
142 Modifiers::LEFT_ALT
143 | Modifiers::LEFT_CTRL
144 | Modifiers::LEFT_SHIFT
145 | Modifiers::LEFT_META
146 | Modifiers::RIGHT_ALT
147 | Modifiers::RIGHT_CTRL
148 | Modifiers::RIGHT_SHIFT
149 | Modifiers::RIGHT_META,
150 false,
151 );
152 modifiers
153 }
154
155 pub fn into_with_lock_state(self, lock_state: Option<fidl_ui_input3::LockState>) -> Self {
157 Self { lock_state, ..self }
158 }
159
160 pub fn get_lock_state(&self) -> Option<fidl_ui_input3::LockState> {
162 self.lock_state
163 }
164
165 pub fn into_with_keymap(self, keymap: Option<String>) -> Self {
168 Self { keymap, ..self }
169 }
170
171 pub fn get_keymap(&self) -> Option<String> {
173 self.keymap.clone()
174 }
175
176 pub fn into_with_key_meaning(
178 self,
179 key_meaning: Option<fidl_fuchsia_ui_input3::KeyMeaning>,
180 ) -> Self {
181 Self { key_meaning, ..self }
182 }
183
184 pub fn get_key_meaning(&self) -> Option<fidl_fuchsia_ui_input3::KeyMeaning> {
186 self.key_meaning
187 }
188
189 pub fn get_repeat_sequence(&self) -> u32 {
193 self.repeat_sequence
194 }
195
196 pub fn into_with_repeat_sequence(self, repeat_sequence: u32) -> Self {
199 Self { repeat_sequence, ..self }
200 }
201
202 #[cfg(test)]
204 pub(crate) fn from_key_event_at_time(
205 &self,
206 event_time: zx::MonotonicInstant,
207 ) -> fidl_ui_input3::KeyEvent {
208 fidl_ui_input3::KeyEvent {
209 timestamp: Some(event_time.into_nanos()),
210 type_: Some(self.event_type),
211 key: Some(self.key),
212 modifiers: self.modifiers,
213 lock_state: self.lock_state,
214 repeat_sequence: Some(self.repeat_sequence),
215 key_meaning: self.key_meaning,
216 ..Default::default()
217 }
218 }
219}
220
221impl KeyboardEvent {
222 pub fn same_key(this: &KeyboardEvent, that: &KeyboardEvent) -> bool {
224 this.get_key() == that.get_key()
225 }
226}
227
228#[derive(Clone, Debug, PartialEq)]
230pub struct KeyboardDeviceDescriptor {
231 pub keys: Vec<fidl_fuchsia_input::Key>,
233
234 pub device_information: fidl_fuchsia_input_report::DeviceInformation,
236
237 pub device_id: u32,
239}
240
241#[cfg(test)]
242impl Default for KeyboardDeviceDescriptor {
243 fn default() -> Self {
244 KeyboardDeviceDescriptor {
245 keys: vec![],
246 device_information: fidl_fuchsia_input_report::DeviceInformation {
247 vendor_id: Some(0),
248 product_id: Some(0),
249 version: Some(0),
250 polling_rate: Some(0),
251 ..Default::default()
252 },
253 device_id: 0,
254 }
255 }
256}
257
258pub struct KeyboardBinding {
264 event_sender: UnboundedSender<input_device::InputEvent>,
266
267 device_descriptor: KeyboardDeviceDescriptor,
269}
270
271#[async_trait]
272impl input_device::InputDeviceBinding for KeyboardBinding {
273 fn input_event_sender(&self) -> UnboundedSender<input_device::InputEvent> {
274 self.event_sender.clone()
275 }
276
277 fn get_device_descriptor(&self) -> input_device::InputDeviceDescriptor {
278 input_device::InputDeviceDescriptor::Keyboard(self.device_descriptor.clone())
279 }
280}
281
282impl KeyboardBinding {
283 pub async fn new(
298 device_proxy: InputDeviceProxy,
299 device_id: u32,
300 input_event_sender: UnboundedSender<input_device::InputEvent>,
301 device_node: fuchsia_inspect::Node,
302 metrics_logger: metrics::MetricsLogger,
303 ) -> Result<Self, Error> {
304 let (device_binding, mut inspect_status) = Self::bind_device(
305 &device_proxy,
306 input_event_sender,
307 device_id,
308 device_node,
309 metrics_logger.clone(),
310 )
311 .await?;
312 inspect_status.health_node.set_ok();
313 input_device::initialize_report_stream(
314 device_proxy,
315 device_binding.get_device_descriptor(),
316 device_binding.input_event_sender(),
317 inspect_status,
318 metrics_logger,
319 Self::process_reports,
320 );
321
322 Ok(device_binding)
323 }
324
325 pub fn to_modifiers(keys: &[&fidl_fuchsia_input::Key]) -> Option<fidl_ui_input3::Modifiers> {
336 let mut modifiers = fidl_ui_input3::Modifiers::empty();
337 for key in keys {
338 let modifier = match key {
339 fidl_fuchsia_input::Key::CapsLock => Some(fidl_ui_input3::Modifiers::CAPS_LOCK),
340 fidl_fuchsia_input::Key::NumLock => Some(fidl_ui_input3::Modifiers::NUM_LOCK),
341 fidl_fuchsia_input::Key::ScrollLock => Some(fidl_ui_input3::Modifiers::SCROLL_LOCK),
342 _ => None,
343 };
344 if let Some(modifier) = modifier {
345 modifiers.insert(modifier);
346 };
347 }
348 if modifiers.is_empty() {
349 return None;
350 }
351 Some(modifiers)
352 }
353
354 async fn bind_device(
366 device: &InputDeviceProxy,
367 input_event_sender: UnboundedSender<input_device::InputEvent>,
368 device_id: u32,
369 device_node: fuchsia_inspect::Node,
370 metrics_logger: metrics::MetricsLogger,
371 ) -> Result<(Self, InputDeviceStatus), Error> {
372 let mut input_device_status = InputDeviceStatus::new(device_node);
373 let descriptor = match device.get_descriptor().await {
374 Ok(descriptor) => descriptor,
375 Err(_) => {
376 input_device_status.health_node.set_unhealthy("Could not get device descriptor.");
377 return Err(format_err!("Could not get descriptor for device_id: {}", device_id));
378 }
379 };
380
381 let device_info = descriptor.device_information.ok_or_else(|| {
382 input_device_status.health_node.set_unhealthy("Empty device_information in descriptor");
383 metrics_logger.log_error(
386 InputPipelineErrorMetricDimensionEvent::KeyboardEmptyDeviceInfo,
387 std::format!("DRIVER BUG: empty device_information for device_id: {}", device_id),
388 );
389 format_err!("empty device info for device_id: {}", device_id)
390 })?;
391 match descriptor.keyboard {
392 Some(fidl_fuchsia_input_report::KeyboardDescriptor {
393 input: Some(fidl_fuchsia_input_report::KeyboardInputDescriptor { keys3, .. }),
394 output: _,
395 ..
396 }) => Ok((
397 KeyboardBinding {
398 event_sender: input_event_sender,
399 device_descriptor: KeyboardDeviceDescriptor {
400 keys: keys3.unwrap_or_default(),
401 device_information: device_info,
402 device_id,
403 },
404 },
405 input_device_status,
406 )),
407 device_descriptor => {
408 input_device_status
409 .health_node
410 .set_unhealthy("Keyboard Device Descriptor failed to parse.");
411 Err(format_err!(
412 "Keyboard Device Descriptor failed to parse: \n {:?}",
413 device_descriptor
414 ))
415 }
416 }
417 }
418
419 fn process_reports(
439 report: InputReport,
440 previous_report: Option<InputReport>,
441 device_descriptor: &input_device::InputDeviceDescriptor,
442 input_event_sender: &mut UnboundedSender<input_device::InputEvent>,
443 inspect_status: &InputDeviceStatus,
444 metrics_logger: &metrics::MetricsLogger,
445 ) -> (Option<InputReport>, Option<UnboundedReceiver<InputEvent>>) {
446 inspect_status.count_received_report(&report);
447 match &report.keyboard {
449 None => {
450 inspect_status.count_filtered_report();
451 return (previous_report, None);
452 }
453 _ => (),
454 };
455
456 let new_keys = match KeyboardBinding::parse_pressed_keys(&report) {
457 Some(keys) => keys,
458 None => {
459 metrics_logger.log_error(
465 InputPipelineErrorMetricDimensionEvent::KeyboardFailedToParse,
466 std::format!("Failed to parse keyboard keys: {:?}", report),
467 );
468 inspect_status.count_filtered_report();
469 return (previous_report, None);
470 }
471 };
472
473 let previous_keys: Vec<fidl_fuchsia_input::Key> = previous_report
474 .as_ref()
475 .and_then(|unwrapped_report| KeyboardBinding::parse_pressed_keys(&unwrapped_report))
476 .unwrap_or_default();
477
478 let (inspect_sender, inspect_receiver) = futures::channel::mpsc::unbounded();
479
480 KeyboardBinding::send_key_events(
481 &new_keys,
482 &previous_keys,
483 device_descriptor.clone(),
484 zx::MonotonicInstant::get(),
485 input_event_sender.clone(),
486 inspect_sender,
487 metrics_logger,
488 );
489
490 (Some(report), Some(inspect_receiver))
491 }
492
493 fn parse_pressed_keys(input_report: &InputReport) -> Option<Vec<fidl_fuchsia_input::Key>> {
503 input_report
504 .keyboard
505 .as_ref()
506 .and_then(|unwrapped_keyboard| unwrapped_keyboard.pressed_keys3.as_ref())
507 .and_then(|unwrapped_keys| Some(unwrapped_keys.iter().cloned().collect()))
508 }
509
510 fn send_key_events(
519 new_keys: &Vec<fidl_fuchsia_input::Key>,
520 previous_keys: &Vec<fidl_fuchsia_input::Key>,
521 device_descriptor: input_device::InputDeviceDescriptor,
522 event_time: zx::MonotonicInstant,
523 input_event_sender: UnboundedSender<input_device::InputEvent>,
524 inspect_sender: UnboundedSender<input_device::InputEvent>,
525 metrics_logger: &metrics::MetricsLogger,
526 ) {
527 fn dispatch_events(
531 key_events: Vec<(fidl_fuchsia_input::Key, fidl_fuchsia_ui_input3::KeyEventType)>,
532 device_descriptor: input_device::InputDeviceDescriptor,
533 event_time: zx::MonotonicInstant,
534 input_event_sender: UnboundedSender<input_device::InputEvent>,
535 inspect_sender: UnboundedSender<input_device::InputEvent>,
536 metrics_logger: metrics::MetricsLogger,
537 ) {
538 fasync::Task::local(async move {
539 let mut event_time = event_time;
540 for (key, event_type) in key_events.into_iter() {
541 let event = input_device::InputEvent {
542 device_event: input_device::InputDeviceEvent::Keyboard(
543 KeyboardEvent::new(key, event_type),
544 ),
545 device_descriptor: device_descriptor.clone(),
546 event_time,
547 handled: Handled::No,
548 trace_id: None,
549 };
550 match input_event_sender.unbounded_send(event.clone()) {
551 Err(error) => {
552 metrics_logger.log_error(
553 InputPipelineErrorMetricDimensionEvent::KeyboardFailedToSendKeyboardEvent,
554 std::format!(
555 "Failed to send KeyboardEvent for key: {:?}, event_type: {:?}: {:?}",
556 &key,
557 &event_type,
558 error));
559 }
560 _ => { let _ = inspect_sender.unbounded_send(event).expect("Failed to count generated KeyboardEvent in Input Pipeline Inspect tree."); },
561 }
562 event_time = event_time + zx::MonotonicDuration::from_nanos(1);
567 }
568 })
569 .detach();
570 }
571
572 let pressed_keys = new_keys
575 .iter()
576 .cloned()
577 .filter(|key| !previous_keys.contains(key))
578 .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Pressed));
579
580 let released_keys = previous_keys
583 .iter()
584 .cloned()
585 .filter(|key| !new_keys.contains(key))
586 .map(|k| (k, fidl_fuchsia_ui_input3::KeyEventType::Released));
587
588 let all_keys = released_keys.chain(pressed_keys).collect::<Vec<_>>();
593
594 dispatch_events(
595 all_keys,
596 device_descriptor,
597 event_time,
598 input_event_sender,
599 inspect_sender,
600 metrics_logger.clone(),
601 );
602 }
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608 use crate::testing_utilities;
609 use fuchsia_async as fasync;
610 use futures::StreamExt;
611
612 #[fasync::run_singlethreaded(test)]
615 async fn pressed_key() {
616 let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
617 keys: vec![fidl_fuchsia_input::Key::A],
618 ..Default::default()
619 });
620 let (event_time_i64, _) = testing_utilities::event_times();
621
622 let reports = vec![testing_utilities::create_keyboard_input_report(
623 vec![fidl_fuchsia_input::Key::A],
624 event_time_i64,
625 )];
626 let expected_events = vec![testing_utilities::create_keyboard_event(
627 fidl_fuchsia_input::Key::A,
628 fidl_fuchsia_ui_input3::KeyEventType::Pressed,
629 None,
630 &descriptor,
631 None,
632 )];
633
634 assert_input_report_sequence_generates_events!(
635 input_reports: reports,
636 expected_events: expected_events,
637 device_descriptor: descriptor,
638 device_type: KeyboardBinding,
639 );
640 }
641
642 #[fasync::run_singlethreaded(test)]
645 async fn released_key() {
646 let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
647 keys: vec![fidl_fuchsia_input::Key::A],
648 ..Default::default()
649 });
650 let (event_time_i64, _) = testing_utilities::event_times();
651
652 let reports = vec![
653 testing_utilities::create_keyboard_input_report(
654 vec![fidl_fuchsia_input::Key::A],
655 event_time_i64,
656 ),
657 testing_utilities::create_keyboard_input_report(vec![], event_time_i64),
658 ];
659
660 let expected_events = vec![
661 testing_utilities::create_keyboard_event(
662 fidl_fuchsia_input::Key::A,
663 fidl_fuchsia_ui_input3::KeyEventType::Pressed,
664 None,
665 &descriptor,
666 None,
667 ),
668 testing_utilities::create_keyboard_event(
669 fidl_fuchsia_input::Key::A,
670 fidl_fuchsia_ui_input3::KeyEventType::Released,
671 None,
672 &descriptor,
673 None,
674 ),
675 ];
676
677 assert_input_report_sequence_generates_events!(
678 input_reports: reports,
679 expected_events: expected_events,
680 device_descriptor: descriptor.clone(),
681 device_type: KeyboardBinding,
682 );
683 }
684
685 #[fasync::run_singlethreaded(test)]
688 async fn multiple_pressed_event_filtering() {
689 let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
690 keys: vec![fidl_fuchsia_input::Key::A],
691 ..Default::default()
692 });
693 let (event_time_i64, _) = testing_utilities::event_times();
694
695 let reports = vec![
696 testing_utilities::create_keyboard_input_report(
697 vec![fidl_fuchsia_input::Key::A],
698 event_time_i64,
699 ),
700 testing_utilities::create_keyboard_input_report(
701 vec![fidl_fuchsia_input::Key::A],
702 event_time_i64,
703 ),
704 ];
705
706 let expected_events = vec![testing_utilities::create_keyboard_event(
707 fidl_fuchsia_input::Key::A,
708 fidl_fuchsia_ui_input3::KeyEventType::Pressed,
709 None,
710 &descriptor,
711 None,
712 )];
713
714 assert_input_report_sequence_generates_events!(
715 input_reports: reports,
716 expected_events: expected_events,
717 device_descriptor: descriptor,
718 device_type: KeyboardBinding,
719 );
720 }
721
722 #[fasync::run_singlethreaded(test)]
724 async fn pressed_and_released_keys() {
725 let descriptor = input_device::InputDeviceDescriptor::Keyboard(KeyboardDeviceDescriptor {
726 keys: vec![fidl_fuchsia_input::Key::A, fidl_fuchsia_input::Key::B],
727 ..Default::default()
728 });
729 let (event_time_i64, _) = testing_utilities::event_times();
730
731 let reports = vec![
732 testing_utilities::create_keyboard_input_report(
733 vec![fidl_fuchsia_input::Key::A],
734 event_time_i64,
735 ),
736 testing_utilities::create_keyboard_input_report(
737 vec![fidl_fuchsia_input::Key::B],
738 event_time_i64,
739 ),
740 ];
741
742 let expected_events = vec![
743 testing_utilities::create_keyboard_event(
744 fidl_fuchsia_input::Key::A,
745 fidl_fuchsia_ui_input3::KeyEventType::Pressed,
746 None,
747 &descriptor,
748 None,
749 ),
750 testing_utilities::create_keyboard_event(
751 fidl_fuchsia_input::Key::A,
752 fidl_fuchsia_ui_input3::KeyEventType::Released,
753 None,
754 &descriptor,
755 None,
756 ),
757 testing_utilities::create_keyboard_event(
758 fidl_fuchsia_input::Key::B,
759 fidl_fuchsia_ui_input3::KeyEventType::Pressed,
760 None,
761 &descriptor,
762 None,
763 ),
764 ];
765
766 assert_input_report_sequence_generates_events!(
767 input_reports: reports,
768 expected_events: expected_events,
769 device_descriptor: descriptor,
770 device_type: KeyboardBinding,
771 );
772 }
773
774 #[fuchsia::test]
775 fn get_unsided_modifiers() {
776 use fidl_ui_input3::Modifiers;
777 let event = KeyboardEvent::new(fidl_fuchsia_input::Key::A, KeyEventType::Pressed)
778 .into_with_modifiers(Some(Modifiers::all()));
779 assert_eq!(
780 event.get_unsided_modifiers(),
781 Modifiers::CAPS_LOCK
782 | Modifiers::NUM_LOCK
783 | Modifiers::SCROLL_LOCK
784 | Modifiers::FUNCTION
785 | Modifiers::SYMBOL
786 | Modifiers::SHIFT
787 | Modifiers::ALT
788 | Modifiers::ALT_GRAPH
789 | Modifiers::META
790 | Modifiers::CTRL
791 )
792 }
793
794 #[fuchsia::test]
795 fn conversion_fills_out_all_fields() {
796 use fidl_fuchsia_input::Key;
797 use fidl_ui_input3::{KeyMeaning, LockState, Modifiers, NonPrintableKey};
798 let event = KeyboardEvent::new(Key::A, KeyEventType::Pressed)
799 .into_with_modifiers(Some(Modifiers::all()))
800 .into_with_lock_state(Some(LockState::all()))
801 .into_with_repeat_sequence(42)
802 .into_with_key_meaning(Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)));
803
804 let actual = event.from_key_event_at_time(zx::MonotonicInstant::from_nanos(42));
805 assert_eq!(
806 actual,
807 fidl_fuchsia_ui_input3::KeyEvent {
808 timestamp: Some(42),
809 type_: Some(KeyEventType::Pressed),
810 key: Some(Key::A),
811 modifiers: Some(Modifiers::all()),
812 key_meaning: Some(KeyMeaning::NonPrintableKey(NonPrintableKey::Tab)),
813 repeat_sequence: Some(42),
814 lock_state: Some(LockState::all()),
815 ..Default::default()
816 }
817 );
818 }
819}