Skip to main content

starnix_modules_input_event_conversion/
key_fuchsia_to_linux.rs

1// Copyright 2025 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::keymap::KEY_MAP;
6use fidl_fuchsia_ui_input3 as fuiinput;
7use starnix_types::time::timeval_from_time;
8use starnix_uapi::uapi;
9
10/// Converts fuchsia KeyEven to a vector of `uapi::input_events`.
11///
12/// A single `KeyEvent` may translate into multiple `uapi::input_events`.
13/// 1 key event and 1 sync event.
14///
15/// If translation fails an empty vector is returned.
16pub fn parse_fidl_keyboard_event_to_linux_input_event(
17    e: &fuiinput::KeyEvent,
18    is_uinput_running: bool,
19) -> Vec<uapi::input_event> {
20    #[allow(clippy::vec_init_then_push, reason = "mass allow for https://fxbug.dev/381896734")]
21    match e {
22        &fuiinput::KeyEvent {
23            timestamp: Some(time_nanos),
24            type_: Some(event_type),
25            key: Some(key),
26            ..
27        } => {
28            let lkey = KEY_MAP.fuchsia_input_key_to_linux_keycode(key);
29            // return empty for unknown keycode.
30            if lkey == uapi::KEY_RESERVED {
31                return vec![];
32            }
33            let lkey = match lkey {
34                // TODO(b/312467059): keep this ESC -> Power workaround for debug.
35                uapi::KEY_ESC => {
36                    if is_uinput_running {
37                        uapi::KEY_ESC
38                    } else {
39                        uapi::KEY_POWER
40                    }
41                }
42                k => k,
43            };
44
45            let time = timeval_from_time(zx::MonotonicInstant::from_nanos(time_nanos));
46            let key_event = uapi::input_event {
47                time,
48                type_: uapi::EV_KEY as u16,
49                code: lkey as u16,
50                value: if event_type == fuiinput::KeyEventType::Pressed { 1 } else { 0 },
51            };
52
53            let sync_event = uapi::input_event {
54                // See https://www.kernel.org/doc/Documentation/input/event-codes.rst.
55                time,
56                type_: uapi::EV_SYN as u16,
57                code: uapi::SYN_REPORT as u16,
58                value: 0,
59            };
60
61            let mut events = vec![];
62            events.push(key_event);
63            events.push(sync_event);
64            events
65        }
66        _ => vec![],
67    }
68}