diff --git a/Cargo.lock b/Cargo.lock index 00c8e5626..e3a30e961 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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]] diff --git a/window/Cargo.toml b/window/Cargo.toml index 6127438ab..f6ae26759 100644 --- a/window/Cargo.toml +++ b/window/Cargo.toml @@ -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" diff --git a/window/src/os/wayland/mod.rs b/window/src/os/wayland/mod.rs index 8f09023a7..81f8c22f8 100644 --- a/window/src/os/wayland/mod.rs +++ b/window/src/os/wayland/mod.rs @@ -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 diff --git a/window/src/os/wayland/seat.rs b/window/src/os/wayland/seat.rs new file mode 100644 index 000000000..236d6027f --- /dev/null +++ b/window/src/os/wayland/seat.rs @@ -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, _seat: WlSeat) { + todo!() + } + + fn new_capability( + &mut self, + _conn: &Connection, + qh: &QueueHandle, + 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, + _seat: WlSeat, + _capability: smithay_client_toolkit::seat::Capability, + ) { + todo!() + } + + fn remove_seat(&mut self, _conn: &Connection, _qh: &QueueHandle, _seat: WlSeat) { + todo!() + } +} + +impl KeyboardHandler for WaylandState { + fn enter( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _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, + _keyboard: &WlKeyboard, + _surface: &WlSurface, + serial: u32, + ) { + // TODO: inner input + *self.last_serial.borrow_mut() = serial; + } + + fn press_key( + &mut self, + _conn: &Connection, + _qh: &QueueHandle, + _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, + _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, + _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, + _keyboard: &wayland_client::protocol::wl_keyboard::WlKeyboard, + _keymap: smithay_client_toolkit::seat::keyboard::Keymap<'_>, + ) { + } +} diff --git a/window/src/os/wayland/state.rs b/window/src/os/wayland/state.rs index 06a93b962..574821486 100644 --- a/window/src/os/wayland/state.rs +++ b/window/src/os/wayland/state.rs @@ -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>>>, + pub(super) active_surface_id: RefCell>, + pub(super) last_serial: RefCell, + pub(super) keyboard: Option, + pub(super) keyboard_mapper: Option, + pub(super) key_repeat_delay: i32, + pub(super) key_repeat_rate: i32, + pub(super) keyboard_window_id: RefCell>, + shm: Shm, pub(super) mem_pool: RefCell, } @@ -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); diff --git a/window/src/os/wayland/window.rs b/window/src/os/wayland/window.rs index 06d181c01..1c423fc0d 100644 --- a/window/src/os/wayland/window.rs +++ b/window/src/os/wayland/window.rs @@ -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>, 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>)>, + pub(super) key_repeat: Option<(u32, Arc>)>, pub(crate) pending_event: Arc>, // pending_mouse: Arc>, pending_first_configure: Option>, frame_callback: Option, invalidated: bool, // font_config: Rc, - // text_cursor: Option, + _text_cursor: Option, // appearance: Appearance, config: ConfigHandle, // // cache the title for comparison to avoid spamming // // the compositor with updates that don't actually change it title: Option, - // // 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, gl_state: Option>, } @@ -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 {