wayland: fix key repeat
The main culprit was the calloop feature that is used by default in the underlying SCTK crate. This commit: * Routes keyboard processing via the same keyboard mapping code that we use for X11 * Implements key repeats directly, and with awareness of elapsed time in case the repeat rate is quicker than the event dispatching quantum * Disables the calloop feature of SCTK and let us do our own polling of the wayland connection. Critically, key repeat is sticky and unpredictable while calloop is enabled. closes: #669
This commit is contained in:
1 parent
c514254138
commit
0a00ffe98b
8 files changed
+383
-353
No files matched your search
Generated
+1
-12
@@ -521,16 +521,6 @@ version = "1.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "631ae5198c9be5e753e5cc215e1bd73c2b466a3565173db433f52bb9d3e66dba"
|
||||
|
||||
[[package]]
|
||||
name = "calloop"
|
||||
version = "0.7.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9d0a1340115d6bd81e1066469091596a339f68878a2ce3c2f39e546607d22131"
|
||||
dependencies = [
|
||||
"log",
|
||||
"nix 0.19.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cassowary"
|
||||
version = "0.3.0"
|
||||
@@ -3878,7 +3868,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec783683499a2cfc85b6df3d04f83b1907b5cbd98a1aed44667dbdf1eac4e64c"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"calloop",
|
||||
"dlib",
|
||||
"lazy_static",
|
||||
"log",
|
||||
@@ -4687,7 +4676,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2907bd297eef464a95ba9349ea771611771aa285b932526c633dc94d5400a8e2"
|
||||
dependencies = [
|
||||
"dlib",
|
||||
"lazy_static",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
@@ -5139,6 +5127,7 @@ version = "0.1.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"async-channel",
|
||||
"async-io",
|
||||
"async-task",
|
||||
"async-trait",
|
||||
"bitflags",
|
||||
|
||||
@@ -48,6 +48,7 @@ As features stabilize some brief notes about them will accumulate here.
|
||||
* Improved: DEC Special Graphics mode conformance and complete coverage of the graphics character set. Thanks to [Autumn Lamonte](https://gitlab.com/klamonte)! [#891](https://github.com/wez/wezterm/pull/891)
|
||||
* Fixed: click to focus now focuses the pane under the mouse cursor [#881](https://github.com/wez/wezterm/issues/881)
|
||||
* Removed: `Parasio Dark` color scheme; it was a duplicate of the correctly named `Paraiso Dark` scheme. Thanks to [@adrian5](https://github.com/adrian5)! [#906](https://github.com/wez/wezterm/pull/906)
|
||||
* Fixed: key repeat on Wayland now respects the system specified key repeat rate, and doesn't "stick". [#669](https://github.com/wez/wezterm/issues/669)
|
||||
|
||||
### 20210502-154244-3f7122cb
|
||||
|
||||
|
||||
+2
-1
@@ -20,6 +20,7 @@ wayland = ["wayland-client", "smithay-client-toolkit", "wayland-egl", "wayland-p
|
||||
|
||||
[dependencies]
|
||||
async-channel = "1.6"
|
||||
async-io = "1.1"
|
||||
async-task = "4.0"
|
||||
async-trait = "0.1"
|
||||
anyhow = "1.0"
|
||||
@@ -66,7 +67,7 @@ xcb-util = { features = [ "cursor", "image", "icccm", "ewmh", "keysyms"], versio
|
||||
xkbcommon = { version = "0.5", features = ["x11", "wayland"], git="https://github.com/wez/xkbcommon-rs.git", rev="01a0a0cd5663405e6e4abb1ad3add9add1496f58"}
|
||||
mio = "0.6"
|
||||
libc = "0.2"
|
||||
smithay-client-toolkit = {version = "0.14", features=["calloop"], optional=true}
|
||||
smithay-client-toolkit = {version = "0.14", default-features=false, optional=true}
|
||||
wayland-protocols = {version="0.28", optional=true}
|
||||
wayland-client = {version="0.28", optional=true}
|
||||
wayland-egl = {version="0.28", optional=true}
|
||||
|
||||
@@ -1,22 +1,25 @@
|
||||
#![allow(dead_code)]
|
||||
use super::keyboard::KeyboardDispatcher;
|
||||
use super::pointer::*;
|
||||
use super::window::*;
|
||||
use crate::connection::ConnectionOps;
|
||||
use crate::os::x11::keyboard::Keyboard;
|
||||
use crate::spawn::*;
|
||||
use crate::Connection;
|
||||
use anyhow::{anyhow, bail, Context};
|
||||
use anyhow::{bail, Context};
|
||||
use mio::unix::EventedFd;
|
||||
use mio::{Evented, Events, Poll, PollOpt, Ready, Token};
|
||||
use smithay_client_toolkit as toolkit;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::io::Read;
|
||||
use std::os::unix::io::FromRawFd;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::time::Duration;
|
||||
use toolkit::environment::Environment;
|
||||
use toolkit::reexports::calloop::{EventLoop, EventSource, Interest, Mode, Poll, Readiness, Token};
|
||||
use toolkit::reexports::client::Display;
|
||||
use toolkit::seat::SeatListener;
|
||||
use toolkit::WaylandSource;
|
||||
use wayland_client::protocol::wl_keyboard::{Event as WlKeyboardEvent, KeymapFormat, WlKeyboard};
|
||||
use wayland_client::{EventQueue, Main};
|
||||
|
||||
toolkit::default_environment!(MyEnvironment, desktop);
|
||||
|
||||
@@ -35,10 +38,19 @@ pub struct WaylandConnection {
|
||||
// must be ahead of the rest.
|
||||
pub(crate) gl_connection: RefCell<Option<Rc<crate::egl::GlConnection>>>,
|
||||
pub(crate) pointer: PointerDispatcher,
|
||||
pub(crate) keyboard: KeyboardDispatcher,
|
||||
pub(crate) keyboard_mapper: RefCell<Option<Keyboard>>,
|
||||
pub(crate) keyboard_window_id: RefCell<Option<usize>>,
|
||||
pub(crate) surface_to_window_id: RefCell<HashMap<u32, usize>>,
|
||||
|
||||
/// Repeats per second
|
||||
pub(crate) key_repeat_rate: RefCell<i32>,
|
||||
|
||||
/// Delay before repeating, in milliseconds
|
||||
pub(crate) key_repeat_delay: RefCell<i32>,
|
||||
pub(crate) last_serial: RefCell<u32>,
|
||||
seat_listener: SeatListener,
|
||||
pub(crate) environment: RefCell<Environment<MyEnvironment>>,
|
||||
event_q: RefCell<EventLoop<'static, ()>>,
|
||||
event_q: RefCell<EventQueue>,
|
||||
pub(crate) display: RefCell<Display>,
|
||||
}
|
||||
|
||||
@@ -46,23 +58,24 @@ impl WaylandConnection {
|
||||
pub fn create_new() -> anyhow::Result<Self> {
|
||||
let (environment, display, event_q) =
|
||||
toolkit::new_default_environment!(MyEnvironment, desktop)?;
|
||||
let event_loop = toolkit::reexports::calloop::EventLoop::<()>::try_new()?;
|
||||
|
||||
let keyboard = KeyboardDispatcher::new();
|
||||
let mut pointer = None;
|
||||
|
||||
for seat in environment.get_all_seats() {
|
||||
if let Some((has_kbd, has_ptr, name)) =
|
||||
toolkit::seat::with_seat_data(&seat, |seat_data| {
|
||||
(
|
||||
seat_data.has_keyboard && !seat_data.defunct,
|
||||
seat_data.has_pointer && !seat_data.defunct,
|
||||
seat_data.name.clone(),
|
||||
)
|
||||
})
|
||||
{
|
||||
if let Some((has_kbd, has_ptr)) = toolkit::seat::with_seat_data(&seat, |seat_data| {
|
||||
(
|
||||
seat_data.has_keyboard && !seat_data.defunct,
|
||||
seat_data.has_pointer && !seat_data.defunct,
|
||||
)
|
||||
}) {
|
||||
if has_kbd {
|
||||
keyboard.register(event_loop.handle(), &seat, &name)?;
|
||||
let keyboard = seat.get_keyboard();
|
||||
keyboard.quick_assign(|keyboard, event, _| {
|
||||
let conn = Connection::get().unwrap().wayland();
|
||||
if let Err(err) = conn.keyboard_event(keyboard, event) {
|
||||
log::error!("keyboard_event: {:#}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
if has_ptr {
|
||||
pointer.replace(PointerDispatcher::register(
|
||||
@@ -77,18 +90,16 @@ impl WaylandConnection {
|
||||
|
||||
let seat_listener;
|
||||
{
|
||||
let loop_handle = event_loop.handle();
|
||||
let keyboard = keyboard.clone();
|
||||
seat_listener = environment.listen_for_seats(move |seat, seat_data, _| {
|
||||
if seat_data.has_keyboard {
|
||||
if seat_data.defunct {
|
||||
keyboard.deregister(loop_handle.clone(), &seat_data.name);
|
||||
} else {
|
||||
if let Err(err) =
|
||||
keyboard.register(loop_handle.clone(), &seat, &seat_data.name)
|
||||
{
|
||||
log::error!("{:#}", err);
|
||||
}
|
||||
if !seat_data.defunct {
|
||||
let keyboard = seat.get_keyboard();
|
||||
keyboard.quick_assign(|keyboard, event, _| {
|
||||
let conn = Connection::get().unwrap().wayland();
|
||||
if let Err(err) = conn.keyboard_event(keyboard, event) {
|
||||
log::error!("keyboard_event: {:#}", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
if seat_data.has_pointer {
|
||||
@@ -105,24 +116,90 @@ impl WaylandConnection {
|
||||
});
|
||||
}
|
||||
|
||||
WaylandSource::new(event_q)
|
||||
.quick_insert(event_loop.handle())
|
||||
.map_err(|e| anyhow!("failed to setup WaylandSource: {:?}", e))?;
|
||||
|
||||
Ok(Self {
|
||||
display: RefCell::new(display),
|
||||
event_q: RefCell::new(event_loop),
|
||||
environment: RefCell::new(environment),
|
||||
should_terminate: RefCell::new(false),
|
||||
next_window_id: AtomicUsize::new(1),
|
||||
windows: RefCell::new(HashMap::new()),
|
||||
keyboard,
|
||||
event_q: RefCell::new(event_q),
|
||||
pointer: pointer.unwrap(),
|
||||
seat_listener,
|
||||
gl_connection: RefCell::new(None),
|
||||
keyboard_mapper: RefCell::new(None),
|
||||
key_repeat_rate: RefCell::new(25),
|
||||
key_repeat_delay: RefCell::new(400),
|
||||
keyboard_window_id: RefCell::new(None),
|
||||
last_serial: RefCell::new(0),
|
||||
surface_to_window_id: RefCell::new(HashMap::new()),
|
||||
})
|
||||
}
|
||||
|
||||
fn keyboard_event(
|
||||
&self,
|
||||
_pointer: Main<WlKeyboard>,
|
||||
event: WlKeyboardEvent,
|
||||
) -> anyhow::Result<()> {
|
||||
match &event {
|
||||
WlKeyboardEvent::Enter {
|
||||
serial, surface, ..
|
||||
} => {
|
||||
*self.last_serial.borrow_mut() = *serial;
|
||||
if let Some(&window_id) = self
|
||||
.surface_to_window_id
|
||||
.borrow()
|
||||
.get(&surface.as_ref().id())
|
||||
{
|
||||
self.keyboard_window_id.borrow_mut().replace(window_id);
|
||||
} else {
|
||||
log::warn!("{:?}, no known surface", event);
|
||||
}
|
||||
}
|
||||
WlKeyboardEvent::Leave { serial, .. }
|
||||
| WlKeyboardEvent::Key { serial, .. }
|
||||
| WlKeyboardEvent::Modifiers { serial, .. } => {
|
||||
*self.last_serial.borrow_mut() = *serial;
|
||||
}
|
||||
WlKeyboardEvent::RepeatInfo { rate, delay } => {
|
||||
*self.key_repeat_rate.borrow_mut() = *rate;
|
||||
*self.key_repeat_delay.borrow_mut() = *delay;
|
||||
}
|
||||
WlKeyboardEvent::Keymap { format, fd, size } => {
|
||||
let mut file = unsafe { std::fs::File::from_raw_fd(*fd) };
|
||||
match format {
|
||||
KeymapFormat::XkbV1 => {
|
||||
let mut data = vec![0u8; *size as usize];
|
||||
file.read_exact(&mut data)?;
|
||||
// Dance around CString panicing on the NUL terminator
|
||||
// in the xkbcommon crate
|
||||
while let Some(0) = data.last() {
|
||||
data.pop();
|
||||
}
|
||||
let s = String::from_utf8(data)?;
|
||||
match Keyboard::new_from_string(s) {
|
||||
Ok(k) => {
|
||||
self.keyboard_mapper.replace(Some(k));
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Error processing keymap change: {:#}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() {
|
||||
if let Some(win) = self.window_by_id(window_id) {
|
||||
let mut inner = win.borrow_mut();
|
||||
inner.keyboard_event(event);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn next_window_id(&self) -> usize {
|
||||
self.next_window_id
|
||||
.fetch_add(1, ::std::sync::atomic::Ordering::Relaxed)
|
||||
@@ -166,35 +243,28 @@ impl WaylandConnection {
|
||||
}
|
||||
}
|
||||
|
||||
struct SpawnQueueSource {}
|
||||
impl EventSource for SpawnQueueSource {
|
||||
type Event = ();
|
||||
type Metadata = ();
|
||||
type Ret = ();
|
||||
|
||||
fn process_events<F>(
|
||||
&mut self,
|
||||
_readiness: Readiness,
|
||||
_token: Token,
|
||||
mut callback: F,
|
||||
) -> std::io::Result<()>
|
||||
where
|
||||
F: FnMut(Self::Event, &mut Self::Metadata) -> Self::Ret,
|
||||
{
|
||||
callback((), &mut ());
|
||||
Ok(())
|
||||
impl Evented for WaylandConnection {
|
||||
fn register(
|
||||
&self,
|
||||
poll: &Poll,
|
||||
token: Token,
|
||||
interest: Ready,
|
||||
opts: PollOpt,
|
||||
) -> std::io::Result<()> {
|
||||
EventedFd(&self.display.borrow().get_connection_fd()).register(poll, token, interest, opts)
|
||||
}
|
||||
|
||||
fn register(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
|
||||
poll.register(SPAWN_QUEUE.raw_fd(), Interest::READ, Mode::Level, token)
|
||||
fn reregister(
|
||||
&self,
|
||||
poll: &Poll,
|
||||
token: Token,
|
||||
interest: Ready,
|
||||
opts: PollOpt,
|
||||
) -> std::io::Result<()> {
|
||||
EventedFd(&self.display.borrow().get_connection_fd())
|
||||
.reregister(poll, token, interest, opts)
|
||||
}
|
||||
|
||||
fn reregister(&mut self, poll: &mut Poll, token: Token) -> std::io::Result<()> {
|
||||
poll.register(SPAWN_QUEUE.raw_fd(), Interest::READ, Mode::Level, token)
|
||||
}
|
||||
|
||||
fn unregister(&mut self, poll: &mut Poll) -> std::io::Result<()> {
|
||||
poll.unregister(SPAWN_QUEUE.raw_fd())
|
||||
fn deregister(&self, poll: &Poll) -> std::io::Result<()> {
|
||||
EventedFd(&self.display.borrow().get_connection_fd()).deregister(poll)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,37 +276,67 @@ impl ConnectionOps for WaylandConnection {
|
||||
fn run_message_loop(&self) -> anyhow::Result<()> {
|
||||
self.flush()?;
|
||||
|
||||
self.event_q
|
||||
.borrow_mut()
|
||||
.handle()
|
||||
.insert_source(SpawnQueueSource {}, move |_, _, _| {
|
||||
// In theory, we'd SPAWN_QUEUE.run() here but we
|
||||
// prefer to defer that to the loop below where we
|
||||
// can have better control over the event_q borrow,
|
||||
// and so that we can inspect its return code.
|
||||
})
|
||||
.map_err(|e| anyhow!("failed to insert SpawnQueueSource: {:?}", e))?;
|
||||
const TOK_WL: usize = 0xffff_fffc;
|
||||
const TOK_SPAWN: usize = 0xffff_fffd;
|
||||
let tok_wl = Token(TOK_WL);
|
||||
let tok_spawn = Token(TOK_SPAWN);
|
||||
|
||||
let poll = Poll::new()?;
|
||||
let mut events = Events::with_capacity(8);
|
||||
poll.register(self, tok_wl, Ready::readable(), PollOpt::level())?;
|
||||
poll.register(
|
||||
&*SPAWN_QUEUE,
|
||||
tok_spawn,
|
||||
Ready::readable(),
|
||||
PollOpt::level(),
|
||||
)?;
|
||||
|
||||
while !*self.should_terminate.borrow() {
|
||||
{
|
||||
let mut event_q = self.event_q.borrow_mut();
|
||||
if let Err(err) = event_q.dispatch_pending(&mut (), |_, _, _| {}) {
|
||||
if err.kind() != std::io::ErrorKind::WouldBlock
|
||||
&& err.kind() != std::io::ErrorKind::Interrupted
|
||||
{
|
||||
return Err(err).with_context(|| {
|
||||
format!(
|
||||
"error during event_q.dispatch protocol_error={:?}",
|
||||
self.display.borrow().protocol_error()
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Check the spawn queue before we try to sleep; there may
|
||||
// be work pending and we don't guarantee that there is a
|
||||
// 1:1 wakeup to queued function, so we need to be assertive
|
||||
// in order to avoid missing wakeups
|
||||
let period = if SPAWN_QUEUE.run() {
|
||||
if SPAWN_QUEUE.run() {
|
||||
// if we processed one, we don't want to sleep because
|
||||
// there may be others to deal with
|
||||
Some(Duration::new(0, 0))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Err(err) = poll.poll(&mut events, None) {
|
||||
bail!("polling for events: {:?}", err);
|
||||
}
|
||||
|
||||
self.flush()?;
|
||||
{
|
||||
let mut event_q = self.event_q.borrow_mut();
|
||||
if let Err(err) = event_q.dispatch(period, &mut ()) {
|
||||
if err.kind() != std::io::ErrorKind::WouldBlock
|
||||
&& err.kind() != std::io::ErrorKind::Interrupted
|
||||
{
|
||||
return Err(err).context("error during event_q.dispatch");
|
||||
let event_q = self.event_q.borrow();
|
||||
if let Some(guard) = event_q.prepare_read() {
|
||||
if let Err(err) = guard.read_events() {
|
||||
if err.kind() != std::io::ErrorKind::WouldBlock
|
||||
&& err.kind() != std::io::ErrorKind::Interrupted
|
||||
{
|
||||
return Err(err).with_context(|| {
|
||||
format!(
|
||||
"error during event_q.read_events protocol_error={:?}",
|
||||
self.display.borrow().protocol_error()
|
||||
)
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,193 +0,0 @@
|
||||
use crate::os::wayland::connection::WaylandConnection;
|
||||
use anyhow::anyhow;
|
||||
use smithay_client_toolkit as toolkit;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use toolkit::reexports::calloop::{LoopHandle, RegistrationToken};
|
||||
use toolkit::seat::keyboard::{
|
||||
map_keyboard_repeat, Event as KbEvent, KeyState, ModifiersState, RepeatKind,
|
||||
};
|
||||
use wayland_client::protocol::wl_keyboard::WlKeyboard;
|
||||
use wayland_client::protocol::wl_seat::WlSeat;
|
||||
use wayland_client::protocol::wl_surface::WlSurface;
|
||||
use wayland_client::Attached;
|
||||
use wezterm_input_types::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Inner {
|
||||
active_surface_id: u32,
|
||||
surface_to_window_id: HashMap<u32, usize>,
|
||||
by_name: HashMap<String, (WlKeyboard, RegistrationToken)>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn handle_event(&mut self, evt: KbEvent) {
|
||||
// Track the most recently entered window surface.
|
||||
// We manually filter to the keys of surface_to_window_id
|
||||
// because we may have auxilliary surfaces on our connection
|
||||
// that were created by the window decorations and we don't
|
||||
// want to suppress keyboard input if the user clicked in
|
||||
// the titlebar.
|
||||
if let KbEvent::Enter { surface, .. } = &evt {
|
||||
let id = surface.as_ref().id();
|
||||
if self.surface_to_window_id.contains_key(&id) {
|
||||
self.active_surface_id = id;
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(event) = KeyboardEvent::from_event(evt) {
|
||||
self.dispatch_to_window(event);
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_to_window(&mut self, evt: KeyboardEvent) {
|
||||
if let Some(window_id) = self.surface_to_window_id.get(&self.active_surface_id) {
|
||||
let mut evt = Some(evt);
|
||||
WaylandConnection::with_window_inner(*window_id, move |inner| {
|
||||
inner.handle_keyboard_event(evt.take().unwrap());
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct KeyboardDispatcher {
|
||||
inner: Arc<Mutex<Inner>>,
|
||||
}
|
||||
|
||||
impl KeyboardDispatcher {
|
||||
pub fn new() -> Self {
|
||||
let inner = Arc::new(Mutex::new(Inner::default()));
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
pub fn register(
|
||||
&self,
|
||||
loop_handle: LoopHandle<()>,
|
||||
seat: &Attached<WlSeat>,
|
||||
name: &str,
|
||||
) -> anyhow::Result<()> {
|
||||
let inner = Arc::clone(&self.inner);
|
||||
let pair = map_keyboard_repeat(
|
||||
loop_handle,
|
||||
&seat,
|
||||
None,
|
||||
// We use a Fixed rate here because if we use
|
||||
// RepeatKind::System and/or a rate higher than the 25
|
||||
// repeats per second specified here, the repeat machinery
|
||||
// in the toolkit generates synthetic results faster than
|
||||
// can be kept up with. I think there might be a scheduling
|
||||
// issue with the calloop crate. The issue manifests as
|
||||
// the key generating LOTs more presses even after it has
|
||||
// been released.
|
||||
// Capping it to a reasonable (but subjectively not ideal)
|
||||
// value avoids the application effectively hanging.
|
||||
RepeatKind::Fixed {
|
||||
rate: 25,
|
||||
delay: 500,
|
||||
},
|
||||
move |evt: KbEvent, _, _| {
|
||||
inner.lock().unwrap().handle_event(evt);
|
||||
},
|
||||
)
|
||||
.map_err(|e| anyhow!("Failed to configure keyboard callback: {:?}", e))?;
|
||||
|
||||
self.inner
|
||||
.lock()
|
||||
.unwrap()
|
||||
.by_name
|
||||
.insert(name.to_string(), pair);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn deregister(&self, loop_handle: LoopHandle<()>, name: &str) {
|
||||
if let Some((kbd, source)) = self.inner.lock().unwrap().by_name.remove(name) {
|
||||
kbd.release();
|
||||
loop_handle.remove(source);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_window(&self, window_id: usize, surface: &WlSurface) {
|
||||
let mut inner = self.inner.lock().unwrap();
|
||||
inner
|
||||
.surface_to_window_id
|
||||
.insert(surface.as_ref().id(), window_id);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum KeyboardEvent {
|
||||
Enter {
|
||||
serial: u32,
|
||||
},
|
||||
Leave {
|
||||
serial: u32,
|
||||
},
|
||||
Key {
|
||||
rawkey: u32,
|
||||
keysym: u32,
|
||||
is_down: bool,
|
||||
serial: u32,
|
||||
utf8: Option<String>,
|
||||
},
|
||||
Modifiers {
|
||||
modifiers: Modifiers,
|
||||
},
|
||||
}
|
||||
|
||||
impl KeyboardEvent {
|
||||
fn from_event(evt: KbEvent) -> Option<Self> {
|
||||
Some(match evt {
|
||||
KbEvent::Enter { serial, .. } => KeyboardEvent::Enter { serial },
|
||||
KbEvent::Leave { serial, .. } => KeyboardEvent::Leave { serial },
|
||||
KbEvent::Key {
|
||||
rawkey,
|
||||
keysym,
|
||||
state,
|
||||
serial,
|
||||
utf8,
|
||||
..
|
||||
} => KeyboardEvent::Key {
|
||||
rawkey,
|
||||
keysym,
|
||||
is_down: state == KeyState::Pressed,
|
||||
serial,
|
||||
utf8,
|
||||
},
|
||||
KbEvent::Repeat {
|
||||
rawkey,
|
||||
keysym,
|
||||
utf8,
|
||||
..
|
||||
} => KeyboardEvent::Key {
|
||||
rawkey,
|
||||
keysym,
|
||||
is_down: true,
|
||||
serial: 0,
|
||||
utf8,
|
||||
},
|
||||
KbEvent::Modifiers { modifiers } => KeyboardEvent::Modifiers {
|
||||
modifiers: modifier_keys(modifiers),
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn modifier_keys(state: ModifiersState) -> Modifiers {
|
||||
let mut mods = Modifiers::NONE;
|
||||
if state.ctrl {
|
||||
mods |= Modifiers::CTRL;
|
||||
}
|
||||
if state.alt {
|
||||
mods |= Modifiers::ALT;
|
||||
}
|
||||
if state.shift {
|
||||
mods |= Modifiers::SHIFT;
|
||||
}
|
||||
if state.logo {
|
||||
mods |= Modifiers::SUPER;
|
||||
}
|
||||
mods
|
||||
}
|
||||
@@ -6,5 +6,4 @@ pub use self::window::*;
|
||||
pub use connection::*;
|
||||
mod copy_and_paste;
|
||||
mod frame;
|
||||
mod keyboard;
|
||||
mod pointer;
|
||||
+137
-63
@@ -1,15 +1,15 @@
|
||||
use super::copy_and_paste::*;
|
||||
use super::frame::{ConceptConfig, ConceptFrame};
|
||||
use super::keyboard::KeyboardEvent;
|
||||
use super::pointer::*;
|
||||
use crate::connection::ConnectionOps;
|
||||
use crate::os::wayland::connection::WaylandConnection;
|
||||
use crate::os::xkeysyms::keysym_to_keycode;
|
||||
use crate::os::x11::keyboard::Keyboard;
|
||||
use crate::{
|
||||
Clipboard, Connection, Dimensions, MouseCursor, Point, ScreenPoint, Window, WindowEvent,
|
||||
WindowEventReceiver, WindowEventSender, WindowOps,
|
||||
};
|
||||
use anyhow::{anyhow, bail, Context};
|
||||
use async_io::Timer;
|
||||
use async_trait::async_trait;
|
||||
use config::ConfigHandle;
|
||||
use filedescriptor::FileDescriptor;
|
||||
@@ -24,16 +24,88 @@ use std::io::{Read, Write};
|
||||
use std::os::unix::io::{AsRawFd, FromRawFd};
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use toolkit::get_surface_scale_factor;
|
||||
use toolkit::reexports::client::protocol::wl_data_source::Event as DataSourceEvent;
|
||||
use toolkit::reexports::client::protocol::wl_surface::WlSurface;
|
||||
use toolkit::window::{Event, State};
|
||||
use wayland_client::protocol::wl_data_device_manager::WlDataDeviceManager;
|
||||
use wayland_client::protocol::wl_keyboard::{Event as WlKeyboardEvent, KeyState};
|
||||
use wayland_egl::{is_available as egl_is_available, WlEglSurface};
|
||||
use wezterm_font::FontConfiguration;
|
||||
use wezterm_input_types::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct KeyRepeatState {
|
||||
when: Instant,
|
||||
key: KeyEvent,
|
||||
}
|
||||
|
||||
impl KeyRepeatState {
|
||||
fn schedule(state: Arc<Mutex<Self>>, window_id: usize) {
|
||||
promise::spawn::spawn_into_main_thread(async move {
|
||||
let delay;
|
||||
let gap;
|
||||
{
|
||||
let conn = WaylandConnection::get().unwrap().wayland();
|
||||
delay = Duration::from_millis(*conn.key_repeat_delay.borrow() as u64);
|
||||
gap = Duration::from_millis(1000 / *conn.key_repeat_rate.borrow() as u64);
|
||||
}
|
||||
|
||||
let mut initial = true;
|
||||
Timer::after(delay).await;
|
||||
loop {
|
||||
{
|
||||
let handle = {
|
||||
let conn = WaylandConnection::get().unwrap().wayland();
|
||||
match conn.window_by_id(window_id) {
|
||||
Some(handle) => handle,
|
||||
None => return,
|
||||
}
|
||||
};
|
||||
|
||||
let inner = handle.borrow();
|
||||
|
||||
if inner.key_repeat.as_ref().map(|k| Arc::as_ptr(k))
|
||||
!= Some(Arc::as_ptr(&state))
|
||||
{
|
||||
// Key was released and/or some other key is doing
|
||||
// its own repetition now
|
||||
return;
|
||||
}
|
||||
|
||||
let mut st = state.lock().unwrap();
|
||||
let mut event = st.key.clone();
|
||||
|
||||
event.repeat_count = 1;
|
||||
|
||||
let mut elapsed = st.when.elapsed();
|
||||
if initial {
|
||||
elapsed -= delay;
|
||||
initial = false;
|
||||
}
|
||||
|
||||
// If our scheduling interval is longer than the repeat
|
||||
// gap, we need to inflate the repeat count to match
|
||||
// the intended rate
|
||||
while elapsed >= gap {
|
||||
event.repeat_count += 1;
|
||||
elapsed -= gap;
|
||||
}
|
||||
inner.events.try_send(WindowEvent::KeyEvent(event)).ok();
|
||||
|
||||
st.when = Instant::now();
|
||||
}
|
||||
|
||||
Timer::after(gap).await;
|
||||
}
|
||||
})
|
||||
.detach();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WaylandWindowInner {
|
||||
window_id: usize,
|
||||
events: WindowEventSender,
|
||||
surface: WlSurface,
|
||||
copy_and_paste: Arc<Mutex<CopyAndPaste>>,
|
||||
@@ -43,6 +115,7 @@ pub struct WaylandWindowInner {
|
||||
last_mouse_coords: Point,
|
||||
mouse_buttons: MouseButtons,
|
||||
modifiers: Modifiers,
|
||||
key_repeat: Option<Arc<Mutex<KeyRepeatState>>>,
|
||||
pending_event: Arc<Mutex<PendingEvent>>,
|
||||
pending_mouse: Arc<Mutex<PendingMouse>>,
|
||||
pending_first_configure: Option<async_channel::Sender<()>>,
|
||||
@@ -155,6 +228,9 @@ impl WaylandWindow {
|
||||
});
|
||||
}
|
||||
});
|
||||
conn.surface_to_window_id
|
||||
.borrow_mut()
|
||||
.insert(surface.as_ref().id(), window_id);
|
||||
|
||||
let dimensions = Dimensions {
|
||||
pixel_width: width,
|
||||
@@ -200,14 +276,14 @@ impl WaylandWindow {
|
||||
window.set_min_size(Some((32, 32)));
|
||||
|
||||
// window.new_seat(&conn.seat);
|
||||
conn.keyboard.add_window(window_id, &surface);
|
||||
|
||||
let copy_and_paste = CopyAndPaste::create();
|
||||
let pending_mouse = PendingMouse::create(window_id, ©_and_paste);
|
||||
|
||||
conn.pointer.add_window(&surface, &pending_mouse);
|
||||
|
||||
let inner = Rc::new(RefCell::new(WaylandWindowInner {
|
||||
window_id,
|
||||
key_repeat: None,
|
||||
copy_and_paste,
|
||||
events,
|
||||
surface: surface.detach(),
|
||||
@@ -247,73 +323,71 @@ unsafe impl HasRawWindowHandle for WaylandWindowInner {
|
||||
}
|
||||
|
||||
impl WaylandWindowInner {
|
||||
pub(crate) fn handle_keyboard_event(&mut self, evt: KeyboardEvent) {
|
||||
match evt {
|
||||
KeyboardEvent::Key {
|
||||
keysym,
|
||||
is_down,
|
||||
utf8,
|
||||
serial,
|
||||
rawkey: raw_code,
|
||||
} => {
|
||||
self.copy_and_paste
|
||||
.lock()
|
||||
.unwrap()
|
||||
.update_last_serial(serial);
|
||||
let raw_key = keysym_to_keycode(keysym);
|
||||
let (key, raw_key) = match utf8 {
|
||||
Some(text) if text.chars().count() == 1 => {
|
||||
(KeyCode::Char(text.chars().nth(0).unwrap()), raw_key)
|
||||
pub(crate) fn keyboard_event(&mut self, event: WlKeyboardEvent) {
|
||||
let conn = WaylandConnection::get().unwrap().wayland();
|
||||
let mut mapper = conn.keyboard_mapper.borrow_mut();
|
||||
let mapper = mapper.as_mut().expect("no keymap");
|
||||
|
||||
match event {
|
||||
WlKeyboardEvent::Enter { keys, .. } => {
|
||||
// Keys is bytes, but is really u32 keysyms
|
||||
let key_codes = keys
|
||||
.chunks_exact(4)
|
||||
.map(|c| u32::from_ne_bytes(c.try_into().unwrap()))
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
log::trace!("keyboard event: Enter with keys: {:?}", key_codes);
|
||||
|
||||
self.emit_focus(mapper, true);
|
||||
}
|
||||
WlKeyboardEvent::Leave { .. } => {
|
||||
self.emit_focus(mapper, false);
|
||||
}
|
||||
WlKeyboardEvent::Key { key, state, .. } => {
|
||||
if let Some(event) = mapper.process_wayland_key(key, state == KeyState::Pressed) {
|
||||
if event.key_is_down && mapper.wayland_key_repeats(key) {
|
||||
let rep = Arc::new(Mutex::new(KeyRepeatState {
|
||||
when: Instant::now(),
|
||||
key: event.clone(),
|
||||
}));
|
||||
self.key_repeat.replace(Arc::clone(&rep));
|
||||
KeyRepeatState::schedule(rep, self.window_id);
|
||||
} else {
|
||||
self.key_repeat.take();
|
||||
}
|
||||
Some(text) => (KeyCode::Composed(text), raw_key),
|
||||
None => match raw_key {
|
||||
Some(key) => (key, None),
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let (key, raw_key) = match (key, raw_key) {
|
||||
// Avoid eg: \x01 when we can use CTRL-A
|
||||
(KeyCode::Char(c), Some(raw)) if c.is_ascii_control() => (raw, None),
|
||||
// Avoid redundant key == raw_key
|
||||
(key, Some(raw)) if key == raw => (key, None),
|
||||
pair => pair,
|
||||
};
|
||||
|
||||
let modifiers = if raw_key.is_some() {
|
||||
Modifiers::NONE
|
||||
self.events.try_send(WindowEvent::KeyEvent(event)).ok();
|
||||
} else {
|
||||
self.modifiers
|
||||
};
|
||||
|
||||
let key_event = KeyEvent {
|
||||
key_is_down: is_down,
|
||||
key,
|
||||
raw_key,
|
||||
modifiers,
|
||||
raw_modifiers: self.modifiers,
|
||||
raw_code: Some(raw_code),
|
||||
repeat_count: 1,
|
||||
self.key_repeat.take();
|
||||
}
|
||||
.normalize_shift();
|
||||
self.events.try_send(WindowEvent::KeyEvent(key_event)).ok();
|
||||
}
|
||||
KeyboardEvent::Modifiers { modifiers } => self.modifiers = modifiers,
|
||||
// Clear the modifiers when we change focus, otherwise weird
|
||||
// things can happen. For instance, if we lost focus because
|
||||
// CTRL+SHIFT+N was pressed to spawn a new window, we'd be
|
||||
// left stuck with CTRL+SHIFT held down and the window would
|
||||
// be left in a broken state.
|
||||
KeyboardEvent::Enter { .. } => {
|
||||
self.modifiers = Modifiers::NONE;
|
||||
self.events.try_send(WindowEvent::FocusChanged(true)).ok();
|
||||
}
|
||||
KeyboardEvent::Leave { .. } => {
|
||||
self.modifiers = Modifiers::NONE;
|
||||
self.events.try_send(WindowEvent::FocusChanged(false)).ok();
|
||||
WlKeyboardEvent::Modifiers {
|
||||
mods_depressed,
|
||||
mods_latched,
|
||||
mods_locked,
|
||||
group,
|
||||
..
|
||||
} => {
|
||||
mapper.update_modifier_state(mods_depressed, mods_latched, mods_locked, group);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_focus(&mut self, mapper: &mut Keyboard, focused: bool) {
|
||||
// Clear the modifiers when we change focus, otherwise weird
|
||||
// things can happen. For instance, if we lost focus because
|
||||
// CTRL+SHIFT+N was pressed to spawn a new window, we'd be
|
||||
// left stuck with CTRL+SHIFT held down and the window would
|
||||
// be left in a broken state.
|
||||
|
||||
self.modifiers = Modifiers::NONE;
|
||||
mapper.update_modifier_state(0, 0, 0, 0);
|
||||
self.key_repeat.take();
|
||||
self.events
|
||||
.try_send(WindowEvent::FocusChanged(focused))
|
||||
.ok();
|
||||
}
|
||||
|
||||
pub(crate) fn dispatch_pending_mouse(&mut self) {
|
||||
// Dancing around the borrow checker and the call to self.refresh_frame()
|
||||
let pending_mouse = Arc::clone(&self.pending_mouse);
|
||||
|
||||
@@ -17,6 +17,36 @@ pub struct Keyboard {
|
||||
}
|
||||
|
||||
impl Keyboard {
|
||||
pub fn new_from_string(s: String) -> anyhow::Result<Self> {
|
||||
let context = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
|
||||
let keymap = xkb::Keymap::new_from_string(
|
||||
&context,
|
||||
s,
|
||||
xkbcommon::xkb::KEYMAP_FORMAT_TEXT_V1,
|
||||
xkb::KEYMAP_COMPILE_NO_FLAGS,
|
||||
)
|
||||
.ok_or_else(|| anyhow!("Failed to parse keymap state from file"))?;
|
||||
|
||||
let state = xkb::State::new(&keymap);
|
||||
let locale = query_lc_ctype()?;
|
||||
|
||||
let table = xkb::compose::Table::new_from_locale(
|
||||
&context,
|
||||
locale.to_str()?,
|
||||
xkb::compose::COMPILE_NO_FLAGS,
|
||||
)
|
||||
.map_err(|_| anyhow!("Failed to acquire compose table from locale"))?;
|
||||
let compose_state = xkb::compose::State::new(&table, xkb::compose::STATE_NO_FLAGS);
|
||||
|
||||
Ok(Self {
|
||||
context,
|
||||
device_id: -1,
|
||||
keymap: RefCell::new(keymap),
|
||||
state: RefCell::new(state),
|
||||
compose_state: RefCell::new(compose_state),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn new(connection: &xcb::Connection) -> anyhow::Result<(Keyboard, u8)> {
|
||||
connection.prefetch_extension_data(xcb::xkb::id());
|
||||
|
||||
@@ -102,10 +132,22 @@ impl Keyboard {
|
||||
Ok((kbd, first_ev))
|
||||
}
|
||||
|
||||
pub fn wayland_key_repeats(&self, code: u32) -> bool {
|
||||
self.keymap.borrow().key_repeats(code + 8)
|
||||
}
|
||||
|
||||
pub fn process_wayland_key(&self, code: u32, pressed: bool) -> Option<KeyEvent> {
|
||||
self.process_key_event_impl(code + 8, pressed)
|
||||
}
|
||||
|
||||
pub fn process_key_event(&self, xcb_ev: &xcb::KeyPressEvent) -> Option<KeyEvent> {
|
||||
let pressed = (xcb_ev.response_type() & !0x80) == xcb::KEY_PRESS;
|
||||
|
||||
let xcode = xkb::Keycode::from(xcb_ev.detail());
|
||||
self.process_key_event_impl(xcode, pressed)
|
||||
}
|
||||
|
||||
fn process_key_event_impl(&self, xcode: xkb::Keycode, pressed: bool) -> Option<KeyEvent> {
|
||||
let xsym = self.state.borrow().key_get_one_sym(xcode);
|
||||
|
||||
let ksym = if pressed {
|
||||
@@ -212,6 +254,23 @@ impl Keyboard {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn update_modifier_state(
|
||||
&self,
|
||||
mods_depressed: u32,
|
||||
mods_latched: u32,
|
||||
mods_locked: u32,
|
||||
group: u32,
|
||||
) {
|
||||
self.state.borrow_mut().update_mask(
|
||||
xkb::ModMask::from(mods_depressed),
|
||||
xkb::ModMask::from(mods_latched),
|
||||
xkb::ModMask::from(mods_locked),
|
||||
0,
|
||||
0,
|
||||
xkb::LayoutIndex::from(group),
|
||||
);
|
||||
}
|
||||
|
||||
pub fn update_state(&self, ev: &xcb::xkb::StateNotifyEvent) {
|
||||
self.state.borrow_mut().update_mask(
|
||||
xkb::ModMask::from(ev.base_mods()),
|
||||
|
||||
Reference in new issue
Block a user