keyboard.rs

  1#[cfg(any(feature = "wayland", feature = "x11"))]
  2use std::sync::LazyLock;
  3
  4#[cfg(any(feature = "wayland", feature = "x11"))]
  5use collections::{HashMap, HashSet};
  6#[cfg(any(feature = "wayland", feature = "x11"))]
  7use strum::{EnumIter, IntoEnumIterator as _};
  8#[cfg(any(feature = "wayland", feature = "x11"))]
  9use x11rb::{protocol::xkb::ConnectionExt as _, xcb_ffi::XCBConnection};
 10#[cfg(any(feature = "wayland", feature = "x11"))]
 11use xkbcommon::xkb::{
 12    Keycode, Keysym,
 13    x11::ffi::{XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION},
 14};
 15
 16use crate::{PlatformKeyboardLayout, SharedString};
 17
 18#[derive(Clone)]
 19pub(crate) struct LinuxKeyboardLayout {
 20    name: SharedString,
 21}
 22
 23impl PlatformKeyboardLayout for LinuxKeyboardLayout {
 24    fn id(&self) -> &str {
 25        &self.name
 26    }
 27
 28    fn name(&self) -> &str {
 29        &self.name
 30    }
 31}
 32
 33impl LinuxKeyboardLayout {
 34    pub(crate) fn new(name: SharedString) -> Self {
 35        Self { name }
 36    }
 37}
 38
 39#[cfg(any(feature = "wayland", feature = "x11"))]
 40static XCB_CONNECTION: LazyLock<XCBConnection> =
 41    LazyLock::new(|| XCBConnection::connect(None).unwrap().0);
 42
 43#[cfg(any(feature = "wayland", feature = "x11"))]
 44pub(crate) struct LinuxKeyboardMapper {
 45    letters: HashMap<Keycode, String>,
 46    code_to_key: HashMap<Keycode, String>,
 47    code_to_shifted_key: HashMap<Keycode, String>,
 48}
 49
 50#[cfg(any(feature = "wayland", feature = "x11"))]
 51impl LinuxKeyboardMapper {
 52    pub(crate) fn new(group: Option<u32>) -> Self {
 53        let group = group.unwrap_or(0);
 54        let _ = XCB_CONNECTION
 55            .xkb_use_extension(XKB_X11_MIN_MAJOR_XKB_VERSION, XKB_X11_MIN_MINOR_XKB_VERSION)
 56            .unwrap()
 57            .reply()
 58            .unwrap();
 59        let xkb_context = xkbcommon::xkb::Context::new(xkbcommon::xkb::CONTEXT_NO_FLAGS);
 60        let xkb_device_id = xkbcommon::xkb::x11::get_core_keyboard_device_id(&*XCB_CONNECTION);
 61        let mut xkb_state = {
 62            let xkb_keymap = xkbcommon::xkb::x11::keymap_new_from_device(
 63                &xkb_context,
 64                &*XCB_CONNECTION,
 65                xkb_device_id,
 66                xkbcommon::xkb::KEYMAP_COMPILE_NO_FLAGS,
 67            );
 68            xkbcommon::xkb::x11::state_new_from_device(&xkb_keymap, &*XCB_CONNECTION, xkb_device_id)
 69        };
 70        xkb_state.update_mask(0, 0, 0, 0, 0, group);
 71
 72        let mut letters = HashMap::default();
 73        let mut code_to_key = HashMap::default();
 74        let mut code_to_shifted_key = HashMap::default();
 75        let mut inserted_letters = HashSet::default();
 76
 77        let keymap = xkb_state.get_keymap();
 78        let mut shifted_state = xkbcommon::xkb::State::new(&keymap);
 79        let shift_mod = keymap.mod_get_index(xkbcommon::xkb::MOD_NAME_SHIFT);
 80        let shift_mask = 1 << shift_mod;
 81        shifted_state.update_mask(shift_mask, 0, 0, 0, 0, group);
 82
 83        for scan_code in LinuxScanCodes::iter() {
 84            let keycode = Keycode::new(scan_code as u32);
 85
 86            let key = xkb_state.key_get_utf8(keycode);
 87            if !key.is_empty() {
 88                if key_is_a_letter(&key) {
 89                    letters.insert(keycode, key.clone());
 90                } else {
 91                    code_to_key.insert(keycode, key.clone());
 92                }
 93                inserted_letters.insert(key);
 94            } else {
 95                // keycode might be a dead key
 96                let keysym = xkb_state.key_get_one_sym(keycode);
 97                if let Some(key) = underlying_dead_key(keysym) {
 98                    code_to_key.insert(keycode, key.clone());
 99                    inserted_letters.insert(key);
100                }
101            }
102
103            let shifted_key = shifted_state.key_get_utf8(keycode);
104            if !shifted_key.is_empty() {
105                code_to_shifted_key.insert(keycode, shifted_key);
106            } else {
107                // keycode might be a dead key
108                let shifted_keysym = shifted_state.key_get_one_sym(keycode);
109                if let Some(shifted_key) = underlying_dead_key(shifted_keysym) {
110                    code_to_shifted_key.insert(keycode, shifted_key);
111                }
112            }
113        }
114        insert_letters_if_missing(&inserted_letters, &mut letters);
115
116        Self {
117            letters,
118            code_to_key,
119            code_to_shifted_key,
120        }
121    }
122
123    pub(crate) fn get_key(
124        &self,
125        keycode: Keycode,
126        modifiers: &mut crate::Modifiers,
127    ) -> Option<String> {
128        if let Some(key) = self.letters.get(&keycode) {
129            return Some(key.clone());
130        }
131        if modifiers.shift {
132            modifiers.shift = false;
133            self.code_to_shifted_key.get(&keycode).cloned()
134        } else {
135            self.code_to_key.get(&keycode).cloned()
136        }
137    }
138}
139
140#[cfg(any(feature = "wayland", feature = "x11"))]
141fn key_is_a_letter(key: &str) -> bool {
142    matches!(
143        key,
144        "a" | "b"
145            | "c"
146            | "d"
147            | "e"
148            | "f"
149            | "g"
150            | "h"
151            | "i"
152            | "j"
153            | "k"
154            | "l"
155            | "m"
156            | "n"
157            | "o"
158            | "p"
159            | "q"
160            | "r"
161            | "s"
162            | "t"
163            | "u"
164            | "v"
165            | "w"
166            | "x"
167            | "y"
168            | "z"
169    )
170}
171
172/**
173 * Returns which symbol the dead key represents
174 * <https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values#dead_keycodes_for_linux>
175 */
176#[cfg(any(feature = "wayland", feature = "x11"))]
177pub(crate) fn underlying_dead_key(keysym: Keysym) -> Option<String> {
178    match keysym {
179        Keysym::dead_grave => Some("`".to_owned()),
180        Keysym::dead_acute => Some("´".to_owned()),
181        Keysym::dead_circumflex => Some("^".to_owned()),
182        Keysym::dead_tilde => Some("~".to_owned()),
183        Keysym::dead_macron => Some("¯".to_owned()),
184        Keysym::dead_breve => Some("˘".to_owned()),
185        Keysym::dead_abovedot => Some("˙".to_owned()),
186        Keysym::dead_diaeresis => Some("¨".to_owned()),
187        Keysym::dead_abovering => Some("˚".to_owned()),
188        Keysym::dead_doubleacute => Some("˝".to_owned()),
189        Keysym::dead_caron => Some("ˇ".to_owned()),
190        Keysym::dead_cedilla => Some("¸".to_owned()),
191        Keysym::dead_ogonek => Some("˛".to_owned()),
192        Keysym::dead_iota => Some("ͅ".to_owned()),
193        Keysym::dead_voiced_sound => Some("".to_owned()),
194        Keysym::dead_semivoiced_sound => Some("".to_owned()),
195        Keysym::dead_belowdot => Some("̣̣".to_owned()),
196        Keysym::dead_hook => Some("̡".to_owned()),
197        Keysym::dead_horn => Some("̛".to_owned()),
198        Keysym::dead_stroke => Some("̶̶".to_owned()),
199        Keysym::dead_abovecomma => Some("̓̓".to_owned()),
200        Keysym::dead_abovereversedcomma => Some("ʽ".to_owned()),
201        Keysym::dead_doublegrave => Some("̏".to_owned()),
202        Keysym::dead_belowring => Some("˳".to_owned()),
203        Keysym::dead_belowmacron => Some("̱".to_owned()),
204        Keysym::dead_belowcircumflex => Some("".to_owned()),
205        Keysym::dead_belowtilde => Some("̰".to_owned()),
206        Keysym::dead_belowbreve => Some("̮".to_owned()),
207        Keysym::dead_belowdiaeresis => Some("̤".to_owned()),
208        Keysym::dead_invertedbreve => Some("̯".to_owned()),
209        Keysym::dead_belowcomma => Some("̦".to_owned()),
210        Keysym::dead_currency => None,
211        Keysym::dead_lowline => None,
212        Keysym::dead_aboveverticalline => None,
213        Keysym::dead_belowverticalline => None,
214        Keysym::dead_longsolidusoverlay => None,
215        Keysym::dead_a => None,
216        Keysym::dead_A => None,
217        Keysym::dead_e => None,
218        Keysym::dead_E => None,
219        Keysym::dead_i => None,
220        Keysym::dead_I => None,
221        Keysym::dead_o => None,
222        Keysym::dead_O => None,
223        Keysym::dead_u => None,
224        Keysym::dead_U => None,
225        Keysym::dead_small_schwa => Some("ə".to_owned()),
226        Keysym::dead_capital_schwa => Some("Ə".to_owned()),
227        Keysym::dead_greek => None,
228        _ => None,
229    }
230}
231
232#[cfg(any(feature = "wayland", feature = "x11"))]
233fn insert_letters_if_missing(inserted: &HashSet<String>, letters: &mut HashMap<Keycode, String>) {
234    for scan_code in LinuxScanCodes::LETTERS.iter() {
235        let keycode = Keycode::new(*scan_code as u32);
236        let key = scan_code.to_str();
237        if !inserted.contains(key) {
238            letters.insert(keycode, key.to_owned());
239        }
240    }
241}
242
243#[cfg(any(feature = "wayland", feature = "x11"))]
244#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumIter)]
245enum LinuxScanCodes {
246    A = 0x0026,
247    B = 0x0038,
248    C = 0x0036,
249    D = 0x0028,
250    E = 0x001a,
251    F = 0x0029,
252    G = 0x002a,
253    H = 0x002b,
254    I = 0x001f,
255    J = 0x002c,
256    K = 0x002d,
257    L = 0x002e,
258    M = 0x003a,
259    N = 0x0039,
260    O = 0x0020,
261    P = 0x0021,
262    Q = 0x0018,
263    R = 0x001b,
264    S = 0x0027,
265    T = 0x001c,
266    U = 0x001e,
267    V = 0x0037,
268    W = 0x0019,
269    X = 0x0035,
270    Y = 0x001d,
271    Z = 0x0034,
272    Digit0 = 0x0013,
273    Digit1 = 0x000a,
274    Digit2 = 0x000b,
275    Digit3 = 0x000c,
276    Digit4 = 0x000d,
277    Digit5 = 0x000e,
278    Digit6 = 0x000f,
279    Digit7 = 0x0010,
280    Digit8 = 0x0011,
281    Digit9 = 0x0012,
282    Backquote = 0x0031,
283    Minus = 0x0014,
284    Equal = 0x0015,
285    LeftBracket = 0x0022,
286    RightBracket = 0x0023,
287    Backslash = 0x0033,
288    Semicolon = 0x002f,
289    Quote = 0x0030,
290    Comma = 0x003b,
291    Period = 0x003c,
292    Slash = 0x003d,
293    // This key is typically located near LeftShift key, varies on international keyboards: Dan: <> Dutch: ][ Ger: <> UK: \|
294    IntlBackslash = 0x005e,
295    // Used for Brazilian /? and Japanese _ 'ro'.
296    IntlRo = 0x0061,
297}
298
299#[cfg(any(feature = "wayland", feature = "x11"))]
300impl LinuxScanCodes {
301    const LETTERS: &'static [LinuxScanCodes] = &[
302        LinuxScanCodes::A,
303        LinuxScanCodes::B,
304        LinuxScanCodes::C,
305        LinuxScanCodes::D,
306        LinuxScanCodes::E,
307        LinuxScanCodes::F,
308        LinuxScanCodes::G,
309        LinuxScanCodes::H,
310        LinuxScanCodes::I,
311        LinuxScanCodes::J,
312        LinuxScanCodes::K,
313        LinuxScanCodes::L,
314        LinuxScanCodes::M,
315        LinuxScanCodes::N,
316        LinuxScanCodes::O,
317        LinuxScanCodes::P,
318        LinuxScanCodes::Q,
319        LinuxScanCodes::R,
320        LinuxScanCodes::S,
321        LinuxScanCodes::T,
322        LinuxScanCodes::U,
323        LinuxScanCodes::V,
324        LinuxScanCodes::W,
325        LinuxScanCodes::X,
326        LinuxScanCodes::Y,
327        LinuxScanCodes::Z,
328    ];
329
330    fn to_str(&self) -> &str {
331        match self {
332            LinuxScanCodes::A => "a",
333            LinuxScanCodes::B => "b",
334            LinuxScanCodes::C => "c",
335            LinuxScanCodes::D => "d",
336            LinuxScanCodes::E => "e",
337            LinuxScanCodes::F => "f",
338            LinuxScanCodes::G => "g",
339            LinuxScanCodes::H => "h",
340            LinuxScanCodes::I => "i",
341            LinuxScanCodes::J => "j",
342            LinuxScanCodes::K => "k",
343            LinuxScanCodes::L => "l",
344            LinuxScanCodes::M => "m",
345            LinuxScanCodes::N => "n",
346            LinuxScanCodes::O => "o",
347            LinuxScanCodes::P => "p",
348            LinuxScanCodes::Q => "q",
349            LinuxScanCodes::R => "r",
350            LinuxScanCodes::S => "s",
351            LinuxScanCodes::T => "t",
352            LinuxScanCodes::U => "u",
353            LinuxScanCodes::V => "v",
354            LinuxScanCodes::W => "w",
355            LinuxScanCodes::X => "x",
356            LinuxScanCodes::Y => "y",
357            LinuxScanCodes::Z => "z",
358            LinuxScanCodes::Digit0 => "0",
359            LinuxScanCodes::Digit1 => "1",
360            LinuxScanCodes::Digit2 => "2",
361            LinuxScanCodes::Digit3 => "3",
362            LinuxScanCodes::Digit4 => "4",
363            LinuxScanCodes::Digit5 => "5",
364            LinuxScanCodes::Digit6 => "6",
365            LinuxScanCodes::Digit7 => "7",
366            LinuxScanCodes::Digit8 => "8",
367            LinuxScanCodes::Digit9 => "9",
368            LinuxScanCodes::Backquote => "`",
369            LinuxScanCodes::Minus => "-",
370            LinuxScanCodes::Equal => "=",
371            LinuxScanCodes::LeftBracket => "[",
372            LinuxScanCodes::RightBracket => "]",
373            LinuxScanCodes::Backslash => "\\",
374            LinuxScanCodes::Semicolon => ";",
375            LinuxScanCodes::Quote => "'",
376            LinuxScanCodes::Comma => ",",
377            LinuxScanCodes::Period => ".",
378            LinuxScanCodes::Slash => "/",
379            LinuxScanCodes::IntlBackslash => "unknown",
380            LinuxScanCodes::IntlRo => "unknown",
381        }
382    }
383
384    #[cfg(test)]
385    fn to_shifted(&self) -> &str {
386        match self {
387            LinuxScanCodes::A => "a",
388            LinuxScanCodes::B => "b",
389            LinuxScanCodes::C => "c",
390            LinuxScanCodes::D => "d",
391            LinuxScanCodes::E => "e",
392            LinuxScanCodes::F => "f",
393            LinuxScanCodes::G => "g",
394            LinuxScanCodes::H => "h",
395            LinuxScanCodes::I => "i",
396            LinuxScanCodes::J => "j",
397            LinuxScanCodes::K => "k",
398            LinuxScanCodes::L => "l",
399            LinuxScanCodes::M => "m",
400            LinuxScanCodes::N => "n",
401            LinuxScanCodes::O => "o",
402            LinuxScanCodes::P => "p",
403            LinuxScanCodes::Q => "q",
404            LinuxScanCodes::R => "r",
405            LinuxScanCodes::S => "s",
406            LinuxScanCodes::T => "t",
407            LinuxScanCodes::U => "u",
408            LinuxScanCodes::V => "v",
409            LinuxScanCodes::W => "w",
410            LinuxScanCodes::X => "x",
411            LinuxScanCodes::Y => "y",
412            LinuxScanCodes::Z => "z",
413            LinuxScanCodes::Digit0 => ")",
414            LinuxScanCodes::Digit1 => "!",
415            LinuxScanCodes::Digit2 => "@",
416            LinuxScanCodes::Digit3 => "#",
417            LinuxScanCodes::Digit4 => "$",
418            LinuxScanCodes::Digit5 => "%",
419            LinuxScanCodes::Digit6 => "^",
420            LinuxScanCodes::Digit7 => "&",
421            LinuxScanCodes::Digit8 => "*",
422            LinuxScanCodes::Digit9 => "(",
423            LinuxScanCodes::Backquote => "~",
424            LinuxScanCodes::Minus => "_",
425            LinuxScanCodes::Equal => "+",
426            LinuxScanCodes::LeftBracket => "{",
427            LinuxScanCodes::RightBracket => "}",
428            LinuxScanCodes::Backslash => "|",
429            LinuxScanCodes::Semicolon => ":",
430            LinuxScanCodes::Quote => "\"",
431            LinuxScanCodes::Comma => "<",
432            LinuxScanCodes::Period => ">",
433            LinuxScanCodes::Slash => "?",
434            LinuxScanCodes::IntlBackslash => "unknown",
435            LinuxScanCodes::IntlRo => "unknown",
436        }
437    }
438}
439
440#[cfg(all(test, any(feature = "wayland", feature = "x11")))]
441mod tests {
442    use strum::IntoEnumIterator;
443
444    use crate::platform::linux::keyboard::LinuxScanCodes;
445
446    use super::LinuxKeyboardMapper;
447
448    #[test]
449    fn test_us_layout_mapper() {
450        let mapper = LinuxKeyboardMapper::new(None);
451        for scan_code in super::LinuxScanCodes::iter() {
452            if scan_code == LinuxScanCodes::IntlBackslash || scan_code == LinuxScanCodes::IntlRo {
453                continue;
454            }
455            let keycode = xkbcommon::xkb::Keycode::new(scan_code as u32);
456            let key = mapper
457                .get_key(keycode, &mut crate::Modifiers::default())
458                .unwrap();
459            assert_eq!(key.as_str(), scan_code.to_str());
460
461            let shifted_key = mapper
462                .get_key(
463                    keycode,
464                    &mut crate::Modifiers {
465                        shift: true,
466                        ..Default::default()
467                    },
468                )
469                .unwrap();
470            assert_eq!(shifted_key.as_str(), scan_code.to_shifted());
471        }
472    }
473}