Skip to content

GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.

feat: start/stop mouse hook on config change

Lars Bergerf2e92b723e21
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rs
index 73b115bd..7d3c26b0 100644
--- a/packages/wm/src/common/platform/event_listener.rs
+++ b/packages/wm/src/common/platform/event_listener.rs
@@ -66,12 +66,9 @@ impl EventListener {
binding_modes: &Vec<&BindingModeConfig>,
) {
// TODO: Modify keybindings based on active binding modes.
- self
- .event_window
- .update_keybindings(config.value.keybindings.clone());
-
- self
- .event_window
- .enable_mouse_listener(config.value.general.focus_follows_cursor);
+ self.event_window.update(
+ config.value.keybindings.clone(),
+ config.value.general.focus_follows_cursor,
+ );
}
}
diff --git a/packages/wm/src/common/platform/event_window.rs b/packages/wm/src/common/platform/event_window.rs
index 94af0552..2bb63ddf 100644
--- a/packages/wm/src/common/platform/event_window.rs
+++ b/packages/wm/src/common/platform/event_window.rs
@@ -1,5 +1,5 @@
use std::{
- sync::{Arc, Mutex, OnceLock},
+ sync::{Arc, OnceLock},
thread::{self, JoinHandle},
};
@@ -28,8 +28,10 @@ static PLATFORM_EVENT_TX: OnceLock<mpsc::UnboundedSender<PlatformEvent>> =
#[derive(Debug)]
pub struct EventWindow {
- window_thread: Option<JoinHandle<anyhow::Result<()>>>,
keyboard_hook: Arc<KeyboardHook>,
+ mouse_hook: Arc<MouseHook>,
+ win_event_hook: Arc<WinEventHook>,
+ window_thread: Option<JoinHandle<anyhow::Result<()>>>,
}
impl EventWindow {
@@ -44,8 +46,12 @@ impl EventWindow {
enable_mouse_events: bool,
) -> anyhow::Result<Self> {
let keyboard_hook = KeyboardHook::new(keybindings, event_tx.clone())?;
+ let mouse_hook = MouseHook::new(event_tx.clone())?;
+ let win_event_hook = WinEventHook::new(event_tx.clone())?;
let keyboard_hook_clone = keyboard_hook.clone();
+ let mouse_hook_clone = mouse_hook.clone();
+ let win_event_hook_clone = win_event_hook.clone();
let window_thread = thread::spawn(move || {
// Add the sender for platform events to global state.
@@ -55,8 +61,11 @@ impl EventWindow {
// Start hooks for listening to platform events.
keyboard_hook_clone.start()?;
- WinEventHook::start(event_tx.clone())?;
- MouseHook::start(enable_mouse_events, event_tx)?;
+ win_event_hook_clone.start()?;
+
+ if enable_mouse_events {
+ mouse_hook_clone.start()?;
+ }
// Create a hidden window with a message loop on the current thread.
let handle =
@@ -70,26 +79,31 @@ impl EventWindow {
Ok(Self {
keyboard_hook,
+ mouse_hook,
+ win_event_hook,
window_thread: Some(window_thread),
})
}
- pub fn update_keybindings(
+ pub fn update(
&mut self,
keybindings: Vec<KeybindingConfig>,
+ enable_mouse_events: bool,
) {
self.keyboard_hook.update(keybindings);
- }
-
- pub fn enable_mouse_listener(&mut self, is_enabled: bool) {
- // TODO
+ match enable_mouse_events {
+ true => _ = self.mouse_hook.start(),
+ false => self.mouse_hook.stop(),
+ }
}
/// 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();
+ self.keyboard_hook.stop();
+ self.mouse_hook.stop();
+ self.win_event_hook.stop();
// Wait for the spawned thread to finish.
if let Some(window_thread) = self.window_thread.take() {
diff --git a/packages/wm/src/common/platform/keyboard_hook.rs b/packages/wm/src/common/platform/keyboard_hook.rs
index 3294fa24..9ea011f8 100644
--- a/packages/wm/src/common/platform/keyboard_hook.rs
+++ b/packages/wm/src/common/platform/keyboard_hook.rs
@@ -92,9 +92,13 @@ impl KeyboardHook {
Self::keybindings_by_trigger_key(keybindings);
}
- pub fn stop(&self) -> anyhow::Result<()> {
- unsafe { UnhookWindowsHookEx(*self.hook.lock().unwrap()) }?;
- Ok(())
+ /// Stops the low-level keyboard hook.
+ pub fn stop(&self) {
+ if let Err(err) =
+ unsafe { UnhookWindowsHookEx(*self.hook.lock().unwrap()) }
+ {
+ error!("Failed to unhook low-level keyboard hook: {}", err);
+ }
}
fn keybindings_by_trigger_key(
@@ -431,14 +435,6 @@ impl KeyboardHook {
}
}
-impl Drop for KeyboardHook {
- fn drop(&mut self) {
- if let Err(err) = self.stop() {
- error!("Failed to gracefully shut down keyboard hook: {}", err);
- }
- }
-}
-
extern "system" fn keyboard_hook_proc(
code: i32,
wparam: WPARAM,
diff --git a/packages/wm/src/common/platform/mouse_hook.rs b/packages/wm/src/common/platform/mouse_hook.rs
index 0d2c6128..75333533 100644
--- a/packages/wm/src/common/platform/mouse_hook.rs
+++ b/packages/wm/src/common/platform/mouse_hook.rs
@@ -1,17 +1,10 @@
-use std::{
- cell::OnceCell,
- sync::{
- atomic::{AtomicBool, AtomicU32, Ordering},
- Arc,
- },
+use std::sync::{
+ atomic::{AtomicBool, AtomicU32, Ordering},
+ Arc, Mutex, OnceLock,
};
-use crate::common::Point;
-
-use super::{MouseMoveEvent, PlatformEvent};
-use anyhow::Result;
use tokio::sync::mpsc;
-use tracing::warn;
+use tracing::{error, warn};
use windows::Win32::{
Foundation::{LPARAM, LRESULT, WPARAM},
UI::WindowsAndMessaging::{
@@ -21,19 +14,22 @@ use windows::Win32::{
},
};
-thread_local! {
- /// Thread-local for instance of `MouseHook`.
- ///
- /// For use with hook procedure.
- static MOUSE_HOOK: OnceCell<Arc<MouseHook>> = OnceCell::new();
-}
+use crate::common::Point;
+
+use super::{MouseMoveEvent, PlatformEvent};
+
+/// Global instance of `MouseHook`.
+///
+/// For use with hook procedure.
+static MOUSE_HOOK: OnceLock<Arc<MouseHook>> = OnceLock::new();
+#[derive(Debug)]
pub struct MouseHook {
/// Sender to emit platform events.
event_tx: mpsc::UnboundedSender<PlatformEvent>,
/// Handle to the mouse hook.
- hook: Option<HHOOK>,
+ hook: Arc<Mutex<HHOOK>>,
/// Whether left-click is currently pressed.
is_l_mouse_down: AtomicBool,
@@ -46,41 +42,36 @@ pub struct MouseHook {
}
impl MouseHook {
- /// Starts a mouse hook on the current thread.
- ///
- /// Assumes that a message loop is currently running.
- pub fn start(
- enabled: bool,
+ /// Creates an instance of `MouseHook`.
+ pub fn new(
event_tx: mpsc::UnboundedSender<PlatformEvent>,
- ) -> Result<Arc<MouseHook>> {
- let hook = match enabled {
- false => None,
- true => {
- let hook = unsafe {
- SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook_proc), None, 0)
- }?;
-
- Some(hook)
- }
- };
-
+ ) -> anyhow::Result<Arc<Self>> {
let mouse_hook = Arc::new(Self {
event_tx,
- hook,
+ hook: Arc::new(Mutex::new(HHOOK::default())),
is_l_mouse_down: AtomicBool::new(false),
is_r_mouse_down: AtomicBool::new(false),
last_event_time: AtomicU32::new(0),
});
MOUSE_HOOK
- .with(|cell| cell.set(mouse_hook.clone()))
- .map_err(|_| {
- anyhow::anyhow!("Mouse hook already started on current thread.")
- })?;
+ .set(mouse_hook.clone())
+ .map_err(|_| anyhow::anyhow!("Mouse hook already running."))?;
Ok(mouse_hook)
}
+ /// Starts a mouse hook on the current thread.
+ ///
+ /// Assumes that a message loop is currently running.
+ pub fn start(&self) -> anyhow::Result<()> {
+ *self.hook.lock().unwrap() = unsafe {
+ SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook_proc), None, 0)
+ }?;
+
+ Ok(())
+ }
+
fn handle_event(&self, event_type: u32, mouse_event: MSLLHOOKSTRUCT) {
// Throttle events so that there's a minimum of 50ms between each
// emission.
@@ -125,18 +116,12 @@ impl MouseHook {
}
/// Stops the low-level mouse hook.
- pub fn stop(&mut self) -> anyhow::Result<()> {
- if let Some(hook) = self.hook.take() {
- unsafe { UnhookWindowsHookEx(hook) }?;
+ pub fn stop(&self) {
+ if let Err(err) =
+ unsafe { UnhookWindowsHookEx(*self.hook.lock().unwrap()) }
+ {
+ error!("Failed to unhook low-level mouse hook: {}", err);
}
-
- Ok(())
- }
-}
-
-impl Drop for MouseHook {
- fn drop(&mut self) {
- let _ = self.stop();
}
}
@@ -152,11 +137,9 @@ extern "system" fn mouse_hook_proc(
if code >= 0 {
let mouse_event = unsafe { *(lparam.0 as *const MSLLHOOKSTRUCT) };
- MOUSE_HOOK.with(|hook| {
- if let Some(hook) = hook.get() {
- hook.handle_event(wparam.0 as u32, mouse_event);
- }
- });
+ if let Some(hook) = MOUSE_HOOK.get() {
+ hook.handle_event(wparam.0 as u32, mouse_event);
+ }
}
unsafe { CallNextHookEx(None, code, wparam, lparam) }
diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rs
index 584202d3..7e85720a 100644
--- a/packages/wm/src/common/platform/platform.rs
+++ b/packages/wm/src/common/platform/platform.rs
@@ -23,9 +23,9 @@ use windows::{
PostThreadMessageW, RegisterClassW, SetCursorPos,
SystemParametersInfoW, TranslateMessage, WindowFromPoint,
ANIMATIONINFO, CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, GA_ROOT,
- MSG, PM_REMOVE, SPI_GETANIMATION, SPI_SETANIMATION, SW_NORMAL,
- SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, WM_QUIT, WNDCLASSW, WNDPROC,
- WS_OVERLAPPEDWINDOW,
+ HWND_MESSAGE, MSG, PM_REMOVE, SPI_GETANIMATION, SPI_SETANIMATION,
+ SW_NORMAL, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, WM_QUIT,
+ WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,
},
},
},
@@ -172,7 +172,7 @@ impl Platform {
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
- None,
+ HWND_MESSAGE,
None,
wnd_class.hInstance,
None,
diff --git a/packages/wm/src/common/platform/win_event_hook.rs b/packages/wm/src/common/platform/win_event_hook.rs
index 7157c3fc..3ecf3f9d 100644
--- a/packages/wm/src/common/platform/win_event_hook.rs
+++ b/packages/wm/src/common/platform/win_event_hook.rs
@@ -1,4 +1,4 @@
-use std::{cell::OnceCell, sync::Arc};
+use std::sync::{Arc, Mutex, OnceLock};
use anyhow::Result;
use tokio::sync::mpsc;
@@ -20,72 +20,40 @@ use windows::Win32::{
use super::{NativeWindow, PlatformEvent};
-thread_local! {
- /// Thread-local for instance of `WinEventHook`.
- ///
- /// For use with hook procedure.
- static WINDOW_EVENT_HOOK: OnceCell<Arc<WinEventHook>> = OnceCell::new();
-}
+/// Global instance of `WinEventHook`.
+///
+/// For use with hook procedure.
+static WIN_EVENT_HOOK: OnceLock<Arc<WinEventHook>> = OnceLock::new();
+#[derive(Debug)]
pub struct WinEventHook {
event_tx: mpsc::UnboundedSender<PlatformEvent>,
- hook_handles: Vec<HWINEVENTHOOK>,
+ hook_handles: Arc<Mutex<Vec<HWINEVENTHOOK>>>,
}
impl WinEventHook {
- /// Starts a window event hook on the current thread.
- ///
- /// Assumes that a message loop is currently running.
- pub fn start(
+ /// Creates an instance of `WinEventHook`.
+ pub fn new(
event_tx: mpsc::UnboundedSender<PlatformEvent>,
- ) -> Result<Arc<Self>> {
- let hook_handles = Self::hook_win_events()?;
-
- let window_event_hook = Arc::new(Self {
+ ) -> anyhow::Result<Arc<Self>> {
+ let win_event_hook = Arc::new(Self {
event_tx,
- hook_handles,
+ hook_handles: Arc::new(Mutex::new(Vec::new())),
});
- WINDOW_EVENT_HOOK
- .with(|cell| cell.set(window_event_hook.clone()))
- .map_err(|_| {
- anyhow::anyhow!(
- "Window event hook already started on current thread."
- )
- })?;
+ WIN_EVENT_HOOK.set(win_event_hook.clone()).map_err(|_| {
+ anyhow::anyhow!("Window event hook already running.")
+ })?;
- Ok(window_event_hook)
+ Ok(win_event_hook)
}
- fn handle_event(&self, event_type: u32, handle: isize) {
- let window = NativeWindow::new(handle);
-
- let platform_event = match event_type {
- EVENT_OBJECT_DESTROY => PlatformEvent::WindowDestroyed(window),
- EVENT_SYSTEM_FOREGROUND => PlatformEvent::WindowFocused(window),
- EVENT_OBJECT_HIDE | EVENT_OBJECT_CLOAKED => {
- PlatformEvent::WindowHidden(window)
- }
- EVENT_OBJECT_LOCATIONCHANGE => {
- PlatformEvent::WindowLocationChanged(window)
- }
- EVENT_SYSTEM_MINIMIZESTART => PlatformEvent::WindowMinimized(window),
- EVENT_SYSTEM_MINIMIZEEND => {
- PlatformEvent::WindowMinimizeEnded(window)
- }
- EVENT_SYSTEM_MOVESIZEEND => {
- PlatformEvent::WindowMovedOrResized(window)
- }
- EVENT_OBJECT_SHOW | EVENT_OBJECT_UNCLOAKED => {
- PlatformEvent::WindowShown(window)
- }
- EVENT_OBJECT_NAMECHANGE => PlatformEvent::WindowTitleChanged(window),
- _ => return,
- };
-
- if let Err(err) = self.event_tx.send(platform_event) {
- warn!("Failed to send platform event '{}'.", err);
- }
+ /// Starts a window event hook on the current thread.
+ ///
+ /// Assumes that a message loop is currently running.
+ pub fn start(&self) -> anyhow::Result<()> {
+ *self.hook_handles.lock().unwrap() = Self::hook_win_events()?;
+ Ok(())
}
/// Creates several window event hooks via `SetWinEventHook`.
@@ -136,9 +104,41 @@ impl WinEventHook {
}
}
+ /// Invoked by the hook procedure when a window event is received.
+ fn handle_event(&self, event_type: u32, handle: isize) {
+ let window = NativeWindow::new(handle);
+
+ let platform_event = match event_type {
+ EVENT_OBJECT_DESTROY => PlatformEvent::WindowDestroyed(window),
+ EVENT_SYSTEM_FOREGROUND => PlatformEvent::WindowFocused(window),
+ EVENT_OBJECT_HIDE | EVENT_OBJECT_CLOAKED => {
+ PlatformEvent::WindowHidden(window)
+ }
+ EVENT_OBJECT_LOCATIONCHANGE => {
+ PlatformEvent::WindowLocationChanged(window)
+ }
+ EVENT_SYSTEM_MINIMIZESTART => PlatformEvent::WindowMinimized(window),
+ EVENT_SYSTEM_MINIMIZEEND => {
+ PlatformEvent::WindowMinimizeEnded(window)
+ }
+ EVENT_SYSTEM_MOVESIZEEND => {
+ PlatformEvent::WindowMovedOrResized(window)
+ }
+ EVENT_OBJECT_SHOW | EVENT_OBJECT_UNCLOAKED => {
+ PlatformEvent::WindowShown(window)
+ }
+ EVENT_OBJECT_NAMECHANGE => PlatformEvent::WindowTitleChanged(window),
+ _ => return,
+ };
+
+ if let Err(err) = self.event_tx.send(platform_event) {
+ warn!("Failed to send platform event '{}'.", err);
+ }
+ }
+
/// Stops the window event hook and unhooks from all window events.
- pub fn stop(&mut self) {
- for hook_handle in self.hook_handles.drain(..) {
+ pub fn stop(&self) {
+ for hook_handle in self.hook_handles.lock().unwrap().drain(..) {
if let false = unsafe { UnhookWinEvent(hook_handle) }.as_bool() {
warn!("Failed to unhook window event.");
}
@@ -146,12 +146,6 @@ impl WinEventHook {
}
}
-impl Drop for WinEventHook {
- fn drop(&mut self) {
- self.stop();
- }
-}
-
/// Callback passed to `SetWinEventHook` to handle window events.
///
/// This function is called on selected window events, and forwards them
@@ -174,9 +168,7 @@ extern "system" fn window_event_hook_proc(
return;
}
- WINDOW_EVENT_HOOK.with(|hook| {
- if let Some(hook) = hook.get() {
- hook.handle_event(event_type, handle.0);
- }
- });
+ if let Some(hook) = WIN_EVENT_HOOK.get() {
+ hook.handle_event(event_type, handle.0);
+ }
}