GlazeWM is a tiling window manager for macOS and Windows inspired by i3wm.
feat: add `device_path` and `hardware_id` to monitors; wip event handler for display settings changes
Lars Berger3ff1e89706b2
diff --git a/packages/wm/src/common/events/handle_display_settings_changed.rs b/packages/wm/src/common/events/handle_display_settings_changed.rsnew file mode 100644index 00000000..cc31d4a9--- /dev/null+++ b/packages/wm/src/common/events/handle_display_settings_changed.rs@@ -0,0 +1,62 @@+use tracing::info;++use crate::{+ common::platform::Platform, user_config::UserConfig, wm_event::WmEvent,+ wm_state::WmState,+};++pub fn handle_display_settings_changed(+ state: &mut WmState,+ config: &UserConfig,+) -> anyhow::Result<()> {+ info!("Display settings changed.");++ let native_monitors = Platform::monitors()?;+ let hardware_ids = native_monitors+ .iter()+ .filter_map(|m| m.hardware_id().ok())+ .flatten()+ .collect::<Vec<_>>();++ let monitors = state.monitors();++ for native_monitor in native_monitors {+ // Hardware ID is not guaranteed to be unique, so we check+ // for that as a fallback.+ let found_monitor = monitors.iter().find(|monitor| {+ monitor.native().handle == native_monitor.handle+ || monitor.native().device_path().is_ok_and(|path| {+ path.is_some_and(|path| {+ Some(Some(path)) == native_monitor.device_path().ok()+ })+ })+ // TODO: Check that there aren't multiple monitors with the same+ // hardware ID.+ || monitor.native().hardware_id().is_ok_and(|id| {+ id.is_some_and(|id| {+ Some(Some(id)) == native_monitor.hardware_id().ok()+ })+ })+ // == native_monitor.hardware_id().ok() && !hardware_ids.contains(monitor.native().hardware_id().unwrap()))+ });++ if let Some(found_monitor) = found_monitor {+ info!(+ "Monitor: {:?} {} {:?} {:?}",+ native_monitor.handle,+ native_monitor.device_name()?,+ native_monitor.device_path()?,+ native_monitor.hardware_id()?+ );++ // found_monitor.set_native(native_monitor);++ state.emit_event(WmEvent::MonitorUpdated {+ updated_monitor: found_monitor.clone(),+ })+ }+ }+ info!("-------");++ Ok(())+}diff --git a/packages/wm/src/common/events/mod.rs b/packages/wm/src/common/events/mod.rsindex 11320ab7..01599fe7 100644--- a/packages/wm/src/common/events/mod.rs+++ b/packages/wm/src/common/events/mod.rs@@ -1,3 +1,4 @@+mod handle_display_settings_changed;mod handle_window_destroyed;mod handle_window_focused;mod handle_window_hidden;@@ -7,6 +8,7 @@ mod handle_window_minimized;mod handle_window_moved_or_resized;mod handle_window_shown;+pub use handle_display_settings_changed::*;pub use handle_window_destroyed::*;pub use handle_window_focused::*;pub use handle_window_hidden::*;diff --git a/packages/wm/src/common/platform/event_listener.rs b/packages/wm/src/common/platform/event_listener.rsindex 9a2e854a..48dd8751 100644--- a/packages/wm/src/common/platform/event_listener.rs+++ b/packages/wm/src/common/platform/event_listener.rs@@ -15,6 +15,7 @@ use super::{EventWindow, EventWindowOptions, NativeWindow};#[derive(Debug)]pub enum PlatformEvent {+ PowerModeChanged,DisplaySettingsChanged,KeybindingTriggered(KeybindingConfig),MouseMove(MouseMoveEvent),diff --git a/packages/wm/src/common/platform/event_window.rs b/packages/wm/src/common/platform/event_window.rsindex 67ded643..79776268 100644--- a/packages/wm/src/common/platform/event_window.rs+++ b/packages/wm/src/common/platform/event_window.rs@@ -5,13 +5,13 @@ use std::{use anyhow::Result;use tokio::sync::{mpsc, oneshot};-use tracing::warn;+use tracing::{info, warn};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,+ WM_DISPLAYCHANGE, WM_POWERBROADCAST, WM_SETTINGCHANGE,},};@@ -118,6 +118,11 @@ pub extern "system" fn event_window_proc(WM_DISPLAYCHANGE | WM_SETTINGCHANGE | WM_DEVICECHANGE => {handle_display_change_msg(message, wparam, event_tx)}+ WM_POWERBROADCAST => {+ info!("power mode changed------- {}", wparam.0 as u32);+ event_tx.send(PlatformEvent::PowerModeChanged).unwrap();+ LRESULT(0)+ }WM_DESTROY => {unsafe { PostQuitMessage(0) };LRESULT(0)diff --git a/packages/wm/src/common/platform/native_monitor.rs b/packages/wm/src/common/platform/native_monitor.rsindex b56fc334..1e8f1d5c 100644--- a/packages/wm/src/common/platform/native_monitor.rs+++ b/packages/wm/src/common/platform/native_monitor.rs@@ -1,50 +1,153 @@-use windows::Win32::{- Foundation::{BOOL, LPARAM, RECT},- Graphics::Gdi::{- EnumDisplayMonitors, GetMonitorInfoW, MonitorFromWindow, HDC,- HMONITOR, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST,+use std::cell::OnceCell;++use windows::{+ core::PCWSTR,+ Win32::{+ Foundation::{BOOL, LPARAM, RECT},+ Graphics::Gdi::{+ EnumDisplayDevicesW, EnumDisplayMonitors, GetMonitorInfoW,+ MonitorFromWindow, DISPLAY_DEVICEW, DISPLAY_DEVICE_ACTIVE, HDC,+ HMONITOR, MONITORINFOEXW, MONITOR_DEFAULTTONEAREST,+ },+ UI::{+ HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},+ WindowsAndMessaging::EDD_GET_DEVICE_INTERFACE_NAME,+ },},- UI::HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},};use super::WindowHandle;pub type MonitorHandle = HMONITOR;-// 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,- pub width: i32,- pub height: i32,- pub x: i32,- pub y: i32,- pub dpi: f32,+ info: OnceCell<MonitorInfo>,+}++#[derive(Clone, Debug)]+struct MonitorInfo {+ device_name: String,+ device_path: Option<String>,+ hardware_id: Option<String>,+ width: i32,+ height: i32,+ x: i32,+ y: i32,+ dpi: f32,}impl NativeMonitor {- pub fn new(- handle: MonitorHandle,- device_name: String,- width: i32,- height: i32,- x: i32,- y: i32,- dpi: f32,- ) -> Self {+ pub fn new(handle: MonitorHandle) -> Self {Self {handle,- device_name,- width,- height,- x,- y,- dpi,+ info: OnceCell::new(),}}++ pub fn device_name(&self) -> anyhow::Result<&String> {+ self.monitor_info().map(|info| &info.device_name)+ }++ pub fn device_path(&self) -> anyhow::Result<Option<&String>> {+ self.monitor_info().map(|info| info.device_path.as_ref())+ }++ pub fn hardware_id(&self) -> anyhow::Result<Option<&String>> {+ self.monitor_info().map(|info| info.hardware_id.as_ref())+ }++ pub fn width(&self) -> anyhow::Result<i32> {+ self.monitor_info().map(|info| info.width)+ }++ pub fn height(&self) -> anyhow::Result<i32> {+ self.monitor_info().map(|info| info.height)+ }++ pub fn x(&self) -> anyhow::Result<i32> {+ self.monitor_info().map(|info| info.x)+ }++ pub fn y(&self) -> anyhow::Result<i32> {+ self.monitor_info().map(|info| info.y)+ }++ pub fn dpi(&self) -> anyhow::Result<f32> {+ self.monitor_info().map(|info| info.dpi)+ }++ fn monitor_info(&self) -> anyhow::Result<&MonitorInfo> {+ self.info.get_or_try_init(|| {+ let mut monitor_info = MONITORINFOEXW::default();+ monitor_info.monitorInfo.cbSize =+ std::mem::size_of::<MONITORINFOEXW>() as u32;++ unsafe {+ GetMonitorInfoW(self.handle, &mut monitor_info as *mut _ as _)+ }+ .ok()?;++ // Get the display devices associated with the monitor.+ let mut display_devices = (0..)+ .map_while(|index| {+ let mut display_device = DISPLAY_DEVICEW::default();+ display_device.cb =+ std::mem::size_of::<DISPLAY_DEVICEW>() as u32;++ // Due to the `EDD_GET_DEVICE_INTERFACE_NAME` flag, the device+ // struct will contain the DOS device path under the `DeviceId`+ // field.+ unsafe {+ EnumDisplayDevicesW(+ PCWSTR(monitor_info.szDevice.as_ptr()),+ index,+ &mut display_device,+ EDD_GET_DEVICE_INTERFACE_NAME,+ )+ }+ .as_bool()+ .then(|| display_device)+ })+ // Filter out any devices that are not active.+ .filter(|device| device.StateFlags & DISPLAY_DEVICE_ACTIVE != 0);++ // Get the device path and hardware ID from the first valid device.+ let (device_path, hardware_id) = display_devices+ .next()+ .map(|device| {+ let device_path = String::from_utf16_lossy(&device.DeviceID)+ .trim_end_matches('\0')+ .to_string();++ let hardware_id = device_path+ .split("#")+ .collect::<Vec<_>>()+ .get(1)+ .map(|id| id.to_string());++ (Some(device_path), hardware_id)+ })+ .unwrap_or((None, None));++ let device_name = String::from_utf16_lossy(&monitor_info.szDevice);+ let dpi = monitor_dpi(self.handle)?;++ Ok(MonitorInfo {+ device_name,+ device_path,+ hardware_id,+ width: monitor_info.monitorInfo.rcMonitor.right+ - monitor_info.monitorInfo.rcMonitor.left,+ height: monitor_info.monitorInfo.rcMonitor.bottom+ - monitor_info.monitorInfo.rcMonitor.top,+ x: monitor_info.monitorInfo.rcMonitor.left,+ y: monitor_info.monitorInfo.rcMonitor.top,+ dpi,+ })+ })+ }}impl PartialEq for NativeMonitor {@@ -55,11 +158,12 @@ impl PartialEq for NativeMonitor {impl Eq for NativeMonitor {}+/// Gets all available monitors.pub fn available_monitors() -> anyhow::Result<Vec<NativeMonitor>> {Ok(available_monitor_handles()?.into_iter()- .filter_map(|handle| handle_to_monitor(handle).ok())+ .map(|handle| NativeMonitor::new(handle)).collect(),)}@@ -94,40 +198,11 @@ extern "system" fn available_monitor_handles_proc(true.into()}-/// Converts a monitor handle to an instance of `NativeMonitor`.-fn handle_to_monitor(- handle: MonitorHandle,-) -> anyhow::Result<NativeMonitor> {- let mut monitor_info = MONITORINFOEXW::default();- monitor_info.monitorInfo.cbSize =- std::mem::size_of::<MONITORINFOEXW>() as u32;-- unsafe { GetMonitorInfoW(handle, &mut monitor_info as *mut _ as _) }- .ok()?;-- let device_name = String::from_utf16_lossy(&monitor_info.szDevice);- let dpi = monitor_dpi(handle)?;-- Ok(NativeMonitor::new(- handle,- device_name,- monitor_info.monitorInfo.rcMonitor.right- - monitor_info.monitorInfo.rcMonitor.left,- monitor_info.monitorInfo.rcMonitor.bottom- - monitor_info.monitorInfo.rcMonitor.top,- monitor_info.monitorInfo.rcMonitor.left,- monitor_info.monitorInfo.rcMonitor.top,- dpi,- ))-}--pub fn nearest_monitor(- window_handle: WindowHandle,-) -> anyhow::Result<NativeMonitor> {+pub fn nearest_monitor(window_handle: WindowHandle) -> NativeMonitor {let handle =unsafe { MonitorFromWindow(window_handle, MONITOR_DEFAULTTONEAREST) };- handle_to_monitor(handle)+ NativeMonitor::new(handle)}fn monitor_dpi(handle: MonitorHandle) -> anyhow::Result<f32> {diff --git a/packages/wm/src/common/platform/native_window.rs b/packages/wm/src/common/platform/native_window.rsindex c2059a89..219aefa1 100644--- a/packages/wm/src/common/platform/native_window.rs+++ b/packages/wm/src/common/platform/native_window.rs@@ -21,11 +21,11 @@ use windows::{SetForegroundWindow, SetWindowPos, ShowWindowAsync, GWL_EXSTYLE,GWL_STYLE, GW_OWNER, HWND_NOTOPMOST, HWND_TOPMOST,SWP_ASYNCWINDOWPOS, SWP_FRAMECHANGED, SWP_HIDEWINDOW,- SWP_NOACTIVATE, SWP_NOCOPYBITS, SWP_NOMOVE, SWP_NOSENDCHANGING,- SWP_NOSIZE, SWP_SHOWWINDOW, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE,+ SWP_NOACTIVATE, SWP_NOCOPYBITS, SWP_NOSENDCHANGING,+ SWP_SHOWWINDOW, SW_MAXIMIZE, SW_MINIMIZE, SW_RESTORE,WINDOWPLACEMENT, WINDOW_EX_STYLE, WINDOW_STYLE, WM_CLOSE,WS_CAPTION, WS_CHILD, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,- WS_MAXIMIZE, WS_MINIMIZE, WS_THICKFRAME,+ WS_THICKFRAME,},},},diff --git a/packages/wm/src/common/platform/platform.rs b/packages/wm/src/common/platform/platform.rsindex 62457662..7b60b8db 100644--- a/packages/wm/src/common/platform/platform.rs+++ b/packages/wm/src/common/platform/platform.rs@@ -43,9 +43,7 @@ impl Platform {native_monitor::available_monitors()}- pub fn nearest_monitor(- window: &NativeWindow,- ) -> anyhow::Result<NativeMonitor> {+ pub fn nearest_monitor(window: &NativeWindow) -> NativeMonitor {native_monitor::nearest_monitor(window.handle)}diff --git a/packages/wm/src/main.rs b/packages/wm/src/main.rsindex d6bbe91f..9fa8e079 100644--- a/packages/wm/src/main.rs+++ b/packages/wm/src/main.rs@@ -1,4 +1,5 @@#![feature(iterator_try_collect)]+#![feature(once_cell_try)]use std::{env, path::PathBuf};diff --git a/packages/wm/src/monitors/monitor.rs b/packages/wm/src/monitors/monitor.rsindex 8a54c13b..e886be9b 100644--- a/packages/wm/src/monitors/monitor.rs+++ b/packages/wm/src/monitors/monitor.rs@@ -47,12 +47,8 @@ impl Monitor {self.0.borrow().native.clone()}- pub fn name(&self) -> String {- self.native().device_name- }-- pub fn workspaces(&self) -> Vec<Workspace> {- todo!()+ pub fn name(&self) -> anyhow::Result<String> {+ self.native().device_name().cloned()}pub fn displayed_workspace(&self) -> Option<Workspace> {@@ -71,7 +67,7 @@ impl Monitor {) -> anyhow::Result<bool> {let other_monitor = other.monitor().context("No parent monitor.")?;- Ok(self.native().dpi != other_monitor.native().dpi)+ Ok(self.native().dpi()? != other_monitor.native().dpi()?)}pub fn to_dto(&self) -> anyhow::Result<MonitorDto> {@@ -94,7 +90,7 @@ impl Monitor {height: self.height()?,x: self.x()?,y: self.y()?,- dpi: self.native().dpi,+ dpi: self.native().dpi()?,})}}@@ -103,19 +99,19 @@ impl_common_getters!(Monitor, ContainerType::Monitor);impl PositionGetters for Monitor {fn width(&self) -> anyhow::Result<i32> {- Ok(self.0.borrow().native.width)+ Ok(self.0.borrow().native.width()?)}fn height(&self) -> anyhow::Result<i32> {- Ok(self.0.borrow().native.height)+ Ok(self.0.borrow().native.height()?)}fn x(&self) -> anyhow::Result<i32> {- Ok(self.0.borrow().native.x)+ Ok(self.0.borrow().native.x()?)}fn y(&self) -> anyhow::Result<i32> {- Ok(self.0.borrow().native.y)+ Ok(self.0.borrow().native.y()?)}}diff --git a/packages/wm/src/user_config.rs b/packages/wm/src/user_config.rsindex 6196afd1..6f42ffb7 100644--- a/packages/wm/src/user_config.rs+++ b/packages/wm/src/user_config.rs@@ -101,7 +101,9 @@ impl UserConfig {config.bind_to_monitor.as_ref()- .map(|monitor_name| monitor_name == &monitor.name())+ .and_then(|monitor_name| {+ monitor.name().map(|n| &n == monitor_name).ok()+ }).unwrap_or(false)});diff --git a/packages/wm/src/wm.rs b/packages/wm/src/wm.rsindex dd6e1a34..881013e4 100644--- a/packages/wm/src/wm.rs+++ b/packages/wm/src/wm.rs@@ -12,10 +12,11 @@ use crate::{common::{commands::sync_native_focus,events::{- handle_window_destroyed, handle_window_focused,- handle_window_hidden, handle_window_location_changed,- handle_window_minimize_ended, handle_window_minimized,- handle_window_moved_or_resized, handle_window_shown,+ handle_display_settings_changed, handle_window_destroyed,+ handle_window_focused, handle_window_hidden,+ handle_window_location_changed, handle_window_minimize_ended,+ handle_window_minimized, handle_window_moved_or_resized,+ handle_window_shown,},platform::PlatformEvent,},@@ -62,7 +63,10 @@ impl WindowManager {let mut state = self.state.lock().await;match event {- PlatformEvent::DisplaySettingsChanged => Ok(()),+ PlatformEvent::PowerModeChanged => Ok(()),+ PlatformEvent::DisplaySettingsChanged => {+ handle_display_settings_changed(&mut state, config)+ }PlatformEvent::MouseMove(_) => Ok(()),PlatformEvent::WindowDestroyed(window) => {handle_window_destroyed(window, &mut state)diff --git a/packages/wm/src/wm_event.rs b/packages/wm/src/wm_event.rsindex d21ba344..3652d387 100644--- a/packages/wm/src/wm_event.rs+++ b/packages/wm/src/wm_event.rs@@ -22,6 +22,9 @@ pub enum WmEvent {MonitorAdded {added_monitor: Monitor,},+ MonitorUpdated {+ updated_monitor: Monitor,+ },MonitorRemoved {removed_id: Uuid,removed_device_name: String,diff --git a/packages/wm/src/wm_state.rs b/packages/wm/src/wm_state.rsindex ccf7755a..f03580ad 100644--- a/packages/wm/src/wm_state.rs+++ b/packages/wm/src/wm_state.rs@@ -138,9 +138,8 @@ impl WmState {&self,native_window: &NativeWindow,) -> Option<Monitor> {- Platform::nearest_monitor(&native_window)- .ok()- .and_then(|native| self.monitor_from_native(&native))+ self+ .monitor_from_native(&Platform::nearest_monitor(&native_window)).or(self.monitors().first().cloned())}