keyboard.rs

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