xkb_evdev_trans 0.1.2

Provides information about either the current or a specific keyboard layout from xkb and create maps between low level key identifiers (EVDEV/XKB) and the symbols xkb maps them to.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
// SPDX-FileCopyrightText: 2025 Arkadiusz Guzinski <kermit@aguzinski.de>
//
// SPDX-License-Identifier: MIT

//! This crate offers functions to get information about either the current or a specific keyboard
//! layout from xkb, as well as to create maps between low level key identifiers (EVDEV/XKB) and the
//! symbols xkb maps them to.
//! 
//! It is meant to be used in software that remaps input events or visualizes/configures keyboard
//! layouts on Linux.
//!

extern crate alloc;
extern crate core;
pub mod map_builder;

//pub use map_builder::MapBuilder;

// pub use xkb_evdev_trans::*;

// pub mod xkb_evdev_trans {
use std::collections::BTreeMap;
use std::error::Error;
use std::ffi::{c_char, CStr, CString, NulError};
use std::fmt;
use std::fmt::Formatter;
use std::ptr::null;
use xkbcommon_sys::*;


/// A modifier from the list of modifiers.
    pub struct Mod {
        pub index: xkb_mod_index_t,
        // pub mask: xkb_mod_mask_t, 
        pub keycode: xkb_keycode_t,
        pub name: String,
    }

    // easier handling of c-strings where the expected parameter might be nullptr
    struct OptCString {
        value: Option<CString>,
    }

    impl OptCString {
        fn as_ptr(&self) -> *const c_char {
            match &self.value {
                None => {null()}
                Some(v) => {v.as_ptr()}
            }
        }

        /*fn from_str(value: &str) -> Result<Self, NulError> {
            Ok(Self{value: Some(CString::new(value)?)})
        }*/

        fn from_opt_str(value: Option<&str>) -> Result<Self, NulError> {
            Ok(Self{value:
             match value {
                 None => None,
                 Some(v) => Some(CString::new(v)?)
             }})
        }
    }

    /// Description of a hardware key and what it's mapped to.
    #[derive(Clone)]
    pub struct Key {
        /// Code XKB uses for the hardware key 
        pub keycode: u32,
        /// Name of the hardware key
        pub keyname: String,
        /// Map of symbols mapped to this key by modifier level
        pub symbols: BTreeMap<xkb_level_index_t, Symbol>,
        /// Number of different layout associations for that key
        pub num_layouts: u32,
    }

    /// An associated symbol, e.g. the character to be typed or a special key like a modifier.
    #[derive(Clone)]
    pub struct Symbol {
        /// Symbol codes the keymap associates with that key
        pub keysyms: Vec<u32>,
        /// Key as unicode symbol, e.g. '&'
        pub unicode: Option<char>,
        /// Key as symbol name, e.g. "ampersand"
        pub symbol: Option<String>,
        /// Default symbol description. 
        /// 
        /// In most cases this is equal to `unicode` if the character is 
        /// visible (as in "fills pixels" - space does not count as visible here) and equal to 
        /// `symbol` otherwise. There are a few exceptions such as the keys as the numpad, e.g. the
        /// minus there will display as *KP_Subtract* instead of *-* or *minus*.
        pub display: String,
        /// Whether character is visible, meaning non-zero-width -- so here space counts as visible.
        pub visible: bool,
    }

    impl Symbol {
        fn new(ch: char, keysyms: Vec<u32>, num_layouts: u32) -> Symbol {
            // visible (as to the user) characters should be displayed as unicode-representations,
            // while non-visible characters use symbol names
            // for KP_.. we make exceptions to distinguish them from non-keypad keys that produce
            // the same symbol
            let symbol = Self::resolve_keysyms(&keysyms);
            // KP_*             0xFF80..=0xFFB9
            let representation: (Option<String>, bool) = if keysyms.iter()
              .any(|val| {
                  #[allow(non_upper_case_globals)]
                  match *val {XKB_KEY_KP_Space | XKB_KEY_Tab | XKB_KEY_KP_Enter |
                  XKB_KEY_KP_F1..=XKB_KEY_KP_Delete | XKB_KEY_KP_Equal |
                  XKB_KEY_KP_Multiply..=XKB_KEY_KP_9 => true,
                      _ => false
                  }
              }) {
                (Some(String::from(symbol.as_ref().unwrap_or(&format!("KP_{}", ch)))), true)
            } else {
                match ch as u32 {
                    // White_Space
                    0x0020 | 0x0085 | 0x00A0 | 0x1680 | 0x2000..=0x200A | 0x2028 | 0x2029 | 0x202F | 0x205F | 0x3000
                    => (Self::resolve_keysyms(&keysyms), true),
                    // Control characters & Zero Width
                    // Some control characters are not listed as such in xkb docs. Why??
                    // Those are: 0x0-0x8, 0xe-0x1f, 0x7f-0x9f. Also 0x2028-0x2029, which is White_Space
                    0x0000..=0x001F | 0x007F..=0x009F |
                    0x00AD | 0x034F | 0x061C | 0x115F..=0x1160 | 0x17B4..=0x17B5 | 0x180B..=0x180F | 0x200B..=0x200F |
                    0x202A..=0x202E | 0x2060..=0x206F | 0x3164 | 0xFE00..=0xFE0F | 0xFEFF | 0xFFA0 | 0xFFF0..=0xFFF8 |
                    0x1BCA0..=0x1BCA3 | 0x1D173..=0x1D17A | 0xE0000..=0xE0FFF
                    => (Self::resolve_keysyms(&keysyms), false),
                    _ => (Some(ch.to_string()), true)
                }
            };
            Symbol {
                keysyms,
                unicode: Some(ch),
                symbol,
                display: representation.0.unwrap_or("<No Keysym>".to_string()),
                visible: representation.1,
            }
        }

        fn resolve_keysyms(keysyms: &Vec<u32>) -> Option<String> {
            let mut symbols: Vec<String> = Vec::new();
            let mut buf: Vec<u8> = Vec::with_capacity(32);
            buf.resize(32, 0);

            if keysyms.is_empty() {
                return None;
            }

            for keysym in keysyms {
                unsafe {
                    let n = xkb_keysym_get_name(*keysym, buf.as_mut_ptr() as _, buf.len() as _);
                    if n > 0 {
                        let size = (if n > 32 { 32 } else { n }) as usize;
                        symbols.push(CString::from_vec_unchecked(buf[0..(size)].to_vec()).into_string().unwrap_or_default());
                    }
                }
            }

            Some(match symbols.len() {
                0 => format!("Resolution Error for {:#10x}", keysyms[0]),
                1 => format!("{}", symbols[0].to_owned()),
                _ => format!("({})", symbols.join("|"))
            })
        }

    }

    impl Key {
        fn new_unicode(keycode: u32, keyname: String, symbols: BTreeMap<xkb_level_index_t, Symbol>, num_layouts: u32) -> Key {
            Key {
                keycode,
                keyname,
                symbols,
                num_layouts,
            }
        }


        fn new_mod(keycode: u32, keyname: String, keysyms: Vec<u32>, num_layouts: u32) -> Key {
            let symbol = Symbol::resolve_keysyms(&keysyms);
            let display = match &symbol {
                Some(s) => s.clone(),
                None => "No Keysym".to_string()
            };
            let mut symbols = BTreeMap::new();
            symbols.insert(0, Symbol{keysyms, unicode: None, symbol, display, visible: false});
            Key { keycode, keyname, symbols, num_layouts }
        }

        /// Returns the name of the symbol the key maps to, when no modifier is active.
        pub fn symbol_name(&self) -> Option<String> {
            self.symbols.first_key_value()?.1.symbol.clone()
        }

        /// Returns the list of keysyms the key maps to, when no modifier is active.
        pub fn keysyms(&self) -> Vec<u32> {
            if let Some(s) = self.symbols.first_key_value() {
                s.1.keysyms.clone()
            } else { Vec::new() }
        }
        
        pub fn display(&self) -> String {
            if let Some(s) = self.symbols.first_key_value() {
                s.1.display.clone()
            } else { "".to_string() }
        }


        /// Returns the keycode evdev uses for this key.
        #[inline]
        pub fn evdev_code(&self) -> u16 {
            // yes, a value of 8 seems to be the whole difference...
            // todo find reference code from X11 and put link here
            self.keycode as u16 - 8
        }

        /// Returns the unicode character the key types when no modifier is active, or None if no visible character is produced.
        #[inline]
        pub fn visible_unicode(&self) -> Option<char> {
            let sym = self.symbols.first_key_value()?.1;
            if sym.visible {
                sym.unicode
            } else { None }
        }
    }

    /// Structure containing all data queried from XKB about a layout.
    /// If multiple layouts are defined for switching, keys will list those of the first layout.
    /// Will contain all keys - even those not present on the current hardware devices.
    pub struct Keymap {
        /// Names of the configured Layouts. 
        pub layouts: Vec<String>,
        /// List of modifiers.
        pub mods: Vec<Mod>,
        /// List of defined keys. 
        pub keys: Vec<Key>,
    }

    impl Keymap {
        /// Will load a Keymap as specified by parameters. 
        /// 
        /// See the libxkbcommon docs for further information on the first 5 [parameters](https://xkbcommon.org/doc/current/xkb-intro.html#RMLVO-intro).
        /// 
        /// If `all_levels` is true the resulting Keymap will include the full layout. If it is set
        /// to false, it will include only the first layer (no modifiers pressed), which is usually
        /// enough for key remapping.
        ///
        ///
        /// ```
        /// // Load german layout without dead keys
        /// let keymap = xkb_evdev_trans::Keymap::from_rmlvo(
        ///   Some("evdev"), Some("pc105"), Some("de"),
        ///   Some("nodeadkeys"), None, false
        /// ).unwrap();
        /// ```
        ///
        /// # Errors
        /// Will return an error if a supplied parameter contains a \\0 byte or the keymap could not
        /// be loaded.
        pub fn from_rmlvo(
            rules: Option<&str>, // kbd type
            model: Option<&str>, // pc105
            layout: Option<&str>, // pd
            variant: Option<&str>, // dvorak
            options: Option<&str>, // caps:swapescape
            all_levels: bool
        ) -> Result<Keymap, KMError> {
            let context;
            let keymap;
            unsafe {
                context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
                if context.is_null() {
                    return Err(KMError{message: "xkb_context_new() returned null".to_string()});
                }
                let rules = OptCString::from_opt_str(rules)?;
                // else {
                    // return Err(KMError { message: "rules: invalid value".to_string()})
                // };
                let model = OptCString::from_opt_str(model)?;
                let layout = OptCString::from_opt_str(layout)?;
                let variant = OptCString::from_opt_str(variant)?;
                let options = OptCString::from_opt_str(options)?;

                let names = xkb_rule_names {
                    rules: rules.as_ptr(),
                    model: model.as_ptr(),
                    layout: layout.as_ptr(),
                    variant: variant.as_ptr(),
                    options: options.as_ptr(),
                };
                keymap = xkb_keymap_new_from_names(context, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);
                if keymap.is_null() {
                    return Err(KMError{message: "xkb_keymap_new_from_names() returned null".to_string()});
                }
            };
            Self::init_data(context, keymap, all_levels)
        }


        /// Will load the Keymap for the current keyboard layout. If multiple layouts are configured
        /// for switching, keycodes will correspond to the first layout.
        ///
        /// If `all_levels` is true the resulting Keymap will include the full layout. If it is set
        /// to false, it will include only the first layer (no modifiers pressed), which is usually
        /// enough for key remapping.
        ///
        /// Note: This currently queries XCB to determine which layout is loaded. While it has been
        /// tested successfully on Wayland, it might have only worked because XWayland is available.
        /// 
        /// # Errors
        /// Will return an error if the keymap could not be loaded.
        pub fn current_from_xcb(all_levels: bool) -> Result<Keymap, KMError> {
            // xcb works on both X11 and Wayland. Does xcb start XWayland?
            // todo find out if there is a reason to use wl_keyboard_keymap on Wayland?
            let context;
            let keymap;
            unsafe {
                context = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
                let conn = match xcb::Connection::connect(None) {
                    Ok((c, _)) => c,
                    Err(_) => return Err(KMError { message: "Error creating XCB connection".to_string() })
                };
                match conn.has_error() {
                    Ok(_) => {}
                    Err(e) => println!("{}", e)
                }

                Self::setup_xkb_extension(&conn)?;

                let mut dev_id = xkb_x11_get_core_keyboard_device_id(conn.get_raw_conn() as _);
                if dev_id == -1 {
                    dev_id = 1;
                    // return Err(KMError{message: "Could not get device id from X11".to_string()})
                }
                keymap = xkb_x11_keymap_new_from_device(context, conn.get_raw_conn() as _, dev_id, XKB_KEYMAP_COMPILE_NO_FLAGS);
            };
            Self::init_data(context, keymap, all_levels)
        }
        
        // loads data from xkb_keymap. 
        // context is not accessed, but needs to be alive (not freed) for the function to work.
        fn init_data(context: *mut xkb_context, keymap: *mut xkb_keymap, all_levels: bool) -> Result<Keymap, KMError> {
            let mut layouts: Vec<String> = Vec::new();
            unsafe {
                let num_la = xkb_keymap_num_layouts(keymap);
                if num_la < 1 {
                    return Err(KMError{message: "Number of Layouts is 0".to_string()});
                }
                for idx in 0..num_la {
                    let name = CStr::from_ptr(xkb_keymap_layout_get_name(keymap, idx)).to_str().unwrap_or_default().to_string();
                    layouts.push(name);
                }
            }

            let mut mods: Vec<Mod> = Vec::new();
            unsafe {
                let num_mod = xkb_keymap_num_mods(keymap);
                for idx in 0..num_mod {
                    let name = CStr::from_ptr(xkb_keymap_mod_get_name(keymap, idx)).to_str().unwrap_or_default().to_string();
                    // let mask = xkb_keymap_mod_get_mask(keymap, idx); todo seems to be unsupported by the xkbcommon_sys crate
                    mods.push(Mod { index: idx, name, keycode: idx })
                }
            }

            let mut keys: Vec<Key> = Vec::new();
            unsafe {
                let min_keycode = xkb_keymap_min_keycode(keymap);
                let max_keycode = xkb_keymap_max_keycode(keymap);

                // Documentation tells us buf should be at least 5 bytes long (4 bytes unicode + \0),
                // but the function can return -1 if it's too small. Is it possible that more can be
                // returned? Let's rather err on the side of caution and set it to 64.
                let mut buf: Vec<u8> = Vec::with_capacity(64);
                buf.resize(64, 0);

                // TODO What is the maximum number of keysyms that can be returned? And what is the
                // meaning of those extra keysyms?
                let mut sym_buf: Vec<*const u32> = Vec::with_capacity(64);
                sym_buf.resize(64, null());

                let layout = 0;
                // todo there is a function xkb_keymap_key_for_each() which might be more efficient,
                // but it expects a function pointer. How to do this safely as FFI?
                for code in min_keycode..=max_keycode {
                    let cs = xkb_keymap_key_get_name(keymap, code);
                    if cs != null() {
                        let hw_name = CStr::from_ptr(cs).to_str().unwrap_or_default();
                        let num_layouts = xkb_keymap_num_layouts_for_key(keymap, code);
                        if num_layouts == 0 {
                            continue;
                        }
                        let num_levels = if all_levels {xkb_keymap_num_levels_for_key(keymap, code, layout)} else {1};
                        let mut symbols = BTreeMap::new();
                        for level in 0..num_levels {
                            let sym_count = xkb_keymap_key_get_syms_by_level(keymap, code, 0, level, sym_buf.as_mut_ptr() as _) as usize;
                            if sym_count == 0 {continue;}
                            let mut keysyms: Vec<u32> = Vec::new();
                            let sym = *sym_buf[0] as xkb_keysym_t;
                            for i in 0..sym_count {
                                keysyms.push(*sym_buf[i]);
                            }
                            if sym_count > 1 {
                                println!("{sym_count} symbols for key {hw_name}: {keysyms:?}");
                            }
                            let n = xkb_keysym_to_utf8(sym, buf.as_mut_ptr() as _, buf.len());
                            if n > 0 {
                                let unicode = CString::from_vec_unchecked(buf[0..(n as usize)].to_vec()).into_string().unwrap_or_default();
                                let ch = unicode.chars().nth(0).unwrap();
                                let sym = Symbol::new(ch, keysyms, num_layouts);
                                symbols.insert(level, sym);
                            } else {
                                keys.push(Key::new_mod(code, hw_name.to_string(), keysyms, num_layouts));
                            };
                        }
                        if !symbols.is_empty() {
                            keys.push(Key::new_unicode(code, hw_name.to_string(), symbols, num_layouts));
                        }
                    }
                }
            }

            Ok(Keymap { layouts, mods, keys })
        }

        fn setup_xkb_extension(conn: &xcb::Connection) -> Result<(), KMError> {
            let mut major_ver_out: u16 = 0;
            let mut minor_ver_out: u16 = 0;
            let mut base_event_out: u8 = 0;
            let mut base_error_out: u8 = 0;

            unsafe {
                let ret = xkb_x11_setup_xkb_extension(conn.get_raw_conn() as _,
                                                      XKB_X11_MIN_MAJOR_XKB_VERSION.try_into().unwrap(),
                                                      XKB_X11_MIN_MINOR_XKB_VERSION.try_into().unwrap(),
                                                      XKB_X11_SETUP_XKB_EXTENSION_NO_FLAGS,
                                                      &mut major_ver_out, &mut minor_ver_out,
                                                      &mut base_event_out, &mut base_error_out);
                if ret != 1 {
                    return Err(KMError { message: "Error setting up xkb extension".to_string() });
                }
            }
            Ok(())
        }
    }


    /// Simple Error type, which currently only contains a message.
    #[derive(Debug)]
    pub struct KMError {
        message: String,
    }

    impl Error for KMError {}

    impl fmt::Display for KMError {
        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.message)
        }
    }

    impl From<NulError> for KMError {
        fn from(e: NulError) -> Self {
            KMError{ message: e.to_string() }
        }
    }
