GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: update keybindings of the keyboard hook on the fly
Lars Berger059a668d50d8
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rsindex 1f6b551d..73b115bd 100644--- a/packages/wm/src/common/platform/event_listener.rs+++ b/packages/wm/src/common/platform/event_listener.rs@@ -1,4 +1,3 @@-use anyhow::Result;use tokio::sync::mpsc::{self, UnboundedReceiver};use crate::{@@ -6,7 +5,7 @@ use crate::{user_config::{BindingModeConfig, KeybindingConfig, UserConfig},};-use super::{EventWindow, EventWindowOptions, NativeWindow};+use super::{EventWindow, NativeWindow};#[derive(Debug)]pub enum PlatformEvent {@@ -44,16 +43,14 @@ impl EventListener {/// Initializes listener for platform events.////// Returns an instance of `EventListener`.- pub fn start(config: &UserConfig) -> Result<Self> {+ pub fn start(config: &UserConfig) -> anyhow::Result<Self> {let (event_tx, event_rx) = mpsc::unbounded_channel();let event_window = EventWindow::new(event_tx,- EventWindowOptions {- keybindings: config.value.keybindings.clone(),- enable_mouse_events: config.value.general.focus_follows_cursor,- },- );+ config.value.keybindings.clone(),+ config.value.general.focus_follows_cursor,+ )?;Ok(Self {event_rx,diff --git a/packages/wm/src/common/platform/event_window.rs b/packages/wm/src/common/platform/event_window.rsindex f2321cbd..94af0552 100644--- a/packages/wm/src/common/platform/event_window.rs+++ b/packages/wm/src/common/platform/event_window.rs@@ -1,9 +1,8 @@use std::{- cell::OnceCell,+ sync::{Arc, Mutex, OnceLock},thread::{self, JoinHandle},};-use anyhow::Result;use tokio::sync::mpsc;use tracing::{error, info, warn};use windows::Win32::{@@ -21,41 +20,43 @@ use super::{KeyboardHook, MouseHook, Platform, PlatformEvent, WinEventHook,};-thread_local! {- static PLATFORM_EVENT_TX: OnceCell<mpsc::UnboundedSender<PlatformEvent>> = OnceCell::new();-}--#[derive(Debug)]-pub struct EventWindowOptions {- pub keybindings: Vec<KeybindingConfig>,- pub enable_mouse_events: bool,-}+/// Global instance of sender for platform events.+///+/// For use with window procedure.+static PLATFORM_EVENT_TX: OnceLock<mpsc::UnboundedSender<PlatformEvent>> =+ OnceLock::new();#[derive(Debug)]pub struct EventWindow {- window_thread: Option<JoinHandle<Result<()>>>,+ window_thread: Option<JoinHandle<anyhow::Result<()>>>,+ keyboard_hook: Arc<KeyboardHook>,}impl EventWindow {+ /// Creates an instance of `EventWindow`. Spawns a hidden window and+ /// emits platform events.+ ///+ /// Uses global state (i.e. `PLATFORM_EVENT_TX`) and should thus only+ /// ever be instantiated once in the application's lifetime.pub fn new(event_tx: mpsc::UnboundedSender<PlatformEvent>,- options: EventWindowOptions,- ) -> Self {- let keyboard_hook =- KeyboardHook::new(options.keybindings, event_tx.clone());+ keybindings: Vec<KeybindingConfig>,+ enable_mouse_events: bool,+ ) -> anyhow::Result<Self> {+ let keyboard_hook = KeyboardHook::new(keybindings, event_tx.clone())?;++ let keyboard_hook_clone = keyboard_hook.clone();let window_thread = thread::spawn(move || {- // Initialize the thread-local sender for platform events.- PLATFORM_EVENT_TX- .with(|cell| cell.set(event_tx.clone()))- .map_err(|_| {- anyhow::anyhow!("Platform event sender already set.")- })?;+ // Add the sender for platform events to global state.+ PLATFORM_EVENT_TX.set(event_tx.clone()).map_err(|_| {+ anyhow::anyhow!("Platform event sender already set.")+ })?;// Start hooks for listening to platform events.- keyboard_hook.start()?;+ keyboard_hook_clone.start()?;WinEventHook::start(event_tx.clone())?;- MouseHook::start(options.enable_mouse_events, event_tx)?;+ MouseHook::start(enable_mouse_events, event_tx)?;// Create a hidden window with a message loop on the current thread.let handle =@@ -67,26 +68,29 @@ impl EventWindow {Ok(())});- Self {+ Ok(Self {+ keyboard_hook,window_thread: Some(window_thread),- }+ })}pub fn update_keybindings(&mut self,keybindings: Vec<KeybindingConfig>,) {- todo!()+ self.keyboard_hook.update(keybindings);}pub fn enable_mouse_listener(&mut self, is_enabled: bool) {- todo!()+ // TODO}/// Destroys the event window and stops the message loop.pub fn destroy(&mut self) -> anyhow::Result<()> {info!("Shutting down event window.");+ let _ = self.keyboard_hook.stop();+// Wait for the spawned thread to finish.if let Some(window_thread) = self.window_thread.take() {Platform::kill_message_loop(&window_thread)?;@@ -118,26 +122,24 @@ pub extern "system" fn event_window_proc(wparam: WPARAM,lparam: LPARAM,) -> LRESULT {- PLATFORM_EVENT_TX.with(|event_tx| {- if let Some(event_tx) = event_tx.get() {- return match message {- WM_DISPLAYCHANGE | WM_SETTINGCHANGE | WM_DEVICECHANGE => {- handle_display_change_msg(message, wparam, event_tx)- }- WM_POWERBROADCAST => {- event_tx.send(PlatformEvent::PowerModeChanged).unwrap();- LRESULT(0)- }- WM_DESTROY => {- unsafe { PostQuitMessage(0) };- LRESULT(0)- }- _ => unsafe { DefWindowProcW(handle, message, wparam, lparam) },- };- }+ if let Some(event_tx) = PLATFORM_EVENT_TX.get() {+ return match message {+ WM_DISPLAYCHANGE | WM_SETTINGCHANGE | WM_DEVICECHANGE => {+ handle_display_change_msg(message, wparam, event_tx)+ }+ WM_POWERBROADCAST => {+ event_tx.send(PlatformEvent::PowerModeChanged).unwrap();+ LRESULT(0)+ }+ WM_DESTROY => {+ unsafe { PostQuitMessage(0) };+ LRESULT(0)+ }+ _ => unsafe { DefWindowProcW(handle, message, wparam, lparam) },+ };+ }- LRESULT(0)- })+ LRESULT(0)}/// Handles display change messages and emits the corresponding platformdiff --git a/packages/wm/src/common/platform/keyboard_hook.rs b/packages/wm/src/common/platform/keyboard_hook.rsindex ca745289..3294fa24 100644--- a/packages/wm/src/common/platform/keyboard_hook.rs+++ b/packages/wm/src/common/platform/keyboard_hook.rs@@ -1,11 +1,10 @@use std::{- cell::OnceCell,collections::HashMap,sync::{Arc, Mutex, OnceLock},};use tokio::sync::mpsc;-use tracing::warn;+use tracing::{error, warn};use windows::Win32::{Foundation::{LPARAM, LRESULT, WPARAM},UI::{@@ -36,63 +35,66 @@ const MODIFIER_KEYS: [u16; 6] = [VK_RMENU.0,];+#[derive(Debug)]pub struct ActiveKeybinding {pub vk_codes: Vec<u16>,pub config: KeybindingConfig,}+#[derive(Debug)]pub struct KeyboardHook {/// Sender to emit platform events.event_tx: mpsc::UnboundedSender<PlatformEvent>,/// Handle to the keyboard hook.- hook: HHOOK,+ hook: Arc<Mutex<HHOOK>>,/// Active keybindings grouped by trigger key. The trigger key is the/// final key in a key combination.- keybindings_by_trigger_key: HashMap<u16, Vec<ActiveKeybinding>>,+ keybindings_by_trigger_key:+ Arc<Mutex<HashMap<u16, Vec<ActiveKeybinding>>>>,}impl KeyboardHook {+ /// Creates an instance of `KeyboardHook`.pub fn new(keybindings: Vec<KeybindingConfig>,event_tx: mpsc::UnboundedSender<PlatformEvent>,- ) -> Arc<Self> {- Arc::new(Self {+ ) -> anyhow::Result<Arc<Self>> {+ let keyboard_hook = Arc::new(Self {event_tx,- hook: HHOOK::default(),- keybindings_by_trigger_key: Self::keybindings_by_trigger_key(- keybindings,- ),- })+ hook: Arc::new(Mutex::new(HHOOK::default())),+ keybindings_by_trigger_key: Arc::new(Mutex::new(+ Self::keybindings_by_trigger_key(keybindings),+ )),+ });++ KEYBOARD_HOOK+ .set(keyboard_hook.clone())+ .map_err(|_| anyhow::anyhow!("Keyboard hook already running."))?;++ Ok(keyboard_hook)}/// Starts a keyboard hook on the current thread.////// Assumes that a message loop is currently running.- pub fn start(self: &Arc<Self>) -> anyhow::Result<()> {- // Register the low-level keyboard hook.- let hook = unsafe {+ pub fn start(&self) -> anyhow::Result<()> {+ *self.hook.lock().unwrap() = unsafe {SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook_proc), None, 0)}?;- // self.hook = hook;-- KEYBOARD_HOOK.set(self.clone()).map_err(|_| {- anyhow::anyhow!("Keyboard hook already started on current thread.")- })?;-Ok(())}- pub fn update(&mut self, keybindings: Vec<KeybindingConfig>) {- self.keybindings_by_trigger_key =+ pub fn update(&self, keybindings: Vec<KeybindingConfig>) {+ *self.keybindings_by_trigger_key.lock().unwrap() =Self::keybindings_by_trigger_key(keybindings);}- pub fn stop(&mut self) {- self.keybindings_by_trigger_key.clear();- let _ = unsafe { UnhookWindowsHookEx(self.hook) };+ pub fn stop(&self) -> anyhow::Result<()> {+ unsafe { UnhookWindowsHookEx(*self.hook.lock().unwrap()) }?;+ Ok(())}fn keybindings_by_trigger_key(@@ -317,7 +319,12 @@ impl KeyboardHook {/// Returns `true` if the event should be blocked and not sent to other/// applications.fn handle_key_event(&self, vk_code: u16) -> bool {- match self.keybindings_by_trigger_key.get(&vk_code) {+ match self+ .keybindings_by_trigger_key+ .lock()+ .unwrap()+ .get(&vk_code)+ {// Forward the event if no keybindings exist for the trigger key.None => false,// Otherwise, check if there is a matching keybinding.@@ -426,7 +433,9 @@ impl KeyboardHook {impl Drop for KeyboardHook {fn drop(&mut self) {- self.stop();+ if let Err(err) = self.stop() {+ error!("Failed to gracefully shut down keyboard hook: {}", err);+ }}}