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