use std::ffi::OsStr;
use icedwright_protocol::{WireEvent, WireKey, WireLocation};
use icedwright_types::input::NamedKey;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OsKey(pub u32);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Backend {
X11,
}
pub fn choose_backend(
wayland_display: Option<&OsStr>,
display: Option<&OsStr>,
) -> Result<Backend, String> {
if wayland_display.is_some_and(|value| !value.is_empty()) {
return Err(
"the app is a Wayland client, and Wayland lets a client inject keys only \
through the RemoteDesktop portal, which needs a person to approve each \
session; run the app under X11 (unset WAYLAND_DISPLAY) for the OS keyboard"
.to_owned(),
);
}
if display.is_some_and(|value| !value.is_empty()) {
return Ok(Backend::X11);
}
Err(
"there is no display to send OS keys to: neither WAYLAND_DISPLAY nor DISPLAY is set"
.to_owned(),
)
}
#[cfg_attr(test, mockall::automock)]
pub trait KeyInjector: Send {
fn focus(&mut self, window: u32) -> Result<(), String>;
fn key(&mut self, key: OsKey, down: bool) -> Result<(), String>;
fn flush(&mut self) -> Result<(), String>;
}
pub fn os_keys(events: &[WireEvent]) -> Result<Vec<(OsKey, bool)>, String> {
let mut keys = Vec::new();
for event in events {
let (key, location, down) = match event {
WireEvent::KeyPressed { key, location, .. } => (key, *location, true),
WireEvent::KeyReleased { key, location, .. } => (key, *location, false),
WireEvent::ModifiersChanged { .. } => continue,
other => {
return Err(format!(
"{other:?} is not a key event, so the OS keyboard cannot send it"
));
}
};
keys.push((keysym(key, location)?, down));
}
Ok(keys)
}
pub fn inject(
injector: &mut dyn KeyInjector,
window: Option<u32>,
events: &[WireEvent],
) -> Result<usize, String> {
let keys = os_keys(events)?;
if let Some(window) = window {
injector.focus(window)?;
}
for (key, down) in &keys {
injector.key(*key, *down)?;
}
injector.flush()?;
Ok(events.len())
}
fn keysym(key: &WireKey, location: WireLocation) -> Result<OsKey, String> {
match key {
WireKey::Character(text) => {
let mut chars = text.chars();
let (Some(c), None) = (chars.next(), chars.next()) else {
return Err(format!(
"{text:?} is more than one character, which needs an input method"
));
};
let c = c.to_ascii_lowercase();
let code = u32::from(c);
Ok(OsKey(if code <= 0xff {
code
} else {
0x0100_0000 | code
}))
}
WireKey::Named(named) => named_keysym(*named, location)
.map(OsKey)
.ok_or_else(|| format!("the OS keyboard has no key for {named:?}")),
WireKey::Unidentified => Err("an unidentified key cannot be sent".to_owned()),
}
}
fn named_keysym(key: NamedKey, location: WireLocation) -> Option<u32> {
let right = location == WireLocation::Right;
let sym = match key {
NamedKey::Shift if right => 0xffe2,
NamedKey::Shift => 0xffe1,
NamedKey::Control if right => 0xffe4,
NamedKey::Control => 0xffe3,
NamedKey::Alt if right => 0xffea,
NamedKey::Alt => 0xffe9,
NamedKey::Super | NamedKey::Meta if right => 0xffec,
NamedKey::Super | NamedKey::Meta => 0xffeb,
NamedKey::AltGraph => 0xfe03,
NamedKey::CapsLock => 0xffe5,
NamedKey::Enter => 0xff0d,
NamedKey::Tab => 0xff09,
NamedKey::Space => 0x0020,
NamedKey::Backspace => 0xff08,
NamedKey::Delete => 0xffff,
NamedKey::Escape => 0xff1b,
NamedKey::Insert => 0xff63,
NamedKey::Home => 0xff50,
NamedKey::End => 0xff57,
NamedKey::PageUp => 0xff55,
NamedKey::PageDown => 0xff56,
NamedKey::ArrowLeft => 0xff51,
NamedKey::ArrowUp => 0xff52,
NamedKey::ArrowRight => 0xff53,
NamedKey::ArrowDown => 0xff54,
NamedKey::F1 => 0xffbe,
NamedKey::F2 => 0xffbf,
NamedKey::F3 => 0xffc0,
NamedKey::F4 => 0xffc1,
NamedKey::F5 => 0xffc2,
NamedKey::F6 => 0xffc3,
NamedKey::F7 => 0xffc4,
NamedKey::F8 => 0xffc5,
NamedKey::F9 => 0xffc6,
NamedKey::F10 => 0xffc7,
NamedKey::F11 => 0xffc8,
NamedKey::F12 => 0xffc9,
_ => return None,
};
Some(sym)
}
pub(crate) fn x11_window(window: &dyn iced_program::runtime::window::Window) -> Option<u32> {
use iced_program::runtime::window::raw_window_handle::RawWindowHandle;
match window.window_handle().ok()?.as_raw() {
RawWindowHandle::Xlib(handle) => u32::try_from(handle.window).ok(),
RawWindowHandle::Xcb(handle) => Some(handle.window.get()),
_ => None,
}
}
#[cfg(feature = "os-keyboard")]
pub(crate) fn connect() -> Result<Box<dyn KeyInjector>, String> {
let wayland = std::env::var_os("WAYLAND_DISPLAY");
let display = std::env::var_os("DISPLAY");
match choose_backend(wayland.as_deref(), display.as_deref())? {
Backend::X11 => Ok(Box::new(x11::XTest::connect()?)),
}
}
pub(crate) fn support() -> Result<(), String> {
#[cfg(feature = "os-keyboard")]
{
let wayland = std::env::var_os("WAYLAND_DISPLAY");
let display = std::env::var_os("DISPLAY");
choose_backend(wayland.as_deref(), display.as_deref()).map(|_| ())
}
#[cfg(not(feature = "os-keyboard"))]
{
Err("this app was built without the probe's os-keyboard feature".to_owned())
}
}
#[cfg(feature = "os-keyboard")]
mod x11 {
use std::collections::BTreeMap;
use x11rb::connection::Connection as _;
use x11rb::protocol::xproto::{
ConnectionExt as _, InputFocus, KEY_PRESS_EVENT, KEY_RELEASE_EVENT, Keycode, Window,
};
use x11rb::protocol::xtest::ConnectionExt as _;
use x11rb::rust_connection::RustConnection;
use super::{KeyInjector, OsKey};
pub(super) struct XTest {
connection: RustConnection,
root: Window,
keycodes: BTreeMap<u32, Keycode>,
}
fn text(error: impl std::fmt::Display) -> String {
format!("the X server's keyboard could not be used: {error}")
}
impl XTest {
pub(super) fn connect() -> Result<Self, String> {
let (connection, screen) = x11rb::connect(None).map_err(text)?;
let setup = connection.setup();
let root = setup
.roots
.get(screen)
.map(|screen| screen.root)
.ok_or_else(|| text("the display has no screen"))?;
let (min, max) = (setup.min_keycode, setup.max_keycode);
let _ = connection
.xtest_get_version(2, 2)
.map_err(text)?
.reply()
.map_err(|e| text(format!("the XTest extension is missing: {e}")))?;
let mapping = connection
.get_keyboard_mapping(min, max.saturating_sub(min).saturating_add(1))
.map_err(text)?
.reply()
.map_err(text)?;
let per = usize::from(mapping.keysyms_per_keycode).max(1);
let mut keycodes = BTreeMap::new();
for (offset, syms) in mapping.keysyms.chunks(per).enumerate() {
let Some(code) = u8::try_from(offset)
.ok()
.and_then(|offset| min.checked_add(offset))
else {
break;
};
for sym in syms.iter().take(2).filter(|sym| **sym != 0) {
keycodes.entry(*sym).or_insert(code);
}
}
Ok(Self {
connection,
root,
keycodes,
})
}
}
impl KeyInjector for XTest {
fn focus(&mut self, window: u32) -> Result<(), String> {
let _ = self
.connection
.set_input_focus(InputFocus::PARENT, window, x11rb::CURRENT_TIME)
.map_err(text)?;
Ok(())
}
fn key(&mut self, key: OsKey, down: bool) -> Result<(), String> {
let Some(code) = self.keycodes.get(&key.0).copied() else {
return Err(format!(
"no key on the X server's keyboard types keysym {:#x}",
key.0
));
};
let kind = if down {
KEY_PRESS_EVENT
} else {
KEY_RELEASE_EVENT
};
let _ = self
.connection
.xtest_fake_input(kind, code, x11rb::CURRENT_TIME, self.root, 0, 0, 0)
.map_err(text)?;
Ok(())
}
fn flush(&mut self) -> Result<(), String> {
let _ = self
.connection
.get_input_focus()
.map_err(text)?
.reply()
.map_err(text)?;
Ok(())
}
}
}
#[cfg(test)]
mod tests {
use icedwright_protocol::{WireModifiers, WirePhysicalKey};
use icedwright_types::input::KeyCode;
use mockall::Sequence;
use mockall::predicate::eq;
use super::*;
fn press(key: WireKey, down: bool) -> WireEvent {
let physical_key = WirePhysicalKey::Code(KeyCode::KeyK);
let location = WireLocation::Standard;
let modifiers = WireModifiers::default();
if down {
WireEvent::KeyPressed {
modified_key: key.clone(),
key,
physical_key,
location,
modifiers,
text: None,
repeat: false,
}
} else {
WireEvent::KeyReleased {
modified_key: key.clone(),
key,
physical_key,
location,
modifiers,
}
}
}
fn ctrl_k() -> Vec<WireEvent> {
let control = WireKey::Named(NamedKey::Control);
let k = WireKey::Character("K".to_owned());
vec![
WireEvent::ModifiersChanged {
modifiers: WireModifiers {
control: true,
..WireModifiers::default()
},
},
press(control.clone(), true),
press(k.clone(), true),
press(k, false),
press(control, false),
]
}
#[test]
fn a_chord_becomes_its_keysyms_in_order() {
let keys = os_keys(&ctrl_k());
assert_eq!(
keys,
Ok(vec![
(OsKey(0xffe3), true),
(OsKey(u32::from('k')), true),
(OsKey(u32::from('k')), false),
(OsKey(0xffe3), false),
])
);
}
#[test]
fn non_latin_characters_use_the_unicode_keysym_range() {
let keys = os_keys(&[press(WireKey::Character("ж".to_owned()), true)]);
assert_eq!(keys, Ok(vec![(OsKey(0x0100_0000 | 0x0436), true)]));
}
#[test]
fn pointer_events_and_composed_text_are_refused() {
let pointer = WireEvent::CursorLeft;
assert!(os_keys(&[pointer]).is_err_and(|e| e.contains("not a key event")));
let composed = press(WireKey::Character("ab".to_owned()), true);
assert!(os_keys(&[composed]).is_err_and(|e| e.contains("input method")));
}
#[test]
fn inject_focuses_sends_every_key_then_flushes() {
let mut injector = MockKeyInjector::new();
let mut order = Sequence::new();
injector
.expect_focus()
.with(eq(77))
.times(1)
.in_sequence(&mut order)
.returning(|_| Ok(()));
for (key, down) in [(0xffe3, true), (0x6b, true), (0x6b, false), (0xffe3, false)] {
injector
.expect_key()
.with(eq(OsKey(key)), eq(down))
.times(1)
.in_sequence(&mut order)
.returning(|_, _| Ok(()));
}
injector
.expect_flush()
.times(1)
.in_sequence(&mut order)
.returning(|| Ok(()));
assert_eq!(inject(&mut injector, Some(77), &ctrl_k()), Ok(5));
}
#[test]
fn a_window_of_unknown_id_is_not_focused() {
let mut injector = MockKeyInjector::new();
injector.expect_focus().times(0);
injector.expect_key().times(4).returning(|_, _| Ok(()));
injector.expect_flush().times(1).returning(|| Ok(()));
assert_eq!(inject(&mut injector, None, &ctrl_k()), Ok(5));
}
#[test]
fn a_key_the_keyboard_lacks_stops_before_the_flush() {
let mut injector = MockKeyInjector::new();
injector
.expect_key()
.times(1)
.returning(|_, _| Err("no key".to_owned()));
injector.expect_flush().times(0);
let sent = inject(&mut injector, None, &ctrl_k());
assert_eq!(sent, Err("no key".to_owned()));
}
#[test]
fn a_failed_focus_or_flush_is_reported() {
let mut injector = MockKeyInjector::new();
injector
.expect_focus()
.returning(|_| Err("no window".to_owned()));
injector.expect_key().times(0);
let sent = inject(&mut injector, Some(1), &ctrl_k());
assert_eq!(sent, Err("no window".to_owned()));
let mut injector = MockKeyInjector::new();
injector.expect_key().returning(|_, _| Ok(()));
injector.expect_flush().returning(|| Err("gone".to_owned()));
let sent = inject(&mut injector, None, &ctrl_k());
assert_eq!(sent, Err("gone".to_owned()));
}
#[test]
fn wayland_is_refused_and_x11_chosen_from_the_environment() {
let wayland = choose_backend(Some(OsStr::new("wayland-1")), Some(OsStr::new(":0")));
assert!(wayland.is_err_and(|e| e.contains("RemoteDesktop portal")));
assert_eq!(
choose_backend(None, Some(OsStr::new(":99"))),
Ok(Backend::X11)
);
assert_eq!(
choose_backend(Some(OsStr::new("")), Some(OsStr::new(":99"))),
Ok(Backend::X11)
);
assert!(choose_backend(None, None).is_err_and(|e| e.contains("no display")));
}
}