GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: implement fn for getting manageable windows
Lars Berger57a99032a179
diff --git a/Cargo.lock b/Cargo.lockindex 4f2c2391..25cfdf38 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -80,15 +80,6 @@ version = "1.0.80"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5ad32ce52e4161730f7098c077cd2ed6229b5804ccf99e5366be1ab72a98b4e1"-[[package]]-name = "async-thread"-version = "0.1.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f8127d0634ad2b788f12e8c8623f91c584c2eb7496157b2e0cada5b01e0fbfd"-dependencies = [- "futures-channel",-]-[[package]]name = "autocfg"version = "1.1.0"@@ -116,12 +107,6 @@ version = "1.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"-[[package]]-name = "bitflags"-version = "2.4.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf"-[[package]]name = "block-buffer"version = "0.10.4"@@ -233,16 +218,6 @@ dependencies = ["typenum",]-[[package]]-name = "cstr"-version = "0.2.11"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8aa998c33a6d3271e3678950a22134cd7dd27cef86dee1b611b5b14207d1d90b"-dependencies = [- "proc-macro2",- "quote",-]-[[package]]name = "data-encoding"version = "2.5.0"@@ -280,15 +255,6 @@ dependencies = ["percent-encoding",]-[[package]]-name = "futures-channel"-version = "0.3.30"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78"-dependencies = [- "futures-core",-]-[[package]]name = "futures-core"version = "0.3.30"@@ -520,26 +486,6 @@ dependencies = ["libc",]-[[package]]-name = "num_enum"-version = "0.7.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "02339744ee7253741199f897151b38e72257d13802d4ee837285cc2990a90845"-dependencies = [- "num_enum_derive",-]--[[package]]-name = "num_enum_derive"-version = "0.7.2"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "681030a937600a36906c185595136d26abfebb4aa9c65701cefcaf8578bb982b"-dependencies = [- "proc-macro2",- "quote",- "syn",-]-[[package]]name = "object"version = "0.32.2"@@ -668,7 +614,7 @@ version = "0.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa"dependencies = [- "bitflags 1.3.2",+ "bitflags",][[package]]@@ -1304,20 +1250,6 @@ version = "0.52.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04"-[[package]]-name = "wineventhook"-version = "0.9.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e65143ce373ad218b2c09a3dab5dc36aa241f3c370a30b67d560f1e459e1407"-dependencies = [- "async-thread",- "bitflags 2.4.2",- "cstr",- "num_enum",- "tokio",- "winapi",-]-[[package]]name = "wm"version = "0.0.0"@@ -1339,5 +1271,4 @@ dependencies = ["uuid","watcher","windows",- "wineventhook",]diff --git a/Cargo.toml b/Cargo.tomlindex 9d9261c3..b7b034a5 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -9,19 +9,18 @@ regex = "1"tokio = { version = "1", features = ["full"] }windows = { version = "0.52", features = ["implement",- "Win32_System_Com",- "Win32_UI_Shell_Common","Win32_Foundation","Win32_Graphics_Dwm","Win32_Graphics_Gdi",+ "Win32_System_Com","Win32_System_LibraryLoader","Win32_System_RemoteDesktop",+ "Win32_System_SystemServices","Win32_System_Threading","Win32_UI_Accessibility","Win32_UI_HiDpi","Win32_UI_Input_KeyboardAndMouse",- "Win32_UI_Shell",+ "Win32_UI_Input_Ime","Win32_UI_Shell_Common","Win32_UI_WindowsAndMessaging",- "Win32_System_SystemServices",] }diff --git a/packages/wm/Cargo.toml b/packages/wm/Cargo.tomlindex 19458af8..b81de681 100644--- a/packages/wm/Cargo.toml+++ b/packages/wm/Cargo.toml@@ -25,4 +25,3 @@ tokio-tungstenite = "0.21"tracing = "0.1"tracing-subscriber = { version = "0.3", features = ["env-filter"] }windows = { workspace = true }-wineventhook = "0.9"diff --git a/packages/wm/src/common/platform/native_monitor.rs b/packages/wm/src/common/platform/native_monitor.rsindex 73100239..8fdca2f4 100644--- a/packages/wm/src/common/platform/native_monitor.rs+++ b/packages/wm/src/common/platform/native_monitor.rs@@ -7,7 +7,10 @@ use windows::Win32::{pub type MonitorHandle = HMONITOR;-#[derive(Debug)]+// TODO: Consider changing `device_name`, `width`, `height`, `x`, and `y` to+// be lazily retrieved similar to in `NativeWindow`. Add an `refresh` method+// to `NativeMonitor` to refresh the values.+#[derive(Clone, Debug)]pub struct NativeMonitor {pub handle: MonitorHandle,pub device_name: String,@@ -37,15 +40,25 @@ impl NativeMonitor {}}-pub fn available_monitors() -> Vec<NativeMonitor> {- available_monitor_handles()- .into_iter()- .filter_map(|handle| handle_to_monitor(handle).ok())- .collect()+impl PartialEq for NativeMonitor {+ fn eq(&self, other: &Self) -> bool {+ self.handle == other.handle+ }+}++impl Eq for NativeMonitor {}++pub fn available_monitors() -> anyhow::Result<Vec<NativeMonitor>> {+ Ok(+ available_monitor_handles()?+ .into_iter()+ .filter_map(|handle| handle_to_monitor(handle).ok())+ .collect(),+ )}/// Gets all available monitor handles.-fn available_monitor_handles() -> Vec<MonitorHandle> {+fn available_monitor_handles() -> anyhow::Result<Vec<MonitorHandle>> {let mut monitors: Vec<MonitorHandle> = Vec::new();unsafe {@@ -54,10 +67,11 @@ fn available_monitor_handles() -> Vec<MonitorHandle> {None,Some(available_monitor_handles_proc),LPARAM(&mut monitors as *mut _ as _),- );+ )}+ .ok()?;- monitors+ Ok(monitors)}/// Callback passed to `EnumDisplayMonitors` to get all available monitor@@ -68,8 +82,8 @@ unsafe extern "system" fn available_monitor_handles_proc(_clip: *mut RECT,data: LPARAM,) -> BOOL {- let monitors = data.0 as *mut Vec<MonitorHandle>;- unsafe { (*monitors).push(handle) };+ let handles = data.0 as *mut Vec<MonitorHandle>;+ unsafe { (*handles).push(handle) };true.into()}diff --git a/packages/wm/src/common/platform/native_window.rs b/packages/wm/src/common/platform/native_window.rsindex 6fac2ea2..991660d8 100644--- a/packages/wm/src/common/platform/native_window.rs+++ b/packages/wm/src/common/platform/native_window.rs@@ -4,13 +4,21 @@ use anyhow::Result;use windows::{core::PWSTR,Win32::{- Foundation::{CloseHandle, HWND},+ Foundation::{CloseHandle, BOOL, HWND, LPARAM},+ Graphics::Dwm::{DwmGetWindowAttribute, DWMWA_CLOAKED},System::Threading::{OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_WIN32,PROCESS_QUERY_INFORMATION,},- UI::WindowsAndMessaging::{- GetClassNameW, GetWindowTextW, GetWindowThreadProcessId,+ UI::{+ Input::KeyboardAndMouse::{+ SendInput, INPUT, INPUT_0, INPUT_KEYBOARD, KEYBDINPUT,+ KEYBD_EVENT_FLAGS, VIRTUAL_KEY,+ },+ WindowsAndMessaging::{+ EnumWindows, GetClassNameW, GetWindowTextW,+ GetWindowThreadProcessId, IsWindowVisible, SetForegroundWindow,+ },},},};@@ -35,9 +43,10 @@ impl NativeWindow {}}- /// Gets the window's title.+ /// Gets the window's title. If the window is invalid, returns an empty+ /// string.///- /// If the window is invalid, returns an empty string.+ /// This value is lazily retrieved and is cached after first retrieval.pub fn title(&self) -> String {let title_guard = self.title.read().unwrap();match *title_guard {@@ -54,6 +63,8 @@ impl NativeWindow {}/// Gets the process name associated with the window.+ ///+ /// This value is lazily retrieved and is cached after first retrieval.pub fn process_name(&self) -> Result<String> {let process_name_guard = self.process_name.read().unwrap();match *process_name_guard {@@ -89,6 +100,8 @@ impl NativeWindow {}/// Gets the class name of the window.+ ///+ /// This value is lazily retrieved and is cached after first retrieval.pub fn class_name(&self) -> Result<String> {let class_name_guard = self.class_name.read().unwrap();match *class_name_guard {@@ -109,12 +122,38 @@ impl NativeWindow {}}+ /// Whether the window is actually visible.pub fn is_visible(&self) -> bool {- todo!()+ let is_visible = unsafe { IsWindowVisible(self.handle) }.as_bool();+ is_visible && !self.is_cloaked()+ }++ /// Whether the window is cloaked. For some UWP apps, `WS_VISIBLE` will+ /// be present even if the window isn't actually visible. The+ /// `DWMWA_CLOAKED` attribute is used to check whether these apps are+ /// visible.+ fn is_cloaked(&self) -> bool {+ let mut cloaked = 0u32;++ let _ = unsafe {+ DwmGetWindowAttribute(+ self.handle,+ DWMWA_CLOAKED,+ &mut cloaked as *mut u32 as _,+ std::mem::size_of::<u32>() as u32,+ )+ };++ cloaked != 0}pub fn is_manageable(&self) -> bool {- todo!()+ // Ignore windows that are hidden.+ if !self.is_visible() {+ return false;+ }++ true}pub fn is_minimized(&self) -> bool {@@ -133,6 +172,31 @@ impl NativeWindow {todo!()}+ pub fn set_foreground(&self) -> anyhow::Result<()> {+ // Simulate a key press event to activate the window.+ let input = INPUT {+ r#type: INPUT_KEYBOARD,+ Anonymous: INPUT_0 {+ ki: KEYBDINPUT {+ wVk: VIRTUAL_KEY(0),+ wScan: 0,+ dwFlags: KEYBD_EVENT_FLAGS(0),+ time: 0,+ dwExtraInfo: 0,+ },+ },+ };++ unsafe {+ SendInput(&[input], std::mem::size_of::<INPUT>() as i32);+ }++ // Set as the foreground window.+ unsafe { SetForegroundWindow(self.handle) }.ok()?;++ Ok(())+ }+// fn window_styles(&self) -> Vec<WindowStyle> {// todo!()// }@@ -141,3 +205,40 @@ impl NativeWindow {// todo!()// }}++impl PartialEq for NativeWindow {+ fn eq(&self, other: &Self) -> bool {+ self.handle == other.handle+ }+}++impl Eq for NativeWindow {}++pub fn available_windows() -> Result<Vec<NativeWindow>> {+ available_window_handles()?+ .into_iter()+ .map(|handle| Ok(NativeWindow::new(handle)))+ .collect()+}++pub fn available_window_handles() -> anyhow::Result<Vec<WindowHandle>> {+ let mut handles: Vec<WindowHandle> = Vec::new();++ unsafe {+ EnumWindows(+ Some(available_window_handles_proc),+ LPARAM(&mut handles as *mut _ as _),+ )+ }?;++ Ok(handles)+}++extern "system" fn available_window_handles_proc(+ handle: HWND,+ data: LPARAM,+) -> BOOL {+ let handles = data.0 as *mut Vec<HWND>;+ unsafe { (*handles).push(handle) };+ true.into()+}diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rsindex 0d04fed5..f7521d7a 100644--- a/packages/wm/src/common/platform/platform.rs+++ b/packages/wm/src/common/platform/platform.rs@@ -1,27 +1,46 @@use std::sync::Arc;-use anyhow::Result;use tokio::sync::{mpsc::UnboundedReceiver, Mutex};+use windows::Win32::UI::WindowsAndMessaging::GetForegroundWindow;use crate::user_config::UserConfig;-use super::{native_monitor, EventListener, NativeMonitor, NativeWindow};+use super::{+ native_monitor, native_window, EventListener, NativeMonitor,+ NativeWindow,+};pub struct Platform;impl Platform {- pub fn monitors() -> Vec<NativeMonitor> {+ pub fn foreground_window() -> NativeWindow {+ let handle = unsafe { GetForegroundWindow() };+ NativeWindow::new(handle)+ }++ pub fn monitors() -> anyhow::Result<Vec<NativeMonitor>> {+ native_monitor::available_monitors()+ }++ pub fn nearest_monitor(window: NativeWindow) -> Option<NativeMonitor> {native_monitor::available_monitors()+ .ok()+ .and_then(|m| m.first().cloned())}- pub fn manageable_windows() -> Result<Vec<NativeWindow>> {- todo!()+ pub fn manageable_windows() -> anyhow::Result<Vec<NativeWindow>> {+ Ok(+ native_window::available_windows()?+ .into_iter()+ .filter(|w| w.is_manageable())+ .collect(),+ )}pub async fn new_event_listener(config: Arc<Mutex<UserConfig>>,config_changes_rx: UnboundedReceiver<UserConfig>,- ) -> Result<EventListener> {+ ) -> anyhow::Result<EventListener> {EventListener::start(config, config_changes_rx).await}}diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rsindex e9cb544f..74f74427 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -61,16 +61,12 @@ async fn start_wm(config_path: Option<String>) -> Result<()> {// Start watcher process for restoring hidden windows on crash.start_watcher_process()?;- let mut wm =- WindowManager::start(config.clone(), config_changes_tx).await?;+ let mut wm = WindowManager::start(config.clone(), config_changes_tx)?;// Start listening for platform events.let mut event_listener =Platform::new_event_listener(config, config_changes_rx).await?;- let monitors = Platform::monitors();- info!("Available monitors: {:?}", monitors);-loop {let wm_state = wm.state.clone();@@ -93,7 +89,7 @@ async fn start_wm(config_path: Option<String>) -> Result<()> {// println!("aaaa {:?}", leaf_deep);// println!("aaaa {:?}", leaf_deep.grandparent());- // wm.process_event(event).await+ wm.process_event(event).await},Some(wm_event) = wm.event_rx.recv() => {info!("Received WM event: {:?}", wm_event);diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rsindex 00efacea..cf95cc28 100644--- a/packages/wm/src/wm.rs+++ b/packages/wm/src/wm.rs@@ -5,11 +5,10 @@ use tokio::sync::{mpsc::{self, UnboundedReceiver, UnboundedSender},Mutex,};-use wineventhook::WindowEvent;use crate::{- user_config::UserConfig, wm_command::WmCommand, wm_event::WmEvent,- wm_state::WmState,+ common::platform::PlatformEvent, user_config::UserConfig,+ wm_command::WmCommand, wm_event::WmEvent, wm_state::WmState,};pub struct WindowManager {@@ -18,23 +17,31 @@ pub struct WindowManager {}impl WindowManager {- pub async fn start(+ pub fn start(config: Arc<Mutex<UserConfig>>,config_changes_tx: UnboundedSender<UserConfig>,) -> Result<Self> {let (event_tx, event_rx) = mpsc::unbounded_channel();+ let mut state = WmState::new(config, config_changes_tx, event_tx);+ state.populate()?;+Ok(Self {event_rx,- state: Arc::new(Mutex::new(WmState::new(- config,- config_changes_tx,- event_tx,- ))),+ state: Arc::new(Mutex::new(state)),})}- pub async fn process_event(&mut self, event: WindowEvent) {+ // pub fn init() -> Result<()> {+ // let foreground_window = Platform::foreground_window();++ // let monitors = Platform::monitors()?;+ // let manageable_windows = Platform::manageable_windows()?;++ // Ok(())+ // }++ pub async fn process_event(&mut self, event: PlatformEvent) {todo!()}diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex 81fc4056..f3add998 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -11,7 +11,10 @@ use tracing::warn;use uuid::Uuid;use crate::{- common::{platform::NativeMonitor, FocusMode},+ common::{+ platform::{NativeMonitor, Platform},+ FocusMode,+ },containers::{CommonContainer, ContainerRef, ContainerType, RootContainer,RootContainerRef,@@ -61,6 +64,38 @@ impl WmState {}}+ pub fn populate(&mut self) -> anyhow::Result<()> {+ let foreground_window = Platform::foreground_window();+ let native_monitors = Platform::monitors()?;++ for native_monitor in native_monitors {+ let monitor = MonitorRef::new(native_monitor);++ self+ .root_container+ .insert_child(0, ContainerRef::Monitor(monitor));+ }++ for native_window in Platform::manageable_windows()? {+ let window = ContainerRef::Window(native_window);+ self.root_container.insert_child(0, window);+ }++ Ok(())+ }++ pub fn nearest_monitor(&self) -> Option<MonitorRef> {+ self+ .root_container+ .self_and_descendants()+ .into_iter()+ .filter_map(|container| match container {+ ContainerRef::Monitor(monitor) => Some(monitor.clone()),+ _ => None,+ })+ .next()+ }+pub fn add_monitor(&mut self) {let monitor = MonitorRef::new(NativeMonitor::new(windows::Win32::Graphics::Gdi::HMONITOR(1),