use crate::event::{Key, Mods};
use crate::x11::{dlclose, dlopen, key, library, symbol};
use std::ffi::{CStr, CString, c_char, c_int, c_ulong, c_void};
use std::time::Duration;
library!(Xkb, ["libxkbcommon.so.0", "libxkbcommon.so"], {
fn xkb_context_new(c_int) -> *mut c_void;
fn xkb_context_unref(*mut c_void);
fn xkb_keymap_new_from_string(*mut c_void, *const c_char, c_int, c_int) -> *mut c_void;
fn xkb_keymap_unref(*mut c_void);
fn xkb_keymap_key_repeats(*mut c_void, u32) -> c_int;
fn xkb_state_new(*mut c_void) -> *mut c_void;
fn xkb_state_unref(*mut c_void);
fn xkb_state_update_mask(*mut c_void, u32, u32, u32, u32, u32, u32) -> c_int;
fn xkb_state_key_get_one_sym(*mut c_void, u32) -> u32;
fn xkb_state_key_get_utf8(*mut c_void, u32, *mut c_char, usize) -> c_int;
fn xkb_state_mod_name_is_active(*mut c_void, *const c_char, c_int) -> c_int;
fn xkb_compose_table_new_from_locale(*mut c_void, *const c_char, c_int) -> *mut c_void;
fn xkb_compose_table_unref(*mut c_void);
fn xkb_compose_state_new(*mut c_void, c_int) -> *mut c_void;
fn xkb_compose_state_unref(*mut c_void);
fn xkb_compose_state_feed(*mut c_void, u32) -> c_int;
fn xkb_compose_state_get_status(*mut c_void) -> c_int;
fn xkb_compose_state_get_utf8(*mut c_void, *mut c_char, usize) -> c_int;
fn xkb_compose_state_reset(*mut c_void);
});
const COMPOSING: c_int = 1;
const COMPOSED: c_int = 2;
const CANCELLED: c_int = 3;
const IN_EFFECT: c_int = 1 << 3;
pub(crate) struct Keyboard {
xkb: Xkb,
context: *mut c_void,
map: *mut c_void,
state: *mut c_void,
table: *mut c_void,
composing: *mut c_void,
pub(crate) repeat: Option<(Duration, Duration)>,
}
fn language() -> CString {
let said = ["LC_ALL", "LC_CTYPE", "LANG"].into_iter().find_map(|name| std::env::var(name).ok().filter(|value| !value.is_empty()));
CString::new(said.unwrap_or_else(|| "C".into())).unwrap_or_default()
}
impl Keyboard {
pub(crate) fn new() -> Option<Self> {
let xkb = Xkb::open()?;
unsafe {
let context = (xkb.xkb_context_new)(0);
if context.is_null() {
return None;
}
let table = (xkb.xkb_compose_table_new_from_locale)(context, language().as_ptr(), 0);
let composing = if table.is_null() { std::ptr::null_mut() } else { (xkb.xkb_compose_state_new)(table, 0) };
let repeat = Some((Duration::from_millis(600), Duration::from_millis(40)));
Some(Keyboard { xkb, context, map: std::ptr::null_mut(), state: std::ptr::null_mut(), table, composing, repeat })
}
}
pub(crate) fn take_map(&mut self, text: &[u8]) -> bool {
let text = CString::new(text.split(|byte| *byte == 0).next().unwrap_or_default()).unwrap_or_default();
let map = unsafe { (self.xkb.xkb_keymap_new_from_string)(self.context, text.as_ptr(), 1, 0) };
self.with_map(map)
}
#[cfg(test)]
pub(crate) fn named(layout: &str) -> Option<Self> {
let mut keyboard = Keyboard::new()?;
let map = format!(
"xkb_keymap {{ xkb_keycodes {{ include \"evdev+aliases(qwerty)\" }}; xkb_types {{ include \"complete\" }}; xkb_compat {{ include \"complete\" }}; xkb_symbols {{ include \"pc+{layout}+inet(evdev)\" }}; }};"
);
keyboard.take_map(map.as_bytes()).then_some(keyboard)
}
fn with_map(&mut self, map: *mut c_void) -> bool {
if map.is_null() {
return false;
}
unsafe {
self.drop_map();
(self.map, self.state) = (map, (self.xkb.xkb_state_new)(map));
}
!self.state.is_null()
}
unsafe fn drop_map(&mut self) {
unsafe {
if !self.state.is_null() {
(self.xkb.xkb_state_unref)(self.state);
}
if !self.map.is_null() {
(self.xkb.xkb_keymap_unref)(self.map);
}
}
(self.map, self.state) = (std::ptr::null_mut(), std::ptr::null_mut());
}
pub(crate) fn hold(&mut self, held: u32, latched: u32, locked: u32, group: u32) {
if !self.state.is_null() {
unsafe { (self.xkb.xkb_state_update_mask)(self.state, held, latched, locked, 0, 0, group) };
}
}
pub(crate) fn held(&self) -> Mods {
if self.state.is_null() {
return Mods::NONE;
}
let on = |name: &CStr| unsafe { (self.xkb.xkb_state_mod_name_is_active)(self.state, name.as_ptr(), IN_EFFECT) } > 0;
Mods { ctrl: on(c"Control"), shift: on(c"Shift"), alt: on(c"Mod1") }
}
pub(crate) fn press(&mut self, code: u32) -> (Option<Key>, String) {
if self.state.is_null() {
return (None, String::new());
}
let code = code + 8;
let sym = unsafe { (self.xkb.xkb_state_key_get_one_sym)(self.state, code) };
let named = key(sym as c_ulong);
(named, self.typed(code, sym))
}
pub(crate) fn which(&self, code: u32) -> Option<Key> {
if self.state.is_null() {
return None;
}
let sym = unsafe { (self.xkb.xkb_state_key_get_one_sym)(self.state, code + 8) };
key(sym as c_ulong)
}
fn typed(&mut self, code: u32, sym: u32) -> String {
let (status, mut room) = (self.compose(sym), [0 as c_char; 64]);
let len = unsafe {
match status {
COMPOSING | CANCELLED => 0,
COMPOSED => (self.xkb.xkb_compose_state_get_utf8)(self.composing, room.as_mut_ptr(), room.len()),
_ => (self.xkb.xkb_state_key_get_utf8)(self.state, code, room.as_mut_ptr(), room.len()),
}
};
if matches!(status, COMPOSED | CANCELLED) {
unsafe { (self.xkb.xkb_compose_state_reset)(self.composing) };
}
let bytes: Vec<u8> = room[..(len.max(0) as usize).min(room.len() - 1)].iter().map(|byte| *byte as u8).collect();
String::from_utf8_lossy(&bytes).into_owned()
}
fn compose(&mut self, sym: u32) -> c_int {
if self.composing.is_null() {
return 0;
}
unsafe {
if (self.xkb.xkb_compose_state_feed)(self.composing, sym) == 0 {
return 0;
}
(self.xkb.xkb_compose_state_get_status)(self.composing)
}
}
pub(crate) fn repeats(&self, code: u32) -> bool {
!self.map.is_null() && unsafe { (self.xkb.xkb_keymap_key_repeats)(self.map, code + 8) } != 0
}
}
impl Drop for Keyboard {
fn drop(&mut self) {
unsafe {
self.drop_map();
if !self.composing.is_null() {
(self.xkb.xkb_compose_state_unref)(self.composing);
}
if !self.table.is_null() {
(self.xkb.xkb_compose_table_unref)(self.table);
}
(self.xkb.xkb_context_unref)(self.context);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const A: u32 = 30;
const E: u32 = 18;
const APOSTROPHE: u32 = 40;
const ENTER: u32 = 28;
const LEFT_SHIFT: u32 = 42;
const F2: u32 = 60;
#[test]
fn a_key_is_named_and_types_what_the_map_says() {
let Some(mut keyboard) = Keyboard::named("us") else { return eprintln!("no libxkbcommon: not tested") };
assert_eq!(keyboard.press(A), (Some(Key::Char('a')), "a".into()));
assert_eq!(keyboard.press(ENTER).0, Some(Key::Enter));
assert_eq!(keyboard.press(F2), (Some(Key::F(2)), String::new()));
assert_eq!(keyboard.held(), Mods::NONE);
keyboard.hold(1, 0, 0, 0);
assert_eq!(keyboard.held(), Mods::SHIFT);
assert_eq!(keyboard.press(A), (Some(Key::Char('a')), "A".into()));
keyboard.hold(4, 0, 0, 0);
assert_eq!(keyboard.held(), Mods::CTRL);
keyboard.hold(0, 0, 0, 0);
assert!(keyboard.repeats(A) && !keyboard.repeats(LEFT_SHIFT), "letters go on while held; Shift does not");
}
#[test]
fn an_accent_waits_for_its_letter_and_the_two_make_one_character() {
let Some(mut keyboard) = Keyboard::named("us(intl)") else { return eprintln!("no libxkbcommon: not tested") };
if keyboard.composing.is_null() {
return eprintln!("no compose table for the language: not tested");
}
assert_eq!(keyboard.press(APOSTROPHE), (None, String::new()));
assert_eq!(keyboard.press(E).1, "é");
assert_eq!(keyboard.press(E).1, "e", "after the character, keys type as ever");
}
const CRITICAL: c_int = 10;
fn logging_only<T>(keyboard: &mut Keyboard, level: c_int, read: impl FnOnce(&mut Keyboard) -> T) -> T {
type Get = unsafe extern "C" fn(*mut c_void) -> c_int;
type Set = unsafe extern "C" fn(*mut c_void, c_int);
let lib = keyboard.xkb.lib;
let (Some(get), Some(set)) = (symbol(lib, "xkb_context_get_log_level\0"), symbol(lib, "xkb_context_set_log_level\0")) else { return read(keyboard) };
let (get, set) = unsafe { (std::mem::transmute::<*mut c_void, Get>(get), std::mem::transmute::<*mut c_void, Set>(set)) };
let was = unsafe { get(keyboard.context) };
unsafe { set(keyboard.context, level) };
let read = read(keyboard);
unsafe { set(keyboard.context, was) };
read
}
#[test]
fn a_map_handed_over_as_text_is_read() {
let Some(mut keyboard) = Keyboard::new() else { return eprintln!("no libxkbcommon: not tested") };
assert!(!logging_only(&mut keyboard, CRITICAL, |keyboard| keyboard.take_map(b"not a map\0")), "nonsense is no map");
assert_eq!(keyboard.press(A), (None, String::new()), "with no map, keys mean nothing");
let map = b"xkb_keymap { xkb_keycodes { <AC01> = 38; }; xkb_types { include \"basic\" }; xkb_compat { }; xkb_symbols { key <AC01> { [ q, Q ] }; }; };\0";
assert!(keyboard.take_map(map));
assert_eq!(keyboard.press(A), (Some(Key::Char('q')), "q".into()), "the key on the map as given, whatever it is on other keyboards");
}
}