Skip to content

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

feat: separate out win event hook; create mouse hook; add handlers for window focus + hidden events

Lars Berger627d8aa58cad
diff --git a/packages/wm/src/common/events/handle_window_focused.rs b/packages/wm/src/common/events/handle_window_focused.rs
new file mode 100644
index 00000000..ce429368
--- /dev/null
+++ b/packages/wm/src/common/events/handle_window_focused.rs
@@ -0,0 +1,71 @@
+use tracing::info;
+
+use crate::{
+ common::{
+ commands::sync_native_focus, platform::NativeWindow, DisplayState,
+ },
+ containers::{commands::set_focused_descendant, Container},
+ user_config::UserConfig,
+ windows::traits::WindowGetters,
+ wm_event::WmEvent,
+ wm_state::WmState,
+};
+
+pub fn handle_window_focused(
+ native_window: NativeWindow,
+ state: &mut WmState,
+ config: &UserConfig,
+) -> anyhow::Result<()> {
+ let found_window = state.window_from_native(&native_window);
+
+ if let Some(window) = found_window {
+ // Ignore event if window is being hidden by the WM.
+ if window.display_state() == DisplayState::Hiding {
+ return Ok(());
+ }
+
+ // TODO: Log window details.
+ info!("Window focused");
+
+ // Focus is already set to the WM's focused container.
+ if state.focused_container() == Some(window.clone().into()) {
+ info!("already focused {:?}", state.root_container.clone());
+ return Ok(());
+ }
+
+ // Handle overriding focus on close/minimize. After a window is closed
+ // or minimized, the OS or the closed application might automatically
+ // switch focus to a different window. To force focus to go to the WM's
+ // target focus container, we reassign any focus events 100ms after
+ // close/minimize. This will cause focus to briefly flicker to the OS
+ // focus target and then to the WM's focus target.
+ if state
+ .unmanaged_or_minimized_timestamp
+ .map(|time| time.elapsed().as_millis() < 100)
+ .unwrap_or(false)
+ {
+ info!("Overriding native focus.");
+ sync_native_focus(state)?;
+ return Ok(());
+ }
+
+ // Handle focus events from windows on hidden workspaces. For example,
+ // if Discord is forcefully shown by the OS when it's on a hidden
+ // workspace, switch focus to Discord's workspace.
+ if window.clone().display_state() == DisplayState::Hidden {
+ // TODO: Log window details.
+ info!("Focusing off-screen window");
+ // TODO: Focus the workspace of the hidden window.
+ return Ok(());
+ }
+
+ // Update the WM's focus state.
+ set_focused_descendant(window.clone().into(), None, state);
+
+ state.emit_event(WmEvent::FocusChanged {
+ focused_container: Into::<Container>::into(window).clone(),
+ })
+ }
+
+ Ok(())
+}
diff --git a/packages/wm/src/common/events/handle_window_hidden.rs b/packages/wm/src/common/events/handle_window_hidden.rs
new file mode 100644
index 00000000..19986e2d
--- /dev/null
+++ b/packages/wm/src/common/events/handle_window_hidden.rs
@@ -0,0 +1,49 @@
+use tracing::info;
+
+use crate::{
+ common::{
+ commands::sync_native_focus, platform::NativeWindow, DisplayState,
+ },
+ containers::commands::redraw,
+ user_config::UserConfig,
+ windows::{commands::unmanage_window, traits::WindowGetters},
+ wm_state::WmState,
+};
+
+pub fn handle_window_hidden(
+ native_window: NativeWindow,
+ state: &mut WmState,
+ config: &UserConfig,
+) -> anyhow::Result<()> {
+ // TODO: Refresh monitor state.
+ if native_window.is_app_bar() {
+ state.app_bar_windows.retain(|w| w != &native_window);
+ return Ok(());
+ }
+
+ let found_window = state.window_from_native(&native_window);
+
+ if let Some(window) = found_window {
+ // TODO: Log window details.
+ info!("Window hidden");
+
+ // Update the display state.
+ if window.display_state() == DisplayState::Hiding {
+ window.set_display_state(DisplayState::Hidden);
+ return Ok(());
+ }
+
+ // Unmanage the window if it's not in a display state transition. Also,
+ // since window events are not 100% guaranteed to be in correct order,
+ // we need to ignore events where the window is not actually hidden.
+ if window.display_state() == DisplayState::Shown
+ && !window.native().is_visible()
+ {
+ unmanage_window(window, state)?;
+ redraw(state, config)?;
+ sync_native_focus(state)?;
+ }
+ }
+
+ Ok(())
+}
diff --git a/packages/wm/src/common/events/mod.rs b/packages/wm/src/common/events/mod.rs
index fee16bcc..4ff96a86 100644
--- a/packages/wm/src/common/events/mod.rs
+++ b/packages/wm/src/common/events/mod.rs
@@ -1,5 +1,9 @@
mod handle_window_destroyed;
+mod handle_window_focused;
+mod handle_window_hidden;
mod handle_window_shown;
pub use handle_window_destroyed::*;
+pub use handle_window_focused::*;
+pub use handle_window_hidden::*;
pub use handle_window_shown::*;
diff --git a/packages/wm/src/common/mod.rs b/packages/wm/src/common/mod.rs
index fb9b235c..6564a23c 100644
--- a/packages/wm/src/common/mod.rs
+++ b/packages/wm/src/common/mod.rs
@@ -4,6 +4,7 @@ mod display_state;
pub mod events;
mod focus_mode;
pub mod platform;
+mod point;
mod rect;
mod rect_delta;
mod tiling_direction;
@@ -12,6 +13,7 @@ mod units;
pub use direction::*;
pub use display_state::*;
pub use focus_mode::*;
+pub use point::*;
pub use rect::*;
pub use rect_delta::*;
pub use tiling_direction::*;
diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rs
index 6721b2b8..9a2e854a 100644
--- a/packages/wm/src/common/platform/event_listener.rs
+++ b/packages/wm/src/common/platform/event_listener.rs
@@ -6,8 +6,9 @@ use tokio::sync::{
Mutex,
};
-use crate::user_config::{
- BindingModeConfig, KeybindingConfig, UserConfig,
+use crate::{
+ common::Point,
+ user_config::{BindingModeConfig, KeybindingConfig, UserConfig},
};
use super::{EventWindow, EventWindowOptions, NativeWindow};
@@ -16,7 +17,7 @@ use super::{EventWindow, EventWindowOptions, NativeWindow};
pub enum PlatformEvent {
DisplaySettingsChanged,
KeybindingTriggered(KeybindingConfig),
- MouseMove,
+ MouseMove(MouseMoveEvent),
WindowDestroyed(NativeWindow),
WindowFocused(NativeWindow),
WindowHidden(NativeWindow),
@@ -28,6 +29,16 @@ pub enum PlatformEvent {
WindowTitleChanged(NativeWindow),
}
+#[derive(Debug, Clone)]
+pub struct MouseMoveEvent {
+ /// Location of mouse with 0,0 being the top-left corner of the primary
+ /// monitor.
+ pub point: Point,
+
+ /// Whether either left or right-click is currently pressed.
+ pub is_mouse_down: bool,
+}
+
pub struct EventListener {
pub event_rx: UnboundedReceiver<PlatformEvent>,
event_window: EventWindow,
diff --git a/packages/wm/src/common/platform/event_window.rs b/packages/wm/src/common/platform/event_window.rs
index 31ddfc56..99975956 100644
--- a/packages/wm/src/common/platform/event_window.rs
+++ b/packages/wm/src/common/platform/event_window.rs
@@ -3,158 +3,28 @@ use std::{
thread::{self, JoinHandle},
};
-use anyhow::{bail, Result};
+use anyhow::Result;
use tokio::sync::{mpsc, oneshot};
use tracing::warn;
-use windows::{
- core::w,
- Win32::{
- Foundation::{HWND, LPARAM, LRESULT, WPARAM},
- UI::{
- Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK},
- WindowsAndMessaging::{
- CreateWindowExW, DefWindowProcW, DestroyWindow, DispatchMessageW,
- GetMessageW, PostQuitMessage, RegisterClassW, TranslateMessage,
- CS_HREDRAW, CS_VREDRAW, CW_USEDEFAULT, DBT_DEVNODES_CHANGED,
- EVENT_OBJECT_CLOAKED, EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE,
- EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE,
- EVENT_OBJECT_SHOW, EVENT_OBJECT_UNCLOAKED,
- EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_MINIMIZEEND,
- EVENT_SYSTEM_MINIMIZESTART, EVENT_SYSTEM_MOVESIZEEND, MSG,
- OBJID_WINDOW, SPI_ICONVERTICALSPACING, SPI_SETWORKAREA,
- WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS, WM_DESTROY,
- WM_DEVICECHANGE, WM_DISPLAYCHANGE, WM_SETTINGCHANGE, WNDCLASSW,
- WS_OVERLAPPEDWINDOW,
- },
- },
+use windows::Win32::{
+ Foundation::{HWND, LPARAM, LRESULT, WPARAM},
+ UI::WindowsAndMessaging::{
+ DefWindowProcW, PostQuitMessage, DBT_DEVNODES_CHANGED,
+ SPI_ICONVERTICALSPACING, SPI_SETWORKAREA, WM_DESTROY, WM_DEVICECHANGE,
+ WM_DISPLAYCHANGE, WM_SETTINGCHANGE,
},
};
use crate::user_config::KeybindingConfig;
use super::{
- set_local_keyboard_hook, KeyboardHook, NativeWindow, Platform,
- PlatformEvent,
+ KeyboardHook, MouseHook, Platform, PlatformEvent, WinEventHook,
};
thread_local! {
static PLATFORM_EVENT_TX: OnceCell<mpsc::UnboundedSender<PlatformEvent>> = OnceCell::new();
}
-/// Callback passed to `SetWinEventHook` to handle window events.
-///
-/// This function is called on selected window events, and forwards them
-/// through an MPSC channel for the WM to process.
-extern "system" fn event_hook_proc(
- _hook: HWINEVENTHOOK,
- event: u32,
- handle: HWND,
- id_object: i32,
- id_child: i32,
- _event_thread: u32,
- _event_time: u32,
-) {
- 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);
-
- // Check whether the event is associated with a window object instead
- // of a UI control.
- if !is_window_event {
- return;
- }
-
- let window = NativeWindow::new(handle);
-
- let platform_event = match event {
- 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) = event_tx.send(platform_event) {
- warn!("Failed to send platform event '{}'.", err);
- }
- }
- });
-}
-
-/// Window procedure for the event window.
-///
-/// Handles messages for the event window, and forwards display change
-/// events through an MPSC channel for the WM to process.
-pub extern "system" fn event_window_proc(
- handle: HWND,
- message: u32,
- 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_DESTROY => {
- unsafe { PostQuitMessage(0) };
- LRESULT(0)
- }
- _ => unsafe { DefWindowProcW(handle, message, wparam, lparam) },
- };
- }
-
- LRESULT(0)
- })
-}
-
-/// Handles display change messages and emits the corresponding platform
-/// event through an MPSC channel.
-fn handle_display_change_msg(
- message: u32,
- wparam: WPARAM,
- event_tx: &mpsc::UnboundedSender<PlatformEvent>,
-) -> LRESULT {
- let should_emit_event = match message {
- WM_SETTINGCHANGE => {
- wparam.0 as u32 == SPI_SETWORKAREA.0
- || wparam.0 as u32 == SPI_ICONVERTICALSPACING.0
- }
- WM_DEVICECHANGE => wparam.0 as u32 == DBT_DEVNODES_CHANGED,
- _ => true,
- };
-
- if should_emit_event {
- let event = PlatformEvent::DisplaySettingsChanged;
- if let Err(err) = event_tx.send(event) {
- warn!("Failed to send platform event '{}'.", err);
- }
- }
-
- LRESULT(0)
-}
-
#[derive(Debug)]
pub struct EventWindowOptions {
pub keybindings: Vec<KeybindingConfig>,
@@ -182,22 +52,13 @@ impl EventWindow {
anyhow::anyhow!("Platform event sender already set.")
})?;
- set_local_keyboard_hook(KeyboardHook::start(
- options.keybindings,
- event_tx,
- )?);
-
- let hook_handles = Self::hook_win_events()?;
+ // Start hooks for listening to platform events.
+ KeyboardHook::start(options.keybindings, event_tx.clone())?;
+ WinEventHook::start(event_tx.clone())?;
+ MouseHook::start(event_tx)?;
+ // Create a hidden window with a message loop on the current thread.
Platform::create_message_loop(abort_rx, Some(event_window_proc))?;
-
- // Unhook from all window events.
- for hook_handle in hook_handles {
- if let false = UnhookWinEvent(hook_handle).as_bool() {
- bail!("`UnhookWinEvent` failed.");
- }
- }
-
Ok(())
});
@@ -218,52 +79,6 @@ impl EventWindow {
todo!()
}
- /// Creates several window event hooks via `SetWinEventHook`.
- fn hook_win_events() -> Result<Vec<HWINEVENTHOOK>> {
- let event_ranges = [
- (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE),
- (EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE),
- (EVENT_SYSTEM_MINIMIZESTART, EVENT_SYSTEM_MINIMIZEEND),
- (EVENT_SYSTEM_MOVESIZEEND, EVENT_SYSTEM_MOVESIZEEND),
- (EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND),
- (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE),
- (EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED),
- ];
-
- // Create separate hooks for each event range. This is more performant
- // than creating a single hook for all events and filtering them.
- event_ranges
- .iter()
- .try_fold(Vec::new(), |mut handles, event_range| {
- let hook_handle =
- unsafe { Self::hook_win_event(event_range.0, event_range.1) }?;
- handles.push(hook_handle);
- Ok(handles)
- })
- }
-
- /// Creates a window hook for the specified event range.
- unsafe fn hook_win_event(
- event_min: u32,
- event_max: u32,
- ) -> Result<HWINEVENTHOOK> {
- let hook_handle = SetWinEventHook(
- event_min,
- event_max,
- None,
- Some(event_hook_proc),
- 0,
- 0,
- WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
- );
-
- if hook_handle.is_invalid() {
- bail!("Failed to set window event hook.");
- }
-
- Ok(hook_handle)
- }
-
/// Destroys the event window and stops the message loop.
pub fn destroy(&mut self) {
if let Some(abort_tx) = self.abort_tx.take() {
@@ -286,3 +101,57 @@ impl Drop for EventWindow {
self.destroy();
}
}
+
+/// Window procedure for the event window.
+///
+/// Handles messages for the event window, and forwards display change
+/// events through an MPSC channel for the WM to process.
+pub extern "system" fn event_window_proc(
+ handle: HWND,
+ message: u32,
+ 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_DESTROY => {
+ unsafe { PostQuitMessage(0) };
+ LRESULT(0)
+ }
+ _ => unsafe { DefWindowProcW(handle, message, wparam, lparam) },
+ };
+ }
+
+ LRESULT(0)
+ })
+}
+
+/// Handles display change messages and emits the corresponding platform
+/// event through an MPSC channel.
+fn handle_display_change_msg(
+ message: u32,
+ wparam: WPARAM,
+ event_tx: &mpsc::UnboundedSender<PlatformEvent>,
+) -> LRESULT {
+ let should_emit_event = match message {
+ WM_SETTINGCHANGE => {
+ wparam.0 as u32 == SPI_SETWORKAREA.0
+ || wparam.0 as u32 == SPI_ICONVERTICALSPACING.0
+ }
+ WM_DEVICECHANGE => wparam.0 as u32 == DBT_DEVNODES_CHANGED,
+ _ => true,
+ };
+
+ if should_emit_event {
+ let event = PlatformEvent::DisplaySettingsChanged;
+ if let Err(err) = event_tx.send(event) {
+ warn!("Failed to send platform event '{}'.", err);
+ }
+ }
+
+ LRESULT(0)
+}
diff --git a/packages/wm/src/common/platform/keyboard_hook.rs b/packages/wm/src/common/platform/keyboard_hook.rs
index 0333a9b9..febb26ca 100644
--- a/packages/wm/src/common/platform/keyboard_hook.rs
+++ b/packages/wm/src/common/platform/keyboard_hook.rs
@@ -1,4 +1,4 @@
-use std::{cell::OnceCell, collections::HashMap};
+use std::{cell::OnceCell, collections::HashMap, sync::Arc};
use tokio::sync::mpsc;
use tracing::warn;
@@ -21,7 +21,7 @@ thread_local! {
/// Thread-local for instance of `KeyboardHook`.
///
/// For use with hook procedure.
- static KEYBOARD_HOOK: OnceCell<KeyboardHook> = OnceCell::new();
+ static KEYBOARD_HOOK: OnceCell<Arc<KeyboardHook>> = OnceCell::new();
}
/// Available modifier keys.
@@ -34,10 +34,6 @@ const MODIFIER_KEYS: [u16; 6] = [
VK_RMENU.0,
];
-pub fn set_local_keyboard_hook(hook: KeyboardHook) {
- let _ = KEYBOARD_HOOK.with(|cell| cell.set(hook));
-}
-
pub struct ActiveKeybinding {
pub vk_codes: Vec<u16>,
pub config: KeybindingConfig,
@@ -56,29 +52,33 @@ pub struct KeyboardHook {
}
impl KeyboardHook {
- pub fn new() -> Self {
- todo!()
- }
-
/// Starts a keyboard hook on the current thread.
///
/// Assumes that a message loop is currently running.
pub fn start(
keybindings: Vec<KeybindingConfig>,
event_tx: mpsc::UnboundedSender<PlatformEvent>,
- ) -> anyhow::Result<Self> {
- // Register low-level keyboard hook.
+ ) -> anyhow::Result<Arc<Self>> {
+ // Register the low-level keyboard hook.
let hook = unsafe {
SetWindowsHookExW(WH_KEYBOARD_LL, Some(keyboard_hook_proc), None, 0)?
};
- Ok(Self {
+ let keyboard_hook = Arc::new(Self {
event_tx,
hook,
keybindings_by_trigger_key: Self::keybindings_by_trigger_key(
keybindings,
),
- })
+ });
+
+ KEYBOARD_HOOK
+ .with(|cell| cell.set(keyboard_hook.clone()))
+ .map_err(|_| {
+ anyhow::anyhow!("Keyboard hook already started on current thread.")
+ })?;
+
+ Ok(keyboard_hook)
}
pub fn update(&mut self, keybindings: Vec<KeybindingConfig>) {
@@ -116,7 +116,7 @@ impl KeyboardHook {
keybinding_map
.entry(trigger_key)
- .or_insert_with(|| Vec::new()) // vec only created if needed.
+ .or_insert_with(|| Vec::new())
.push(ActiveKeybinding {
vk_codes,
config: keybinding.clone(),
@@ -128,7 +128,7 @@ impl KeyboardHook {
}
fn key_to_vk_code(key: &str) -> Option<u16> {
- match key.to_lowercase().as_str() {
+ match key.to_lowercase().replace("_", "").as_str() {
"a" => Some(VK_A.0),
"b" => Some(VK_B.0),
"c" => Some(VK_C.0),
@@ -302,6 +302,7 @@ impl KeyboardHook {
return None;
}
+ // TODO: Check whether shift or alt is required for the key.
Some((vk_code & 0xFF) as u16)
}
}
@@ -312,8 +313,6 @@ 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 {
- 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 => false,
@@ -349,7 +348,8 @@ impl KeyboardHook {
let longest_keybinding = longest_keybinding.unwrap();
- // Get the modifier keys to reject based on the longest matching keybinding.
+ // Get the modifier keys to reject based on the longest matching
+ // keybinding.
let mut modifier_keys_to_reject =
MODIFIER_KEYS.iter().filter(|&&modifier_key| {
!longest_keybinding.vk_codes.contains(&modifier_key)
@@ -419,6 +419,12 @@ impl KeyboardHook {
}
}
+impl Drop for KeyboardHook {
+ fn drop(&mut self) {
+ self.stop();
+ }
+}
+
extern "system" fn keyboard_hook_proc(
code: i32,
wparam: WPARAM,
diff --git a/packages/wm/src/common/platform/mod.rs b/packages/wm/src/common/platform/mod.rs
index 986e10ff..df73222b 100644
--- a/packages/wm/src/common/platform/mod.rs
+++ b/packages/wm/src/common/platform/mod.rs
@@ -1,15 +1,19 @@
mod event_listener;
mod event_window;
mod keyboard_hook;
+mod mouse_hook;
mod native_monitor;
mod native_window;
mod platform;
mod single_instance;
+mod win_event_hook;
pub use event_listener::*;
pub use event_window::*;
pub use keyboard_hook::*;
+pub use mouse_hook::*;
pub use native_monitor::*;
pub use native_window::*;
pub use platform::*;
pub use single_instance::*;
+pub use win_event_hook::*;
diff --git a/packages/wm/src/common/platform/mouse_hook.rs b/packages/wm/src/common/platform/mouse_hook.rs
new file mode 100644
index 00000000..5025cd88
--- /dev/null
+++ b/packages/wm/src/common/platform/mouse_hook.rs
@@ -0,0 +1,152 @@
+use std::{
+ cell::OnceCell,
+ sync::{Arc, Mutex},
+};
+
+use crate::common::Point;
+
+use super::{MouseMoveEvent, PlatformEvent};
+use anyhow::Result;
+use tokio::sync::mpsc;
+use tracing::warn;
+use windows::Win32::{
+ Foundation::{LPARAM, LRESULT, WPARAM},
+ UI::WindowsAndMessaging::{
+ CallNextHookEx, SetWindowsHookExW, UnhookWindowsHookEx, HHOOK,
+ MSLLHOOKSTRUCT, WH_MOUSE_LL, WM_LBUTTONDOWN, WM_LBUTTONUP,
+ WM_MOUSEMOVE, WM_RBUTTONDOWN, WM_RBUTTONUP,
+ },
+};
+
+thread_local! {
+ /// Thread-local for instance of `MouseHook`.
+ ///
+ /// For use with hook procedure.
+ static MOUSE_HOOK: OnceCell<Arc<Mutex<MouseHook>>> = OnceCell::new();
+}
+
+pub struct MouseHook {
+ /// Sender to emit platform events.
+ event_tx: mpsc::UnboundedSender<PlatformEvent>,
+
+ /// Handle to the mouse hook.
+ hook: HHOOK,
+
+ /// Whether left-click is currently pressed.
+ is_l_mouse_down: bool,
+
+ /// Whether right-click is currently pressed.
+ is_r_mouse_down: bool,
+
+ /// Timestamp of the last event emission.
+ last_event_time: u32,
+}
+
+impl MouseHook {
+ /// Starts a mouse hook on the current thread.
+ ///
+ /// Assumes that a message loop is currently running.
+ pub fn start(
+ event_tx: mpsc::UnboundedSender<PlatformEvent>,
+ ) -> Result<Arc<Mutex<MouseHook>>> {
+ let hook = unsafe {
+ SetWindowsHookExW(WH_MOUSE_LL, Some(mouse_hook_proc), None, 0)?
+ };
+
+ let mouse_hook = Arc::new(Mutex::new(Self {
+ event_tx,
+ hook,
+ is_l_mouse_down: false,
+ is_r_mouse_down: false,
+ last_event_time: 0,
+ }));
+
+ MOUSE_HOOK
+ .with(|cell| cell.set(mouse_hook.clone()))
+ .map_err(|_| {
+ anyhow::anyhow!("Mouse hook already started on current thread.")
+ })?;
+
+ Ok(mouse_hook)
+ }
+
+ fn handle_event(
+ &mut self,
+ event_type: u32,
+ mouse_event: MSLLHOOKSTRUCT,
+ ) {
+ // Throttle events so that there's a minimum of 50ms between each
+ // emission.
+ if mouse_event.time - self.last_event_time < 50 {
+ return;
+ }
+
+ match event_type {
+ WM_LBUTTONDOWN => {
+ self.is_l_mouse_down = true;
+ }
+ WM_LBUTTONUP => {
+ self.is_l_mouse_down = false;
+ }
+ WM_RBUTTONDOWN => {
+ self.is_r_mouse_down = true;
+ }
+ WM_RBUTTONUP => {
+ self.is_r_mouse_down = false;
+ }
+ WM_MOUSEMOVE => {
+ let event = MouseMoveEvent {
+ point: Point {
+ x: mouse_event.pt.x,
+ y: mouse_event.pt.y,
+ },
+ is_mouse_down: self.is_l_mouse_down || self.is_r_mouse_down,
+ };
+
+ if let Err(err) =
+ self.event_tx.send(PlatformEvent::MouseMove(event))
+ {
+ warn!("Failed to send platform event '{}'.", err);
+ };
+
+ self.last_event_time = mouse_event.time;
+ }
+ _ => {}
+ }
+ }
+
+ /// Stops the low-level mouse hook.
+ pub fn stop(&mut self) -> anyhow::Result<()> {
+ unsafe { UnhookWindowsHookEx(self.hook) }?;
+ Ok(())
+ }
+}
+
+impl Drop for MouseHook {
+ fn drop(&mut self) {
+ let _ = self.stop();
+ }
+}
+
+/// Callback function for the low-level mouse hook.
+///
+/// This function is called whenever a mouse event occurs, and it forwards
+/// the event through an MPSC channel for the WM to process.
+extern "system" fn mouse_hook_proc(
+ code: i32,
+ wparam: WPARAM,
+ lparam: LPARAM,
+) -> LRESULT {
+ if code >= 0 {
+ let mouse_event = unsafe { *(lparam.0 as *const MSLLHOOKSTRUCT) };
+
+ MOUSE_HOOK.with(|hook| {
+ if let Some(hook) = hook.get() {
+ let mut hook = hook.lock().unwrap();
+ hook.handle_event(wparam.0 as u32, mouse_event);
+ }
+ });
+ }
+
+ unsafe { CallNextHookEx(None, code, wparam, lparam) }
+}
diff --git a/packages/wm/src/common/platform/single_instance.rs b/packages/wm/src/common/platform/single_instance.rs
index 3b086324..dcaa53fc 100644
--- a/packages/wm/src/common/platform/single_instance.rs
+++ b/packages/wm/src/common/platform/single_instance.rs
@@ -17,6 +17,7 @@ pub struct SingleInstance {
handle: HANDLE,
}
+/// Arbitrary GUID used to identify the application.
const APP_GUID: PCWSTR =
w!("Global\\325d0ed7-7f60-4925-8d1b-aa287b26b218");
diff --git a/packages/wm/src/common/platform/win_event_hook.rs b/packages/wm/src/common/platform/win_event_hook.rs
new file mode 100644
index 00000000..bc3b3a01
--- /dev/null
+++ b/packages/wm/src/common/platform/win_event_hook.rs
@@ -0,0 +1,182 @@
+use std::{cell::OnceCell, sync::Arc};
+
+use anyhow::Result;
+use tokio::sync::mpsc;
+use tracing::warn;
+use windows::Win32::{
+ Foundation::HWND,
+ UI::{
+ Accessibility::{SetWinEventHook, UnhookWinEvent, HWINEVENTHOOK},
+ WindowsAndMessaging::{
+ EVENT_OBJECT_CLOAKED, EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE,
+ EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE,
+ EVENT_OBJECT_SHOW, EVENT_OBJECT_UNCLOAKED, EVENT_SYSTEM_FOREGROUND,
+ EVENT_SYSTEM_MINIMIZEEND, EVENT_SYSTEM_MINIMIZESTART,
+ EVENT_SYSTEM_MOVESIZEEND, OBJID_WINDOW, WINEVENT_OUTOFCONTEXT,
+ WINEVENT_SKIPOWNPROCESS,
+ },
+ },
+};
+
+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();
+}
+
+pub struct WinEventHook {
+ event_tx: mpsc::UnboundedSender<PlatformEvent>,
+ hook_handles: Vec<HWINEVENTHOOK>,
+}
+
+impl WinEventHook {
+ /// Starts a window event hook on the current thread.
+ ///
+ /// Assumes that a message loop is currently running.
+ pub fn start(
+ event_tx: mpsc::UnboundedSender<PlatformEvent>,
+ ) -> Result<Arc<Self>> {
+ let hook_handles = Self::hook_win_events()?;
+
+ let window_event_hook = Arc::new(Self {
+ event_tx,
+ hook_handles,
+ });
+
+ WINDOW_EVENT_HOOK
+ .with(|cell| cell.set(window_event_hook.clone()))
+ .map_err(|_| {
+ anyhow::anyhow!(
+ "Window event hook already started on current thread."
+ )
+ })?;
+
+ Ok(window_event_hook)
+ }
+
+ fn handle_event(&self, event_type: u32, handle: HWND) {
+ 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);
+ }
+ }
+
+ /// Creates several window event hooks via `SetWinEventHook`.
+ fn hook_win_events() -> Result<Vec<HWINEVENTHOOK>> {
+ let event_ranges = [
+ (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_LOCATIONCHANGE),
+ (EVENT_OBJECT_DESTROY, EVENT_OBJECT_HIDE),
+ (EVENT_SYSTEM_MINIMIZESTART, EVENT_SYSTEM_MINIMIZEEND),
+ (EVENT_SYSTEM_MOVESIZEEND, EVENT_SYSTEM_MOVESIZEEND),
+ (EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND),
+ (EVENT_OBJECT_LOCATIONCHANGE, EVENT_OBJECT_NAMECHANGE),
+ (EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED),
+ ];
+
+ // Create separate hooks for each event range. This is more performant
+ // than creating a single hook for all events and filtering them.
+ event_ranges
+ .iter()
+ .try_fold(Vec::new(), |mut handles, event_range| {
+ let hook_handle =
+ Self::hook_win_event(event_range.0, event_range.1)?;
+ handles.push(hook_handle);
+ Ok(handles)
+ })
+ }
+
+ /// Creates a window hook for the specified event range.
+ fn hook_win_event(
+ event_min: u32,
+ event_max: u32,
+ ) -> Result<HWINEVENTHOOK> {
+ let hook_handle = unsafe {
+ SetWinEventHook(
+ event_min,
+ event_max,
+ None,
+ Some(window_event_hook_proc),
+ 0,
+ 0,
+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,
+ )
+ };
+
+ if hook_handle.is_invalid() {
+ Err(anyhow::anyhow!("Failed to set window event hook."))
+ } else {
+ Ok(hook_handle)
+ }
+ }
+
+ /// Stops the window event hook and unhooks from all window events.
+ pub fn stop(&mut self) {
+ for hook_handle in self.hook_handles.drain(..) {
+ if let false = unsafe { UnhookWinEvent(hook_handle) }.as_bool() {
+ warn!("Failed to unhook window event.");
+ }
+ }
+ }
+}
+
+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
+/// through an MPSC channel for the WM to process.
+extern "system" fn window_event_hook_proc(
+ _hook: HWINEVENTHOOK,
+ event_type: u32,
+ handle: HWND,
+ id_object: i32,
+ id_child: i32,
+ _event_thread: u32,
+ _event_time: u32,
+) {
+ let is_window_event =
+ id_object == OBJID_WINDOW.0 && id_child == 0 && handle != HWND(0);
+
+ // Check whether the event is associated with a window object instead
+ // of a UI control.
+ if !is_window_event {
+ return;
+ }
+
+ WINDOW_EVENT_HOOK.with(|hook| {
+ if let Some(hook) = hook.get() {
+ hook.handle_event(event_type, handle);
+ }
+ });
+}
diff --git a/packages/wm/src/common/point.rs b/packages/wm/src/common/point.rs
new file mode 100644
index 00000000..0f87c385
--- /dev/null
+++ b/packages/wm/src/common/point.rs
@@ -0,0 +1,6 @@
+/// Represents an x-y coordinate.
+#[derive(Debug, Clone)]
+pub struct Point {
+ pub x: i32,
+ pub y: i32,
+}
diff --git a/packages/wm/src/containers/commands/set_focused_descendant.rs b/packages/wm/src/containers/commands/set_focused_descendant.rs
index 6ca7222c..7b26f69d 100644
--- a/packages/wm/src/containers/commands/set_focused_descendant.rs
+++ b/packages/wm/src/containers/commands/set_focused_descendant.rs
@@ -5,21 +5,17 @@ use crate::{
pub fn set_focused_descendant(
focused_descendant: Container,
- end_ancestor: Option<&Container>,
+ end_ancestor: Option<Container>,
state: &WmState,
) {
- let root = state.root_container.clone().into();
- let end_ancestor = end_ancestor.unwrap_or(&root);
+ let end_ancestor =
+ end_ancestor.unwrap_or_else(|| state.root_container.clone().into());
- // Traverse upwards, setting the container as the last focused until the
- // root container or `end_ancestor` is reached.
+ // Traverse upwards, setting the container as the last focused up to and
+ // including the end ancestor.
let mut target = focused_descendant;
while let Some(parent) = target.parent() {
- if parent.id() == end_ancestor.id() {
- break;
- }
-
{
let mut child_focus_order = parent.borrow_child_focus_order_mut();
@@ -31,6 +27,11 @@ pub fn set_focused_descendant(
}
}
+ // Exit if we've reached the end ancestor.
+ if target.id() == end_ancestor.id() {
+ break;
+ }
+
target = parent.into();
}
}
diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rs
index 9962d650..9444b49b 100644
--- a/packages/wm/src/wm.rs
+++ b/packages/wm/src/wm.rs
@@ -10,7 +10,10 @@ use tracing::error;
use crate::{
app_command::InvokeCommand,
common::{
- events::{handle_window_destroyed, handle_window_shown},
+ events::{
+ handle_window_destroyed, handle_window_focused,
+ handle_window_hidden, handle_window_shown,
+ },
platform::PlatformEvent,
},
containers::commands::redraw,
@@ -51,14 +54,22 @@ impl WindowManager {
}
Ok(())
}
- PlatformEvent::MouseMove => Ok(()),
+ PlatformEvent::MouseMove(_) => Ok(()),
PlatformEvent::WindowDestroyed(window) => handle_window_destroyed(
window,
self.state.lock().await.deref_mut(),
config,
),
- PlatformEvent::WindowFocused(_) => Ok(()),
- PlatformEvent::WindowHidden(_) => Ok(()),
+ PlatformEvent::WindowFocused(window) => handle_window_focused(
+ window,
+ self.state.lock().await.deref_mut(),
+ config,
+ ),
+ PlatformEvent::WindowHidden(window) => handle_window_hidden(
+ window,
+ self.state.lock().await.deref_mut(),
+ config,
+ ),
PlatformEvent::WindowLocationChanged(_) => Ok(()),
PlatformEvent::WindowMinimized(_) => Ok(()),
PlatformEvent::WindowMinimizeEnded(_) => Ok(()),
diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rs
index c4c73f5c..85e5cb2d 100644
--- a/packages/wm/src/wm_state.rs
+++ b/packages/wm/src/wm_state.rs
@@ -1,3 +1,5 @@
+use std::time::Instant;
+
use anyhow::Context;
use tokio::sync::mpsc::{self};
use tracing::warn;
@@ -10,9 +12,7 @@ use crate::{
FocusMode,
},
containers::{
- commands::{
- handle_set_active_window_border, redraw, set_focused_descendant,
- },
+ commands::{redraw, set_focused_descendant},
traits::CommonGetters,
Container, RootContainer, WindowContainer,
},
@@ -37,6 +37,10 @@ pub struct WmState {
pub active_border_window: Option<NativeWindow>,
+ /// Time since a previously focused window was unmanaged or minimized.
+ /// Used to decide whether to override incoming focus events.
+ pub unmanaged_or_minimized_timestamp: Option<Instant>,
+
/// Names of any currently enabled binding modes.
pub binding_modes: Vec<String>,
@@ -56,6 +60,7 @@ impl WmState {
containers_to_redraw: Vec::new(),
has_pending_focus_sync: false,
active_border_window: None,
+ unmanaged_or_minimized_timestamp: None,
binding_modes: Vec::new(),
app_bar_windows: Vec::new(),
event_tx,