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(base_group: u32, latched_group: u32, locked_group: 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 xkb_state.update_mask(0, 0, 0, base_group, latched_group, locked_group);
70
71 let mut letters = HashMap::default();
72 let mut code_to_key = HashMap::default();
73 let mut code_to_shifted_key = HashMap::default();
74 let mut inserted_letters = HashSet::default();
75
76 let keymap = xkb_state.get_keymap();
77 let mut shifted_state = xkbcommon::xkb::State::new(&keymap);
78 let shift_mod = keymap.mod_get_index(xkbcommon::xkb::MOD_NAME_SHIFT);
79 let shift_mask = 1 << shift_mod;
80 shifted_state.update_mask(shift_mask, 0, 0, base_group, latched_group, locked_group);
81
82 for scan_code in LinuxScanCodes::iter() {
83 let keycode = Keycode::new(scan_code as u32);
84
85 let key = xkb_state.key_get_utf8(keycode);
86 if !key.is_empty() {
87 if key_is_a_letter(&key) {
88 letters.insert(keycode, key.clone());
89 } else {
90 code_to_key.insert(keycode, key.clone());
91 }
92 inserted_letters.insert(key);
93 } else {
94 // keycode might be a dead key
95 let keysym = xkb_state.key_get_one_sym(keycode);
96 if let Some(key) = underlying_dead_key(keysym) {
97 code_to_key.insert(keycode, key.clone());
98 inserted_letters.insert(key);
99 }
100 }
101
102 let shifted_key = shifted_state.key_get_utf8(keycode);
103 if !shifted_key.is_empty() {
104 code_to_shifted_key.insert(keycode, shifted_key);
105 } else {
106 // keycode might be a dead key
107 let shifted_keysym = shifted_state.key_get_one_sym(keycode);
108 if let Some(shifted_key) = underlying_dead_key(shifted_keysym) {
109 code_to_shifted_key.insert(keycode, shifted_key);
110 }
111 }
112 }
113 insert_letters_if_missing(&inserted_letters, &mut letters);
114
115 Self {
116 letters,
117 code_to_key,
118 code_to_shifted_key,
119 }
120 }
121
122 pub(crate) fn get_key(
123 &self,
124 keycode: Keycode,
125 modifiers: &mut crate::Modifiers,
126 ) -> Option<String> {
127 if let Some(key) = self.letters.get(&keycode) {
128 return Some(key.clone());
129 }
130 if modifiers.shift {
131 modifiers.shift = false;
132 self.code_to_shifted_key.get(&keycode).cloned()
133 } else {
134 self.code_to_key.get(&keycode).cloned()
135 }
136 }
137}
138
139#[cfg(any(feature = "wayland", feature = "x11"))]
140fn key_is_a_letter(key: &str) -> bool {
141 matches!(
142 key,
143 "a" | "b"
144 | "c"
145 | "d"
146 | "e"
147 | "f"
148 | "g"
149 | "h"
150 | "i"
151 | "j"
152 | "k"
153 | "l"
154 | "m"
155 | "n"
156 | "o"
157 | "p"
158 | "q"
159 | "r"
160 | "s"
161 | "t"
162 | "u"
163 | "v"
164 | "w"
165 | "x"
166 | "y"
167 | "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 strum::IntoEnumIterator;
442
443 use crate::platform::linux::keyboard::LinuxScanCodes;
444
445 use super::LinuxKeyboardMapper;
446
447 #[test]
448 fn test_us_layout_mapper() {
449 let mapper = LinuxKeyboardMapper::new(0, 0, 0);
450 for scan_code in super::LinuxScanCodes::iter() {
451 if scan_code == LinuxScanCodes::IntlBackslash || scan_code == LinuxScanCodes::IntlRo {
452 continue;
453 }
454 let keycode = xkbcommon::xkb::Keycode::new(scan_code as u32);
455 let key = mapper
456 .get_key(keycode, &mut crate::Modifiers::default())
457 .unwrap();
458 assert_eq!(key.as_str(), scan_code.to_str());
459
460 let shifted_key = mapper
461 .get_key(
462 keycode,
463 &mut crate::Modifiers {
464 shift: true,
465 ..Default::default()
466 },
467 )
468 .unwrap();
469 assert_eq!(shifted_key.as_str(), scan_code.to_shifted());
470 }
471 }
472}