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