use std::env;
use std::ffi::CString;
use std::fs::File;
use std::os::raw::c_char;
use std::os::unix::ffi::OsStringExt;
use std::os::unix::io::{FromRawFd, RawFd};
use std::ptr;
use std::sync::{mpsc, Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use memmap::MmapOptions;
pub use wayland_client::protocol::wl_keyboard::KeyState;
use wayland_client::protocol::{wl_keyboard, wl_seat, wl_surface};
use wayland_client::Proxy;
use wayland_client::protocol::wl_seat::RequestsTrait;
use self::ffi::xkb_state_component;
use self::ffi::XKBCOMMON_HANDLE as XKBH;
mod ffi;
pub mod keysyms;
struct KbState {
xkb_context: *mut ffi::xkb_context,
xkb_keymap: *mut ffi::xkb_keymap,
xkb_state: *mut ffi::xkb_state,
xkb_compose_table: *mut ffi::xkb_compose_table,
xkb_compose_state: *mut ffi::xkb_compose_state,
mods_state: ModifiersState,
locked: bool,
}
#[derive(Copy, Clone, Debug, Default)]
pub struct ModifiersState {
pub ctrl: bool,
pub alt: bool,
pub shift: bool,
pub caps_lock: bool,
pub logo: bool,
pub num_lock: bool,
}
impl ModifiersState {
fn new() -> ModifiersState {
ModifiersState::default()
}
fn update_with(&mut self, state: *mut ffi::xkb_state) {
self.ctrl = unsafe {
(XKBH.xkb_state_mod_name_is_active)(
state,
ffi::XKB_MOD_NAME_CTRL.as_ptr() as *const c_char,
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
) > 0
};
self.alt = unsafe {
(XKBH.xkb_state_mod_name_is_active)(
state,
ffi::XKB_MOD_NAME_ALT.as_ptr() as *const c_char,
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
) > 0
};
self.shift = unsafe {
(XKBH.xkb_state_mod_name_is_active)(
state,
ffi::XKB_MOD_NAME_SHIFT.as_ptr() as *const c_char,
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
) > 0
};
self.caps_lock = unsafe {
(XKBH.xkb_state_mod_name_is_active)(
state,
ffi::XKB_MOD_NAME_CAPS.as_ptr() as *const c_char,
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
) > 0
};
self.logo = unsafe {
(XKBH.xkb_state_mod_name_is_active)(
state,
ffi::XKB_MOD_NAME_LOGO.as_ptr() as *const c_char,
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
) > 0
};
self.num_lock = unsafe {
(XKBH.xkb_state_mod_name_is_active)(
state,
ffi::XKB_MOD_NAME_NUM.as_ptr() as *const c_char,
xkb_state_component::XKB_STATE_MODS_EFFECTIVE,
) > 0
};
}
}
unsafe impl Send for KbState {}
impl KbState {
fn update_modifiers(
&mut self,
mods_depressed: u32,
mods_latched: u32,
mods_locked: u32,
group: u32,
) {
if !self.ready() {
return;
}
let mask = unsafe {
(XKBH.xkb_state_update_mask)(
self.xkb_state,
mods_depressed,
mods_latched,
mods_locked,
0,
0,
group,
)
};
if mask.contains(xkb_state_component::XKB_STATE_MODS_EFFECTIVE) {
self.mods_state.update_with(self.xkb_state);
}
}
fn get_one_sym_raw(&mut self, keycode: u32) -> u32 {
if !self.ready() {
return 0;
}
unsafe { (XKBH.xkb_state_key_get_one_sym)(self.xkb_state, keycode + 8) }
}
fn get_utf8_raw(&mut self, keycode: u32) -> Option<String> {
if !self.ready() {
return None;
}
let size = unsafe {
(XKBH.xkb_state_key_get_utf8)(self.xkb_state, keycode + 8, ptr::null_mut(), 0)
} + 1;
if size <= 1 {
return None;
};
let mut buffer = Vec::with_capacity(size as usize);
unsafe {
buffer.set_len(size as usize);
(XKBH.xkb_state_key_get_utf8)(
self.xkb_state,
keycode + 8,
buffer.as_mut_ptr() as *mut _,
size as usize,
);
};
buffer.pop();
Some(unsafe { String::from_utf8_unchecked(buffer) })
}
fn compose_feed(&mut self, keysym: u32) -> Option<ffi::xkb_compose_feed_result> {
if !self.ready() || self.xkb_compose_state.is_null() {
return None;
}
Some(unsafe { (XKBH.xkb_compose_state_feed)(self.xkb_compose_state, keysym) })
}
fn compose_status(&mut self) -> Option<ffi::xkb_compose_status> {
if !self.ready() || self.xkb_compose_state.is_null() {
return None;
}
Some(unsafe { (XKBH.xkb_compose_state_get_status)(self.xkb_compose_state) })
}
fn compose_get_utf8(&mut self) -> Option<String> {
if !self.ready() || self.xkb_compose_state.is_null() {
return None;
}
let size = unsafe {
(XKBH.xkb_compose_state_get_utf8)(self.xkb_compose_state, ptr::null_mut(), 0)
} + 1;
if size <= 1 {
return None;
};
let mut buffer = Vec::with_capacity(size as usize);
unsafe {
buffer.set_len(size as usize);
(XKBH.xkb_compose_state_get_utf8)(
self.xkb_compose_state,
buffer.as_mut_ptr() as *mut _,
size as usize,
);
};
buffer.pop();
Some(unsafe { String::from_utf8_unchecked(buffer) })
}
fn new() -> Result<KbState, Error> {
let xkbh = match ffi::XKBCOMMON_OPTION.as_ref() {
Some(h) => h,
None => return Err(Error::XKBNotFound),
};
let xkb_context =
unsafe { (xkbh.xkb_context_new)(ffi::xkb_context_flags::XKB_CONTEXT_NO_FLAGS) };
if xkb_context.is_null() {
return Err(Error::XKBNotFound);
}
let mut me = KbState {
xkb_context,
xkb_keymap: ptr::null_mut(),
xkb_state: ptr::null_mut(),
xkb_compose_table: ptr::null_mut(),
xkb_compose_state: ptr::null_mut(),
mods_state: ModifiersState::new(),
locked: false,
};
unsafe {
me.init_compose();
}
Ok(me)
}
unsafe fn init_compose(&mut self) {
let locale = env::var_os("LC_ALL")
.or_else(|| env::var_os("LC_CTYPE"))
.or_else(|| env::var_os("LANG"))
.unwrap_or_else(|| "C".into());
let locale = CString::new(locale.into_vec()).unwrap();
let compose_table = (XKBH.xkb_compose_table_new_from_locale)(
self.xkb_context,
locale.as_ptr(),
ffi::xkb_compose_compile_flags::XKB_COMPOSE_COMPILE_NO_FLAGS,
);
if compose_table.is_null() {
return;
}
let compose_state = (XKBH.xkb_compose_state_new)(
compose_table,
ffi::xkb_compose_state_flags::XKB_COMPOSE_STATE_NO_FLAGS,
);
if compose_state.is_null() {
(XKBH.xkb_compose_table_unref)(compose_table);
return;
}
self.xkb_compose_table = compose_table;
self.xkb_compose_state = compose_state;
}
unsafe fn post_init(&mut self, xkb_keymap: *mut ffi::xkb_keymap) {
let xkb_state = (XKBH.xkb_state_new)(xkb_keymap);
self.xkb_keymap = xkb_keymap;
self.xkb_state = xkb_state;
self.mods_state.update_with(xkb_state);
}
unsafe fn de_init(&mut self) {
(XKBH.xkb_state_unref)(self.xkb_state);
self.xkb_state = ptr::null_mut();
(XKBH.xkb_keymap_unref)(self.xkb_keymap);
self.xkb_keymap = ptr::null_mut();
}
unsafe fn init_with_fd(&mut self, fd: RawFd, size: usize) {
let map = MmapOptions::new()
.len(size)
.map(&File::from_raw_fd(fd))
.unwrap();
let xkb_keymap = (XKBH.xkb_keymap_new_from_string)(
self.xkb_context,
map.as_ptr() as *const _,
ffi::xkb_keymap_format::XKB_KEYMAP_FORMAT_TEXT_V1,
ffi::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
);
if xkb_keymap.is_null() {
panic!("Received invalid keymap from compositor.");
}
self.post_init(xkb_keymap);
}
unsafe fn init_with_rmlvo(&mut self, names: ffi::xkb_rule_names) -> Result<(), Error> {
let xkb_keymap = (XKBH.xkb_keymap_new_from_names)(
self.xkb_context,
&names,
ffi::xkb_keymap_compile_flags::XKB_KEYMAP_COMPILE_NO_FLAGS,
);
if xkb_keymap.is_null() {
return Err(Error::BadNames);
}
self.post_init(xkb_keymap);
Ok(())
}
unsafe fn key_repeats(&mut self, xkb_keycode_t: ffi::xkb_keycode_t) -> bool {
(XKBH.xkb_keymap_key_repeats)(self.xkb_keymap, xkb_keycode_t) == 1
}
#[inline]
fn ready(&self) -> bool {
!self.xkb_state.is_null()
}
}
impl Drop for KbState {
fn drop(&mut self) {
unsafe {
(XKBH.xkb_compose_state_unref)(self.xkb_compose_state);
(XKBH.xkb_compose_table_unref)(self.xkb_compose_table);
(XKBH.xkb_state_unref)(self.xkb_state);
(XKBH.xkb_keymap_unref)(self.xkb_keymap);
(XKBH.xkb_context_unref)(self.xkb_context);
}
}
}
#[derive(PartialEq)]
pub enum KeyRepeatKind {
Fixed {
rate: u64,
delay: u64,
},
System,
}
#[derive(Debug)]
pub enum Error {
XKBNotFound,
BadNames,
}
pub struct RMLVO {
pub rules: Option<String>,
pub model: Option<String>,
pub layout: Option<String>,
pub variant: Option<String>,
pub options: Option<String>,
}
pub enum Event<'a> {
Enter {
serial: u32,
surface: Proxy<wl_surface::WlSurface>,
rawkeys: &'a [u32],
keysyms: &'a [u32],
},
Leave {
serial: u32,
surface: Proxy<wl_surface::WlSurface>,
},
Key {
serial: u32,
time: u32,
rawkey: u32,
keysym: u32,
state: KeyState,
utf8: Option<String>,
},
RepeatInfo {
rate: i32,
delay: i32,
},
Modifiers {
modifiers: ModifiersState,
},
}
pub struct KeyRepeatEvent {
pub time: u32,
pub rawkey: u32,
pub keysym: u32,
pub utf8: Option<String>,
}
pub fn map_keyboard_auto<Impl>(
seat: &Proxy<wl_seat::WlSeat>,
implementation: Impl,
) -> Result<Proxy<wl_keyboard::WlKeyboard>, Error>
where
for<'a> Impl: FnMut(Event<'a>, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
{
let state = match KbState::new() {
Ok(s) => s,
Err(e) => return Err(e),
};
Ok(implement_kbd(
seat,
state,
implementation,
None::<(_, fn(_, _))>,
))
}
pub fn map_keyboard_rmlvo<Impl>(
seat: &Proxy<wl_seat::WlSeat>,
rmlvo: RMLVO,
implementation: Impl,
) -> Result<Proxy<wl_keyboard::WlKeyboard>, Error>
where
for<'a> Impl: FnMut(Event<'a>, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
{
fn to_cstring(s: Option<String>) -> Result<Option<CString>, Error> {
s.map_or(Ok(None), |s| CString::new(s).map(Option::Some))
.map_err(|_| Error::BadNames)
}
fn init_state(rmlvo: RMLVO) -> Result<KbState, Error> {
let mut state = KbState::new()?;
let rules = to_cstring(rmlvo.rules)?;
let model = to_cstring(rmlvo.model)?;
let layout = to_cstring(rmlvo.layout)?;
let variant = to_cstring(rmlvo.variant)?;
let options = to_cstring(rmlvo.options)?;
let xkb_names = ffi::xkb_rule_names {
rules: rules.map_or(ptr::null(), |s| s.as_ptr()),
model: model.map_or(ptr::null(), |s| s.as_ptr()),
layout: layout.map_or(ptr::null(), |s| s.as_ptr()),
variant: variant.map_or(ptr::null(), |s| s.as_ptr()),
options: options.map_or(ptr::null(), |s| s.as_ptr()),
};
unsafe {
state.init_with_rmlvo(xkb_names)?;
}
state.locked = true;
Ok(state)
}
match init_state(rmlvo) {
Ok(state) => Ok(implement_kbd(
seat,
state,
implementation,
None::<(_, fn(_, _))>,
)),
Err(error) => Err(error),
}
}
fn implement_kbd<Impl, RepeatImpl>(
seat: &Proxy<wl_seat::WlSeat>,
state: KbState,
mut event_impl: Impl,
repeat: Option<(KeyRepeatKind, RepeatImpl)>,
) -> Proxy<wl_keyboard::WlKeyboard>
where
for<'a> Impl: FnMut(Event<'a>, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
RepeatImpl: FnMut(KeyRepeatEvent, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
{
let safe_state = Arc::new(Mutex::new(state));
let (key_repeat_kind, repeat_impl) = {
if let Some(repeat) = repeat {
(Some(repeat.0), Some(Arc::new(Mutex::new(repeat.1))))
} else {
(None, None)
}
};
let kill_chan = Arc::new(Mutex::new(mpsc::channel::<()>()));
let state_chan = Arc::new(Mutex::new(mpsc::channel::<()>()));
let mut key_held: Option<u32> = None;
let system_repeat_timing: Arc<Mutex<(u64, u64)>> = Arc::new(Mutex::new((30, 500)));
seat.get_keyboard(|kbd| {
kbd.implement(
move |event: wl_keyboard::Event, proxy: Proxy<wl_keyboard::WlKeyboard>| {
let mut state = safe_state.lock().unwrap();
match event {
wl_keyboard::Event::Keymap { format, fd, size } => {
if state.locked {
return;
}
if state.ready() {
unsafe {
state.de_init();
}
}
match format {
wl_keyboard::KeymapFormat::XkbV1 => unsafe {
state.init_with_fd(fd, size as usize);
},
wl_keyboard::KeymapFormat::NoKeymap => {
}
}
}
wl_keyboard::Event::Enter {
serial,
surface,
keys,
} => {
let rawkeys: &[u32] = unsafe {
::std::slice::from_raw_parts(
keys.as_ptr() as *const u32,
keys.len() / 4,
)
};
let keys: Vec<u32> =
rawkeys.iter().map(|k| state.get_one_sym_raw(*k)).collect();
event_impl(
Event::Enter {
serial,
surface,
rawkeys,
keysyms: &keys,
},
proxy,
);
}
wl_keyboard::Event::Leave { serial, surface } => {
if key_held.is_some() {
kill_chan.lock().unwrap().0.send(()).unwrap();
key_held = None;
}
event_impl(Event::Leave { serial, surface }, proxy);
}
wl_keyboard::Event::Key {
serial,
time,
key,
state: key_state,
} => {
let sym = state.get_one_sym_raw(key);
let utf8 = if key_state == wl_keyboard::KeyState::Pressed {
if state.compose_feed(sym)
!= Some(ffi::xkb_compose_feed_result::XKB_COMPOSE_FEED_ACCEPTED)
{
None
} else if let Some(status) = state.compose_status() {
match status {
ffi::xkb_compose_status::XKB_COMPOSE_COMPOSED => {
state.compose_get_utf8()
}
ffi::xkb_compose_status::XKB_COMPOSE_NOTHING => {
state.get_utf8_raw(key)
}
_ => None,
}
} else {
state.get_utf8_raw(key)
}
} else {
None
};
if key_state == wl_keyboard::KeyState::Pressed {
event_impl(
Event::Key {
serial,
time,
rawkey: key,
keysym: sym,
state: key_state,
utf8: utf8.clone(),
},
proxy.clone(),
);
if let Some(repeat_impl) = repeat_impl.clone() {
if unsafe { state.key_repeats(key + 8) } {
if key_held.is_some() {
kill_chan.lock().unwrap().0.send(()).unwrap();
}
key_held = Some(key);
let thread_kill_chan = kill_chan.clone();
let thread_state_chan = state_chan.clone();
let thread_state = safe_state.clone();
let thread_repeat_impl = repeat_impl.clone();
let repeat_timing = match key_repeat_kind {
Some(KeyRepeatKind::Fixed { rate, delay, .. }) => {
(rate, delay)
}
Some(KeyRepeatKind::System { .. }) => {
*system_repeat_timing.lock().unwrap()
}
None => panic!(),
};
thread::spawn(move || {
let time_tracker = Instant::now();
thread::sleep(Duration::from_millis(repeat_timing.1));
match thread_kill_chan.lock().unwrap().1.try_recv() {
Ok(_) | Err(mpsc::TryRecvError::Disconnected) => return,
_ => {}
}
let mut thread_sym = sym;
let mut thread_utf8 = utf8;
loop {
if thread_state_chan
.lock()
.unwrap()
.1
.try_recv()
.is_ok()
{
let mut thread_state = thread_state.lock().unwrap();
thread_sym = thread_state.get_one_sym_raw(key);
thread_utf8 = thread_state.get_utf8_raw(key);
}
let elapsed_time = time_tracker.elapsed();
(&mut *thread_repeat_impl.lock().unwrap())(
KeyRepeatEvent {
time: time
+ elapsed_time.as_secs() as u32 * 1000
+ elapsed_time.subsec_nanos() / 1_000_000,
rawkey: key,
keysym: thread_sym,
utf8: thread_utf8.clone(),
},
proxy.clone(),
);
thread::sleep(
Duration::from_secs(1) / repeat_timing.0 as u32,
);
match thread_kill_chan.lock().unwrap().1.try_recv() {
Ok(_) | Err(mpsc::TryRecvError::Disconnected) => {
break;
}
_ => {}
}
}
});
}
}
} else {
if key_held == Some(key) {
kill_chan.lock().unwrap().0.send(()).unwrap();
key_held = None;
}
event_impl(
Event::Key {
serial,
time,
rawkey: key,
keysym: sym,
state: key_state,
utf8: utf8.clone(),
},
proxy.clone(),
);
}
}
wl_keyboard::Event::Modifiers {
mods_depressed,
mods_latched,
mods_locked,
group,
..
} => {
state.update_modifiers(mods_depressed, mods_latched, mods_locked, group);
event_impl(
Event::Modifiers {
modifiers: state.mods_state,
},
proxy,
);
if key_held.is_some() {
state_chan.lock().unwrap().0.send(()).unwrap();
}
}
wl_keyboard::Event::RepeatInfo { rate, delay } => {
event_impl(Event::RepeatInfo { rate, delay }, proxy);
*system_repeat_timing.lock().unwrap() = (rate as u64, delay as u64);
}
}
},
(),
)
})
.unwrap()
}
pub fn map_keyboard_auto_with_repeat<Impl, RepeatImpl>(
seat: &Proxy<wl_seat::WlSeat>,
key_repeat_kind: KeyRepeatKind,
implementation: Impl,
repeat_implementation: RepeatImpl,
) -> Result<Proxy<wl_keyboard::WlKeyboard>, Error>
where
for<'a> Impl: FnMut(Event<'a>, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
RepeatImpl: FnMut(KeyRepeatEvent, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
{
let state = match KbState::new() {
Ok(s) => s,
Err(e) => return Err(e),
};
Ok(implement_kbd(
seat,
state,
implementation,
Some((key_repeat_kind, repeat_implementation)),
))
}
pub fn map_keyboard_rmlvo_with_repeat<Impl, RepeatImpl>(
seat: &Proxy<wl_seat::WlSeat>,
rmlvo: RMLVO,
key_repeat_kind: KeyRepeatKind,
implementation: Impl,
repeat_implementation: RepeatImpl,
) -> Result<Proxy<wl_keyboard::WlKeyboard>, Error>
where
for<'a> Impl: FnMut(Event<'a>, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
RepeatImpl: FnMut(KeyRepeatEvent, Proxy<wl_keyboard::WlKeyboard>) + Send + 'static,
{
fn to_cstring(s: Option<String>) -> Result<Option<CString>, Error> {
s.map_or(Ok(None), |s| CString::new(s).map(Option::Some))
.map_err(|_| Error::BadNames)
}
fn init_state(rmlvo: RMLVO) -> Result<KbState, Error> {
let mut state = KbState::new()?;
let rules = to_cstring(rmlvo.rules)?;
let model = to_cstring(rmlvo.model)?;
let layout = to_cstring(rmlvo.layout)?;
let variant = to_cstring(rmlvo.variant)?;
let options = to_cstring(rmlvo.options)?;
let xkb_names = ffi::xkb_rule_names {
rules: rules.map_or(ptr::null(), |s| s.as_ptr()),
model: model.map_or(ptr::null(), |s| s.as_ptr()),
layout: layout.map_or(ptr::null(), |s| s.as_ptr()),
variant: variant.map_or(ptr::null(), |s| s.as_ptr()),
options: options.map_or(ptr::null(), |s| s.as_ptr()),
};
unsafe {
state.init_with_rmlvo(xkb_names)?;
}
state.locked = true;
Ok(state)
}
match init_state(rmlvo) {
Ok(state) => Ok(implement_kbd(
seat,
state,
implementation,
Some((key_repeat_kind, repeat_implementation)),
)),
Err(error) => Err(error),
}
}