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