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