Implement pressing a key

This commit is contained in:
Timmy Xiao authored and Wez Furlong committed 2024-02-03 14:55:29 -07:00
1 parent 8382c370f1
commit c66b1855fc
6 files changed
+354 -16

No files matched your search

Generated
+2
View File
@@ -5037,6 +5037,7 @@ dependencies = [
"log",
"memmap2 0.5.10",
"nix 0.26.4",
"pkg-config",
"thiserror",
"wayland-backend",
"wayland-client",
@@ -5044,6 +5045,7 @@ dependencies = [
"wayland-protocols",
"wayland-protocols-wlr",
"wayland-scanner",
"xkbcommon",
]
[[package]]
+1 -2
View File
@@ -81,11 +81,10 @@ xcb-imdkit = { version="0.3", git="https://github.com/wez/xcb-imdkit-rs.git", re
zbus = "3.14"
zvariant = "3.15"
smithay-client-toolkit = {version = "0.17.0", default-features=false, optional=true}
smithay-client-toolkit = {version = "0.17.0", features=["xkbcommon"], default-features=false, optional=true}
wayland-protocols = {version="0.30", optional=true}
wayland-client = {version="0.30", optional=true}
wayland-egl = {version="0.30", optional=true}
xcb-imdkit = { version="0.2", git="https://github.com/wez/xcb-imdkit-rs.git", branch="hangfix"}
[target.'cfg(target_os="macos")'.dependencies]
cocoa = "0.25"
+1
View File
@@ -12,6 +12,7 @@ pub use connection::*;
// mod frame;
// mod pointer;
mod state;
mod seat;
/// Returns the id of a wayland proxy object, suitable for using
/// a key into hash maps
+196
View File
@@ -0,0 +1,196 @@
use std::borrow::BorrowMut;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use smithay_client_toolkit::seat::keyboard::{KeyEvent, KeyboardHandler};
use smithay_client_toolkit::seat::{Capability, SeatHandler, SeatState};
use wayland_client::protocol::wl_keyboard::WlKeyboard;
use wayland_client::protocol::wl_seat::WlSeat;
use wayland_client::protocol::wl_surface::WlSurface;
use wayland_client::{Connection, QueueHandle};
use super::state::WaylandState;
use super::KeyRepeatState;
impl SeatHandler for WaylandState {
fn seat_state(&mut self) -> &mut SeatState {
&mut self.seat
}
fn new_seat(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _seat: WlSeat) {
todo!()
}
fn new_capability(
&mut self,
_conn: &Connection,
qh: &QueueHandle<Self>,
seat: WlSeat,
capability: smithay_client_toolkit::seat::Capability,
) {
if capability == Capability::Keyboard && self.keyboard.is_none() {
log::trace!("Setting keyboard capability");
let keyboard = self
.seat
.get_keyboard(qh, &seat, None)
.expect("Failed to create keyboard");
self.keyboard = Some(keyboard);
}
}
fn remove_capability(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_seat: WlSeat,
_capability: smithay_client_toolkit::seat::Capability,
) {
todo!()
}
fn remove_seat(&mut self, _conn: &Connection, _qh: &QueueHandle<Self>, _seat: WlSeat) {
todo!()
}
}
impl KeyboardHandler for WaylandState {
fn enter(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_keyboard: &WlKeyboard,
_surface: &WlSurface,
_serial: u32,
_raw: &[u32],
_keysyms: &[u32],
) {
// *self.active_surface_id.borrow_mut() = Some(surface.id());
// *self.last_serial.borrow_mut() = serial;
// if let Some(sud) = SurfaceUserData::try_from_wl(surface) {
// let window_id = sud.window_id;
// self.keyboard_window_id.borrow_mut().replace(window_id);
// // TODO: env with inner seems to IME stuff
// } else {
// log::warn!("{:?}, no known surface", "WlKeyboardEnter");
// }
//
// if let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() {
// // if let Some(win) = self.
// }
}
fn leave(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_keyboard: &WlKeyboard,
_surface: &WlSurface,
serial: u32,
) {
// TODO: inner input
*self.last_serial.borrow_mut() = serial;
}
fn press_key(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_keyboard: &WlKeyboard,
serial: u32,
event: KeyEvent,
) {
*self.last_serial.borrow_mut() = serial;
let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() else {
return;
};
let Some(mut win) = self.window_by_id(window_id) else {
return;
};
let inner = win.borrow_mut();
let events = &mut inner.as_ref().borrow_mut().events;
let mapper = self.keyboard_mapper.borrow_mut();
let mapper = mapper.as_mut().expect("no keymap");
// TODO: not sure if i should use keysym vs rawcode
let key = event.keysym;
let key_repeat = &mut inner.as_ref().borrow_mut().key_repeat;
if let Some(event) = mapper.process_wayland_key(key, true, events) {
let rep = Arc::new(Mutex::new(KeyRepeatState {
when: Instant::now(),
event,
}));
let kp = &mut inner.as_ref().borrow_mut().key_repeat;
kp.replace((key, Arc::clone(&rep)));
KeyRepeatState::schedule(rep, window_id);
} else if let Some((cur_key, _)) = key_repeat {
if *cur_key == key {
key_repeat.take();
}
}
}
fn release_key(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_keyboard: &WlKeyboard,
serial: u32,
event: KeyEvent,
) {
// TODO: copy paste of press_key except process is false
*self.last_serial.borrow_mut() = serial;
let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() else {
return;
};
let Some(mut win) = self.window_by_id(window_id) else {
return;
};
let inner = win.borrow_mut();
let events = &mut inner.as_ref().borrow_mut().events;
let mapper = self.keyboard_mapper.borrow_mut();
let mapper = mapper.as_mut().expect("no keymap");
// TODO: not sure if i should use keysym vs rawcode
let key = event.keysym;
let key_repeat = &mut inner.as_ref().borrow_mut().key_repeat;
if let Some(event) = mapper.process_wayland_key(key, false, events) {
let rep = Arc::new(Mutex::new(KeyRepeatState {
when: Instant::now(),
event,
}));
let kp = &mut inner.as_ref().borrow_mut().key_repeat;
kp.replace((key, Arc::clone(&rep)));
KeyRepeatState::schedule(rep, window_id);
} else if let Some((cur_key, _)) = key_repeat {
if *cur_key == key {
key_repeat.take();
}
}
}
fn update_modifiers(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_keyboard: &WlKeyboard,
serial: u32,
_modifiers: smithay_client_toolkit::seat::keyboard::Modifiers,
) {
*self.last_serial.borrow_mut() = serial;
}
fn update_keymap(
&mut self,
_conn: &Connection,
_qh: &QueueHandle<Self>,
_keyboard: &wayland_client::protocol::wl_keyboard::WlKeyboard,
_keymap: smithay_client_toolkit::seat::keyboard::Keymap<'_>,
) {
}
}
+28 -3
View File
@@ -5,18 +5,23 @@ use std::rc::Rc;
use smithay_client_toolkit::compositor::CompositorState;
use smithay_client_toolkit::output::{OutputHandler, OutputState};
use smithay_client_toolkit::registry::{ProvidesRegistryState, RegistryState};
use smithay_client_toolkit::seat::SeatState;
use smithay_client_toolkit::shell::xdg::XdgShell;
use smithay_client_toolkit::shm::slot::SlotPool;
use smithay_client_toolkit::shm::{Shm, ShmHandler};
use smithay_client_toolkit::{
delegate_compositor, delegate_output, delegate_registry, delegate_shm, delegate_xdg_shell,
delegate_xdg_window, registry_handlers,
delegate_compositor, delegate_keyboard, delegate_output, delegate_registry, delegate_seat,
delegate_shm, delegate_xdg_shell, delegate_xdg_window, registry_handlers,
};
use wayland_client::backend::ObjectId;
use wayland_client::globals::GlobalList;
use wayland_client::protocol::wl_keyboard::WlKeyboard;
use wayland_client::protocol::wl_output::WlOutput;
use wayland_client::protocol::wl_surface::WlSurface;
use wayland_client::{delegate_dispatch, Connection, QueueHandle};
use crate::x11::KeyboardWithFallback;
use super::{SurfaceUserData, WaylandWindowInner};
// We can't combine WaylandState and WaylandConnection together because
@@ -25,9 +30,18 @@ pub(super) struct WaylandState {
registry: RegistryState,
pub(super) output: OutputState,
pub(super) compositor: CompositorState,
pub(super) seat: SeatState,
pub(super) xdg: XdgShell,
pub(super) windows: RefCell<HashMap<usize, Rc<RefCell<WaylandWindowInner>>>>,
pub(super) active_surface_id: RefCell<Option<ObjectId>>,
pub(super) last_serial: RefCell<u32>,
pub(super) keyboard: Option<WlKeyboard>,
pub(super) keyboard_mapper: Option<KeyboardWithFallback>,
pub(super) key_repeat_delay: i32,
pub(super) key_repeat_rate: i32,
pub(super) keyboard_window_id: RefCell<Option<usize>>,
shm: Shm,
pub(super) mem_pool: RefCell<SlotPool>,
}
@@ -41,7 +55,15 @@ impl WaylandState {
output: OutputState::new(globals, qh),
compositor: CompositorState::bind(globals, qh)?,
windows: RefCell::new(HashMap::new()),
seat: SeatState::new(globals, qh),
xdg: XdgShell::bind(globals, qh)?,
active_surface_id: RefCell::new(None),
last_serial: RefCell::new(0),
keyboard: None,
keyboard_mapper: None,
key_repeat_rate: 25,
key_repeat_delay: 400,
keyboard_window_id: RefCell::new(None),
shm,
mem_pool: RefCell::new(mem_pool),
};
@@ -54,7 +76,7 @@ impl ProvidesRegistryState for WaylandState {
&mut self.registry
}
registry_handlers!(OutputState);
registry_handlers![OutputState, SeatState];
}
impl ShmHandler for WaylandState {
@@ -93,5 +115,8 @@ delegate_shm!(WaylandState);
delegate_output!(WaylandState);
delegate_compositor!(WaylandState);
delegate_seat!(WaylandState);
delegate_keyboard!(WaylandState);
delegate_xdg_shell!(WaylandState);
delegate_xdg_window!(WaylandState);
+126 -11
View File
@@ -3,8 +3,10 @@ use std::cell::RefCell;
use std::convert::TryInto;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::anyhow;
use async_io::Timer;
use async_trait::async_trait;
use config::ConfigHandle;
use promise::Future;
@@ -23,16 +25,107 @@ use wayland_client::protocol::wl_surface::WlSurface;
use wayland_client::{Connection as WConnection, Proxy};
use wayland_egl::{is_available as egl_is_available, WlEglSurface};
use wezterm_font::FontConfiguration;
use wezterm_input_types::WindowDecorations;
use wezterm_input_types::{Modifiers, WindowDecorations};
use crate::wayland::WaylandConnection;
use crate::{
Clipboard, Connection, ConnectionOps, Dimensions, MouseCursor, RequestedWindowGeometry,
ResolvedGeometry, Window, WindowEvent, WindowEventSender, WindowOps, WindowState,
Clipboard, Connection, ConnectionOps, Dimensions, MouseCursor, Rect, RequestedWindowGeometry,
ResolvedGeometry, Window, WindowEvent, WindowEventSender, WindowKeyEvent, WindowOps,
WindowState,
};
use super::state::WaylandState;
#[derive(Debug)]
pub(super) struct KeyRepeatState {
pub(super) when: Instant,
pub(super) event: WindowKeyEvent,
}
impl KeyRepeatState {
pub(super) 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();
let (rate, ddelay) = {
let wstate = conn.wayland_state.borrow();
(
wstate.key_repeat_rate as u64,
wstate.key_repeat_delay as u64,
)
};
if rate == 0 {
return;
}
delay = Duration::from_millis(ddelay);
gap = Duration::from_millis(1000 / rate);
}
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 mut inner = handle.borrow_mut();
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 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 {
repeat_count += 1;
elapsed -= gap;
}
let event = match st.event.clone() {
WindowKeyEvent::KeyEvent(mut key) => {
key.repeat_count = repeat_count;
WindowEvent::KeyEvent(key)
}
WindowKeyEvent::RawKeyEvent(mut raw) => {
raw.repeat_count = repeat_count;
WindowEvent::RawKeyEvent(raw)
}
};
inner.events.dispatch(event);
st.when = Instant::now();
}
Timer::after(gap).await;
}
})
.detach();
}
}
enum WaylandWindowEvent {
Close,
Request(WindowConfigure),
@@ -140,11 +233,16 @@ impl WaylandWindow {
resize_increments: None,
window_state: WindowState::default(),
_modifiers: Modifiers::NONE,
key_repeat: None,
pending_event,
pending_first_configure: Some(pending_first_configure),
frame_callback: None,
_text_cursor: None,
config,
title: None,
@@ -271,24 +369,24 @@ pub struct WaylandWindowInner {
// mouse_buttons: MouseButtons,
// hscroll_remainder: f64,
// vscroll_remainder: f64,
// modifiers: Modifiers,
_modifiers: Modifiers,
// leds: KeyboardLedStatus,
// key_repeat: Option<(u32, Arc<Mutex<KeyRepeatState>>)>,
pub(super) key_repeat: Option<(u32, Arc<Mutex<KeyRepeatState>>)>,
pub(crate) pending_event: Arc<Mutex<PendingEvent>>,
// pending_mouse: Arc<Mutex<PendingMouse>>,
pending_first_configure: Option<async_channel::Sender<()>>,
frame_callback: Option<WlCallback>,
invalidated: bool,
// font_config: Rc<FontConfiguration>,
// text_cursor: Option<Rect>,
_text_cursor: Option<Rect>,
// appearance: Appearance,
config: ConfigHandle,
// // cache the title for comparison to avoid spamming
// // the compositor with updates that don't actually change it
title: Option<String>,
// // wegl_surface is listed before gl_state because it
// // must be dropped before gl_state otherwise the underlying
// // libraries will segfault on shutdown
// wegl_surface is listed before gl_state because it
// must be dropped before gl_state otherwise the underlying
// libraries will segfault on shutdown
wegl_surface: Option<WlEglSurface>,
gl_state: Option<Rc<glium::backend::Context>>,
}
@@ -584,6 +682,20 @@ impl WaylandWindowInner {
self.do_paint().ok();
}
}
// pub(crate) fn emit_focus(&mut self, mapper: &mut KeyboardWithFallback, 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.dispatch(WindowEvent::FocusChanged(focused));
// self.text_cursor.take();
// }
}
impl WaylandState {
@@ -716,14 +828,17 @@ impl WindowHandler for WaylandState {
pub(super) struct SurfaceUserData {
surface_data: SurfaceData,
window_id: usize,
pub(super) window_id: usize,
}
impl SurfaceUserData {
pub(crate) fn from_wl(wl: &WlSurface) -> &Self {
pub(super) fn from_wl(wl: &WlSurface) -> &Self {
wl.data()
.expect("User data should be associated with WlSurface")
}
pub(super) fn try_from_wl(wl: &WlSurface) -> Option<&SurfaceUserData> {
wl.data()
}
}
impl SurfaceDataExt for SurfaceUserData {