// }

#[cfg(test)]
mod tests {
    use crate::Keymap;
    use crate::map_builder::{BuildMaps, Fill, MapBuilder, SymbolType};

    #[test]
    fn load_keymap() {
        let keymap = Keymap::from_rmlvo(
            Some("evdev"), Some("pc105"), Some("us"), Some("dvp"), Some("caps:swapescape"), true
        ).unwrap();
        let esc = keymap.keys[0].clone();
        assert_eq!(esc.evdev_code(), 1);
        assert_eq!(esc.symbol_name(), Some("Caps_Lock".to_string()));
    }

    #[test]
    fn load_invalid_keymap() {
        assert!(Keymap::from_rmlvo(
            Some("evdev"), Some("pc105"), Some("this_should_not_exist"), None, None, false
        ).is_err())
    }

    #[test]
    fn stuff_is_public_enough() {
        // no functionality, just tests if everything is sufficiently available
        let keymap = Keymap::current_from_xcb(true).unwrap();
        let (_to, _from) = MapBuilder::default()
          .code_evdev()
          .symbol(SymbolType::SymbolDisplay)
          .fill(Fill::Evdev(true))
          .build(&keymap, BuildMaps::Both);

        let (_to, _from) = MapBuilder::default()
          .code_xkb()
          .symbol_unicode()
          .replace_symbol_by_function(|x|{x})
          .build(&keymap, BuildMaps::Both);

        let (_to, _from) = MapBuilder::default()
          .code_xkb_hw()
          .symbol_codes()
          .build(&keymap, BuildMaps::Both);
    }
}