GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: progress on keyboard hook
Lars Berger9123b4e9810c
diff --git a/Cargo.toml b/Cargo.tomlindex d0f060e8..e7f8ec3a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -23,5 +23,6 @@ windows = { version = "0.52", features = ["Win32_UI_Input_KeyboardAndMouse","Win32_UI_Input_Ime","Win32_UI_Shell_Common",+ "Win32_UI_TextServices","Win32_UI_WindowsAndMessaging",] }diff --git a/packages/wm/src/common/commands/sync_native_focus.rs b/packages/wm/src/common/commands/sync_native_focus.rsindex 1e581149..54cebbf6 100644--- a/packages/wm/src/common/commands/sync_native_focus.rs+++ b/packages/wm/src/common/commands/sync_native_focus.rs@@ -10,7 +10,7 @@ pub fn sync_native_focus(state: &mut WmState) -> anyhow::Result<()> {return Ok(());}- // Container that the WM believes should have focus.+ // Get the container that the WM believes should have focus.let focused_container =state.focused_container().context("No focused container.")?;@@ -22,7 +22,9 @@ pub fn sync_native_focus(state: &mut WmState) -> anyhow::Result<()> {// Set focus to the given window handle. If the container is a normal// window, then this will trigger a `PlatformEvent::WindowFocused` event.- let _ = native_window.set_foreground();+ if Platform::foreground_window() != native_window {+ let _ = native_window.set_foreground();+ }state.emit_event(WmEvent::NativeFocusSynced {focused_container: focused_container.clone(),diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rsindex 18bc941c..6721b2b8 100644--- a/packages/wm/src/common/platform/event_listener.rs+++ b/packages/wm/src/common/platform/event_listener.rs@@ -10,7 +10,7 @@ use crate::user_config::{BindingModeConfig, KeybindingConfig, UserConfig,};-use super::{EventWindow, NativeWindow};+use super::{EventWindow, EventWindowOptions, NativeWindow};#[derive(Debug)]pub enum PlatformEvent {@@ -43,8 +43,10 @@ impl EventListener {let event_window = EventWindow::new(event_tx,- config.value.keybindings.clone(),- config.value.general.focus_follows_cursor,+ EventWindowOptions {+ keybindings: config.value.keybindings.clone(),+ enable_mouse_events: config.value.general.focus_follows_cursor,+ },);Ok(Self {diff --git a/packages/wm/src/common/platform/event_window.rs b/packages/wm/src/common/platform/event_window.rsindex cbe2d395..31ddfc56 100644--- a/packages/wm/src/common/platform/event_window.rs+++ b/packages/wm/src/common/platform/event_window.rs@@ -32,10 +32,13 @@ use windows::{use crate::user_config::KeybindingConfig;-use super::{NativeWindow, PlatformEvent};+use super::{+ set_local_keyboard_hook, KeyboardHook, NativeWindow, Platform,+ PlatformEvent,+};thread_local! {- static HOOK_EVENT_TX: OnceCell<mpsc::UnboundedSender<PlatformEvent>> = OnceCell::new();+ static PLATFORM_EVENT_TX: OnceCell<mpsc::UnboundedSender<PlatformEvent>> = OnceCell::new();}/// Callback passed to `SetWinEventHook` to handle window events.@@ -51,7 +54,7 @@ extern "system" fn event_hook_proc(_event_thread: u32,_event_time: u32,) {- HOOK_EVENT_TX.with(|event_tx| {+ PLATFORM_EVENT_TX.with(|event_tx| {if let Some(event_tx) = event_tx.get() {let is_window_event =id_object == OBJID_WINDOW.0 && id_child == 0 && handle != HWND(0);@@ -108,7 +111,7 @@ pub extern "system" fn event_window_proc(wparam: WPARAM,lparam: LPARAM,) -> LRESULT {- HOOK_EVENT_TX.with(|event_tx| {+ PLATFORM_EVENT_TX.with(|event_tx| {if let Some(event_tx) = event_tx.get() {return match message {WM_DISPLAYCHANGE | WM_SETTINGCHANGE | WM_DEVICECHANGE => {@@ -152,6 +155,12 @@ fn handle_display_change_msg(LRESULT(0)}+#[derive(Debug)]+pub struct EventWindowOptions {+ pub keybindings: Vec<KeybindingConfig>,+ pub enable_mouse_events: bool,+}+#[derive(Debug)]pub struct EventWindow {abort_tx: Option<oneshot::Sender<()>>,@@ -161,18 +170,26 @@ pub struct EventWindow {impl EventWindow {pub fn new(event_tx: mpsc::UnboundedSender<PlatformEvent>,- keybindings: Vec<KeybindingConfig>,- enable_mouse_listener: bool,+ options: EventWindowOptions,) -> Self {let (abort_tx, abort_rx) = oneshot::channel();let window_thread = thread::spawn(|| unsafe {- // Initialize the `HOOK_EVENT_TX` thread-local static.- HOOK_EVENT_TX.with(|cell| cell.set(event_tx)).unwrap();+ // 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.")+ })?;++ set_local_keyboard_hook(KeyboardHook::start(+ options.keybindings,+ event_tx,+ )?);let hook_handles = Self::hook_win_events()?;- Self::create_window(abort_rx)?;+ Platform::create_message_loop(abort_rx, Some(event_window_proc))?;// Unhook from all window events.for hook_handle in hook_handles {@@ -241,66 +258,12 @@ impl EventWindow {);if hook_handle.is_invalid() {- bail!("`SetWinEventHook` failed.");+ bail!("Failed to set window event hook.");}Ok(hook_handle)}- /// Creates the event window and starts a message loop.- unsafe fn create_window(- mut abort_rx: oneshot::Receiver<()>,- ) -> Result<HWND> {- let wnd_class = WNDCLASSW {- lpszClassName: w!("EventWindow"),- style: CS_HREDRAW | CS_VREDRAW,- lpfnWndProc: Some(event_window_proc),- ..Default::default()- };-- RegisterClassW(&wnd_class);-- let handle = CreateWindowExW(- Default::default(),- w!("EventWindow"),- w!("EventWindow"),- WS_OVERLAPPEDWINDOW,- CW_USEDEFAULT,- CW_USEDEFAULT,- CW_USEDEFAULT,- CW_USEDEFAULT,- None,- None,- wnd_class.hInstance,- None,- );-- if handle.0 == 0 {- bail!("`CreateWindowExW` failed.");- }-- let mut msg = MSG::default();-- loop {- // Check whether the abort signal has been received.- if abort_rx.try_recv().is_ok() {- if let Err(err) = DestroyWindow(handle) {- warn!("Failed to destroy event window '{}'.", err);- }- break;- }-- if GetMessageW(&mut msg, None, 0, 0).as_bool() {- TranslateMessage(&msg);- DispatchMessageW(&msg);- } else {- break;- }- }-- Ok(handle)- }-/// Destroys the event window and stops the message loop.pub fn destroy(&mut self) {if let Some(abort_tx) = self.abort_tx.take() {diff --git a/packages/wm/src/common/platform/keyboard_hook.rs b/packages/wm/src/common/platform/keyboard_hook.rsindex a30c3bc6..8e970889 100644--- a/packages/wm/src/common/platform/keyboard_hook.rs+++ b/packages/wm/src/common/platform/keyboard_hook.rs@@ -1,82 +1,148 @@use std::{cell::OnceCell, collections::HashMap};use tokio::sync::mpsc;+use tracing::warn;use windows::Win32::{- Foundation::{HINSTANCE, LPARAM, LRESULT, WPARAM},- UI::WindowsAndMessaging::{- CallNextHookEx, SetWindowsHookExW, UnhookWindowsHookEx, HHOOK,- KBDLLHOOKSTRUCT, WH_KEYBOARD_LL,+ Foundation::{LPARAM, LRESULT, WPARAM},+ UI::{+ Input::KeyboardAndMouse::{GetKeyboardLayout, VkKeyScanExW, VK_4},+ WindowsAndMessaging::{+ CallNextHookEx, SetWindowsHookExW, UnhookWindowsHookEx, HHOOK,+ KBDLLHOOKSTRUCT, WH_KEYBOARD_LL, WM_KEYDOWN, WM_SYSKEYDOWN,+ },},};+use crate::user_config::KeybindingConfig;++use super::PlatformEvent;+thread_local! {static KEYBOARD_HOOK: OnceCell<KeyboardHook> = OnceCell::new();}-pub struct Keybinding {- pub key_combination: String,- pub id: String,+pub fn set_local_keyboard_hook(hook: KeyboardHook) {+ let _ = KEYBOARD_HOOK.with(|cell| cell.set(hook));+}++pub struct ActiveKeybinding {+ pub vk_codes: Vec<u32>,+ pub config: KeybindingConfig,}pub struct KeyboardHook {+ /// Sender to emit platform events.+ event_tx: mpsc::UnboundedSender<PlatformEvent>,++ /// Handle to the keyboard hook.hook: HHOOK,- keybinding_map: HashMap<String, String>,- sender: mpsc::Sender<String>,- pub receiver: mpsc::Receiver<String>,++ /// Active keybindings grouped by trigger key. The trigger key is the+ /// final key in a key combination.+ keybindings_by_trigger_key: HashMap<u32, Vec<ActiveKeybinding>>,}impl KeyboardHook {pub fn new() -> Self {- let (sender, receiver) = mpsc::channel(32);-- Self {- hook: HHOOK(0),- keybinding_map: HashMap::new(),- sender,- receiver,- }+ todo!()}+ /// Starts a keyboard hook on the current thread.+ ///+ /// Assumes that a message loop is currently running.pub fn start(- &mut self,- keybindings: Vec<Keybinding>,- ) -> anyhow::Result<()> {- self.add_keybindings(keybindings);-+ keybindings: Vec<KeybindingConfig>,+ event_tx: mpsc::UnboundedSender<PlatformEvent>,+ ) -> anyhow::Result<Self> {// Register low-level keyboard hook.- unsafe {- self.hook = SetWindowsHookExW(- WH_KEYBOARD_LL,- Some(keyboard_hook_proc),- HINSTANCE(0),- 0,- )?;+ let hook = unsafe {+ SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook_proc), None, 0)?};- Ok(())+ Ok(Self {+ event_tx,+ hook,+ keybindings_by_trigger_key: Self::keybindings_by_trigger_key(+ keybindings,+ ),+ })}- pub fn update(&mut self, keybindings: Vec<Keybinding>) {- self.keybinding_map.clear();- self.add_keybindings(keybindings);+ pub fn update(&mut self, keybindings: Vec<KeybindingConfig>) {+ self.keybindings_by_trigger_key =+ Self::keybindings_by_trigger_key(keybindings);}pub fn stop(&mut self) {- self.keybinding_map.clear();+ self.keybindings_by_trigger_key.clear();let _ = unsafe { UnhookWindowsHookEx(self.hook) };}- fn add_keybindings(&mut self, keybindings: Vec<Keybinding>) {- for keybinding in keybindings {- self- .keybinding_map- .insert(keybinding.key_combination, keybinding.id);+ fn keybindings_by_trigger_key(+ keybindings: Vec<KeybindingConfig>,+ ) -> HashMap<u32, Vec<ActiveKeybinding>> {+ let mut keybinding_map = HashMap::new();++ for keybinding in &keybindings {+ for binding in &keybinding.bindings {+ let vk_codes = binding+ .split("+")+ .filter_map(|key| {+ let vk_code = Self::key_to_vk_code(key);++ if vk_code.is_none() {+ warn!("Unrecognized key on current keyboard '{}'.", key);+ }++ vk_code+ })+ .collect::<Vec<_>>();++ // Safety: A split string always has at least one element.+ let trigger_key = vk_codes.last().unwrap().clone();++ keybinding_map+ .entry(trigger_key)+ .or_insert_with(|| Vec::new()) // vec only created if needed.+ .push(ActiveKeybinding {+ vk_codes,+ config: keybinding.clone(),+ });+ }+ }++ keybinding_map+ }++ fn key_to_vk_code(key: &str) -> Option<u32> {+ match key {+ "ctrl" => Some(0x11),+ "alt" => Some(0x12),+ "shift" => Some(0x10),+ "win" => Some(0x5B),+ _ => {+ // TODO: Check if the key exists on the current keyboard layout.+ // let xx = unsafe { GetKeyboardLayout(0) };+ // unsafe { VkKeyScanExW(key, xx) as _ }+ None+ }}}- fn handle_key_event(&self, key_combination: &str) {- if let Some(id) = self.keybinding_map.get(key_combination) {- let _ = self.sender.try_send(id.clone());+ /// Emits a platform event if a keybinding should be triggered.+ ///+ /// Returns `true` if the event should be forwarded.+ fn handle_key_event(&self, vk_code: u32) -> bool {+ println!("Key event: {}", vk_code);++ match self.keybindings_by_trigger_key.get(&vk_code) {+ // Forward the event if no keybindings exist for the trigger key.+ None => true,+ Some(keybinding) => {+ // TODO: Emit platform event.+ // let _ = self.event_tx.send(keybinding.clone());+ false+ }}}}@@ -86,17 +152,28 @@ extern "system" fn keyboard_hook_proc(wparam: WPARAM,lparam: LPARAM,) -> LRESULT {- if code >= 0 {- let kb = unsafe { *(lparam.0 as *const KBDLLHOOKSTRUCT) };- let key_combination = format!("key_{}", kb.vkCode);-- // TODO: Implement proper key combination parsing and matching- KEYBOARD_HOOK.with(|hook| {- if let Some(hook) = hook.get() {- hook.handle_key_event(&key_combination);- }- });+ let should_ignore = code != 0+ || !(wparam.0 as u32 == WM_KEYDOWN+ || wparam.0 as u32 == WM_SYSKEYDOWN);++ // If the code is less than zero, the hook procedure must pass the hook+ // notification directly to other applications. We also only care about+ // keydown events.+ if should_ignore {+ return unsafe { CallNextHookEx(None, code, wparam, lparam) };}- unsafe { CallNextHookEx(HHOOK(0), code, wparam, lparam) }+ // Get struct with keyboard input event.+ let input = unsafe { *(lparam.0 as *const KBDLLHOOKSTRUCT) };++ KEYBOARD_HOOK.with(|hook| {+ let should_forward =+ hook.get().unwrap().handle_key_event(input.vkCode);++ if should_forward {+ unsafe { CallNextHookEx(None, code, wparam, lparam) }+ } else {+ LRESULT(1)+ }+ })}diff --git a/packages/wm/src/common/platform/native_monitor.rs b/packages/wm/src/common/platform/native_monitor.rsindex 058fa8d0..b56fc334 100644--- a/packages/wm/src/common/platform/native_monitor.rs+++ b/packages/wm/src/common/platform/native_monitor.rs@@ -83,7 +83,7 @@ fn available_monitor_handles() -> anyhow::Result<Vec<MonitorHandle>> {/// Callback passed to `EnumDisplayMonitors` to get all available monitor/// handles.-unsafe extern "system" fn available_monitor_handles_proc(+extern "system" fn available_monitor_handles_proc(handle: MonitorHandle,_hdc: HDC,_clip: *mut RECT,diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rsindex b0527a08..62457662 100644--- a/packages/wm/src/common/platform/platform.rs+++ b/packages/wm/src/common/platform/platform.rs@@ -1,7 +1,14 @@use std::sync::Arc;-use tokio::sync::Mutex;-use windows::Win32::UI::WindowsAndMessaging::SetCursorPos;+use anyhow::bail;+use tokio::sync::{oneshot, Mutex};+use tracing::warn;+use windows::core::w;+use windows::Win32::UI::WindowsAndMessaging::{+ CreateWindowExW, DestroyWindow, DispatchMessageW, GetMessageW,+ RegisterClassW, SetCursorPos, TranslateMessage, CS_HREDRAW, CS_VREDRAW,+ CW_USEDEFAULT, MSG, WNDCLASSW, WNDPROC, WS_OVERLAPPEDWINDOW,+};use windows::Win32::UI::{HiDpi::{SetProcessDpiAwarenessContext,@@ -14,9 +21,11 @@ use crate::user_config::UserConfig;use super::{native_monitor, native_window, EventListener, NativeMonitor,- NativeWindow, SingleInstance,+ NativeWindow, SingleInstance, WindowHandle,};+pub type WindowProcedure = WNDPROC;+pub struct Platform;impl Platform {@@ -76,4 +85,59 @@ impl Platform {Ok(())}++ /// Creates a message window and starts a message loop.+ pub unsafe fn create_message_loop(+ mut abort_rx: oneshot::Receiver<()>,+ window_procedure: WindowProcedure,+ ) -> anyhow::Result<WindowHandle> {+ let wnd_class = WNDCLASSW {+ lpszClassName: w!("MessageWindow"),+ style: CS_HREDRAW | CS_VREDRAW,+ lpfnWndProc: window_procedure,+ ..Default::default()+ };++ RegisterClassW(&wnd_class);++ let handle = CreateWindowExW(+ Default::default(),+ w!("MessageWindow"),+ w!("MessageWindow"),+ WS_OVERLAPPEDWINDOW,+ CW_USEDEFAULT,+ CW_USEDEFAULT,+ CW_USEDEFAULT,+ CW_USEDEFAULT,+ None,+ None,+ wnd_class.hInstance,+ None,+ );++ if handle.0 == 0 {+ bail!("Creation of message window failed.");+ }++ let mut msg = MSG::default();++ loop {+ // Check whether the abort signal has been received.+ if abort_rx.try_recv().is_ok() {+ if let Err(err) = DestroyWindow(handle) {+ warn!("Failed to destroy message window '{}'.", err);+ }+ break;+ }++ if GetMessageW(&mut msg, None, 0, 0).as_bool() {+ TranslateMessage(&msg);+ DispatchMessageW(&msg);+ } else {+ break;+ }+ }++ Ok(handle)+ }}diff --git a/packages/wm/src/windows/commands/manage_window_command.rs b/packages/wm/src/windows/commands/manage_window_command.rsindex 7565d828..dfae3dae 100644--- a/packages/wm/src/windows/commands/manage_window_command.rs+++ b/packages/wm/src/windows/commands/manage_window_command.rs@@ -53,13 +53,13 @@ pub fn manage_window(state.has_pending_focus_sync = true;// Sibling containers need to be redrawn if the window is tiling.- if window.state() == WindowState::Tiling {- state.add_container_to_redraw(- window.parent().context("No parent.")?.into(),- );- } else {- state.add_container_to_redraw(window.into());- }+ state.add_container_to_redraw(+ if window.state() == WindowState::Tiling {+ window.parent().context("No parent.")?+ } else {+ window.into()+ },+ );Ok(())}