diff --git a/window/Cargo.toml b/window/Cargo.toml index 557ee2b3d..09d63925b 100644 --- a/window/Cargo.toml +++ b/window/Cargo.toml @@ -61,6 +61,7 @@ winapi = { version = "0.3", features = [ ]} windows = { version="0.33.0", features = [ "UI_ViewManagement", + "Win32_Devices_Display", ]} winreg = "0.10" diff --git a/window/src/connection.rs b/window/src/connection.rs index c3f448c69..69c830b55 100644 --- a/window/src/connection.rs +++ b/window/src/connection.rs @@ -1,6 +1,7 @@ use crate::screen::Screens; -use crate::{Appearance, Connection}; +use crate::{Appearance, Connection, GeometryOrigin, RequestedWindowGeometry, ResolvedGeometry}; use anyhow::Result as Fallible; +use config::DimensionContext; use std::cell::RefCell; use std::rc::Rc; @@ -54,4 +55,60 @@ pub trait ConnectionOps { fn screens(&self) -> anyhow::Result { anyhow::bail!("Unable to query screen information"); } + + fn resolve_geometry(&self, geometry: RequestedWindowGeometry) -> ResolvedGeometry { + let bounds = match self.screens() { + Ok(screens) => { + log::trace!("{screens:?}"); + + match geometry.origin { + GeometryOrigin::ScreenCoordinateSystem => screens.virtual_rect, + GeometryOrigin::MainScreen => screens.main.rect, + GeometryOrigin::ActiveScreen => screens.active.rect, + GeometryOrigin::Named(name) => match screens.by_name.get(&name) { + Some(info) => info.rect.clone(), + None => { + log::error!( + "Requested display {} was not found; available displays are: {:?}. \ + Using primary display instead", + name, + screens.by_name, + ); + screens.main.rect + } + }, + } + } + Err(_) => euclid::rect(0, 0, 65535, 65535), + }; + + let dpi = self.default_dpi(); + let width_context = DimensionContext { + dpi: dpi as f32, + pixel_max: bounds.width() as f32, + pixel_cell: bounds.width() as f32, + }; + let height_context = DimensionContext { + dpi: dpi as f32, + pixel_max: bounds.height() as f32, + pixel_cell: bounds.height() as f32, + }; + let width = geometry.width.evaluate_as_pixels(width_context) as usize; + let height = geometry.height.evaluate_as_pixels(height_context) as usize; + let x = geometry + .x + .map(|x| x.evaluate_as_pixels(width_context) as i32 + bounds.origin.x as i32) + .unwrap_or(0); + let y = geometry + .y + .map(|y| y.evaluate_as_pixels(height_context) as i32 + bounds.origin.y as i32) + .unwrap_or(0); + + ResolvedGeometry { + x, + y, + width, + height, + } + } } diff --git a/window/src/lib.rs b/window/src/lib.rs index 07aad5085..fe80bbbad 100644 --- a/window/src/lib.rs +++ b/window/src/lib.rs @@ -319,3 +319,11 @@ pub struct RequestedWindowGeometry { /// Also applies to width/height when computing % based dimensions pub origin: GeometryOrigin, } + +#[derive(Debug, Clone)] +pub struct ResolvedGeometry { + pub x: i32, + pub y: i32, + pub width: usize, + pub height: usize, +} diff --git a/window/src/os/windows/connection.rs b/window/src/os/windows/connection.rs index d702e2587..ded6179b0 100644 --- a/window/src/os/windows/connection.rs +++ b/window/src/os/windows/connection.rs @@ -4,6 +4,7 @@ use crate::connection::ConnectionOps; use crate::screen::{ScreenInfo, Screens}; use crate::spawn::*; use crate::{Appearance, ScreenRect}; +use anyhow::Context; use std::cell::RefCell; use std::collections::HashMap; use std::ffi::OsString; @@ -12,9 +13,17 @@ use std::ptr::null_mut; use std::rc::Rc; use winapi::shared::minwindef::*; use winapi::shared::windef::*; +use winapi::shared::winerror::{ERROR_INSUFFICIENT_BUFFER, ERROR_SUCCESS}; use winapi::um::winbase::INFINITE; +use winapi::um::wingdi::{DISPLAY_DEVICEW, QDC_ONLY_ACTIVE_PATHS, QDC_VIRTUAL_MODE_AWARE}; use winapi::um::winnt::HANDLE; use winapi::um::winuser::*; +use windows::Win32::Devices::Display::{ + DisplayConfigGetDeviceInfo, GetDisplayConfigBufferSizes, QueryDisplayConfig, + DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME, + DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME, + DISPLAYCONFIG_TARGET_DEVICE_NAME, +}; use winreg::enums::HKEY_CURRENT_USER; use winreg::RegKey; @@ -84,14 +93,14 @@ impl ConnectionOps for Connection { } fn screens(&self) -> anyhow::Result { - // Iterate the monitors. - // The device names are things like "\\.\DISPLAY1" which isn't super - // user friendly. There may be an alternative API to get a better name, - // but for now this is good enough. struct Info { primary: Option, + active: Option, by_name: HashMap, virtual_rect: ScreenRect, + active_handle: HMONITOR, + friendly_names: HashMap, + gdi_to_adapater: HashMap, } unsafe extern "system" fn callback( @@ -105,17 +114,37 @@ impl ConnectionOps for Connection { mi.cbSize = std::mem::size_of::() as u32; GetMonitorInfoW(mon, &mut mi as *mut MONITORINFOEXW as *mut MONITORINFO); + let monitor_name = wstr(&mi.szDevice); + let friendly_name = match info.friendly_names.get(&monitor_name) { + Some(name) => name.to_string(), + None => { + // Fall back to EnumDisplayDevicesW. + // It likely has a terribly generic name like "Generic PnP Monitor". + let mut display_device: DISPLAY_DEVICEW = std::mem::zeroed(); + display_device.cb = std::mem::size_of::() as u32; + + if EnumDisplayDevicesW(mi.szDevice.as_ptr(), 0, &mut display_device, 0) != 0 { + wstr(&display_device.DeviceString) + } else { + "Unknown".to_string() + } + } + }; + + let adapter_name = match info.gdi_to_adapater.get(&monitor_name) { + Some(name) => name.to_string(), + None => "Unknown".to_string(), + }; + // "\\.\DISPLAY1" -> "DISPLAY1" - let len = mi.szDevice.iter().position(|&c| c == 0).unwrap_or(0); - let monitor_name = OsString::from_wide(&mi.szDevice[0..len]) - .to_string_lossy() - .to_string(); let monitor_name = if let Some(name) = monitor_name.strip_prefix("\\\\.\\") { name.to_string() } else { monitor_name }; + let monitor_name = format!("{monitor_name}: {friendly_name} on {adapter_name}"); + let screen_info = ScreenInfo { name: monitor_name.clone(), rect: euclid::rect( @@ -131,6 +160,9 @@ impl ConnectionOps for Connection { if mi.dwFlags & MONITORINFOF_PRIMARY == MONITORINFOF_PRIMARY { info.primary.replace(screen_info.clone()); } + if mon == info.active_handle { + info.active.replace(screen_info.clone()); + } info.by_name.insert(monitor_name, screen_info); @@ -139,8 +171,12 @@ impl ConnectionOps for Connection { let mut info = Info { primary: None, + active: None, by_name: HashMap::new(), virtual_rect: euclid::rect(0, 0, 0, 0), + active_handle: unsafe { MonitorFromWindow(GetFocus(), MONITOR_DEFAULTTONEAREST) }, + friendly_names: gdi_display_name_to_friendly_monitor_names()?, + gdi_to_adapater: gdi_display_name_to_adapter_names(), }; unsafe { EnumDisplayMonitors( @@ -154,8 +190,11 @@ impl ConnectionOps for Connection { let main = info .primary .ok_or_else(|| anyhow::anyhow!("There is no primary monitor configured!?"))?; + let active = info.active.unwrap_or_else(|| main.clone()); + Ok(Screens { main, + active, by_name: info.by_name, virtual_rect: info.virtual_rect, }) @@ -214,3 +253,119 @@ impl Connection { future } } + +/// Convert a UCS2 wide char string to a Rust String +fn wstr(slice: &[u16]) -> String { + let len = slice.iter().position(|&c| c == 0).unwrap_or(0); + OsString::from_wide(&slice[0..len]) + .to_string_lossy() + .to_string() +} + +/// Build a mapping of GDI paths like `\\.\DISPLAY6` to the name of the associated +/// display adapter eg: `NVIDIA GeForce RTX 3080 Ti`. +fn gdi_display_name_to_adapter_names() -> HashMap { + let mut map = HashMap::new(); + + let mut display_device: DISPLAY_DEVICEW = unsafe { std::mem::zeroed() }; + display_device.cb = std::mem::size_of::() as u32; + + for n in 0.. { + if unsafe { EnumDisplayDevicesW(std::ptr::null(), n, &mut display_device, 0) } == 0 { + break; + } + let adapter_name = wstr(&display_device.DeviceString); + let gdi_name = wstr(&display_device.DeviceName); + + map.insert(gdi_name, adapter_name); + } + map +} + +/// Build a mapping of GDI paths like `\\.\DISPLAY6` to the corresponding friendly name of +/// the associated monitor eg: `Gigabyte M32U`. +fn gdi_display_name_to_friendly_monitor_names() -> anyhow::Result> { + let mut paths: Vec = vec![]; + let mut modes: Vec = vec![]; + let mut map = HashMap::new(); + + let flags = QDC_ONLY_ACTIVE_PATHS | QDC_VIRTUAL_MODE_AWARE; + + loop { + let mut path_count = 0u32; + let mut mode_count = 0u32; + + let result = unsafe { + GetDisplayConfigBufferSizes(flags, &mut path_count as *mut _, &mut mode_count as *mut _) + }; + + if result != ERROR_SUCCESS as _ { + return Err(std::io::Error::last_os_error()).context("GetDisplayConfigBufferSizes"); + } + + unsafe { + paths.resize_with(path_count as usize, || std::mem::zeroed()); + modes.resize_with(mode_count as usize, || std::mem::zeroed()); + } + + let result = unsafe { + QueryDisplayConfig( + flags, + &mut path_count as *mut _, + paths.as_mut_ptr(), + &mut mode_count as &mut _, + modes.as_mut_ptr(), + std::ptr::null_mut(), + ) + }; + + // Shrink down if fewer paths than were requested were + // returned to us + unsafe { + paths.resize_with(path_count as usize, || std::mem::zeroed()); + modes.resize_with(mode_count as usize, || std::mem::zeroed()); + } + + if result == ERROR_INSUFFICIENT_BUFFER as _ { + continue; + } + + if result != ERROR_SUCCESS as _ { + return Err(std::io::Error::last_os_error()).context("QueryDisplayConfig"); + } + + break; + } + + for path in &paths { + let mut target_name: DISPLAYCONFIG_TARGET_DEVICE_NAME = unsafe { std::mem::zeroed() }; + + target_name.header.adapterId = path.targetInfo.adapterId; + target_name.header.id = path.targetInfo.id; + target_name.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME; + target_name.header.size = std::mem::size_of::() as u32; + + let result = unsafe { DisplayConfigGetDeviceInfo(&mut target_name.header) }; + if result != ERROR_SUCCESS as _ { + return Err(std::io::Error::last_os_error()) + .context("DisplayConfigGetDeviceInfo DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME"); + } + + let mut source_name: DISPLAYCONFIG_SOURCE_DEVICE_NAME = unsafe { std::mem::zeroed() }; + source_name.header.adapterId = path.targetInfo.adapterId; + source_name.header.r#type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; + source_name.header.size = std::mem::size_of::() as u32; + + let result = unsafe { DisplayConfigGetDeviceInfo(&mut source_name.header) }; + if result != ERROR_SUCCESS as _ { + return Err(std::io::Error::last_os_error()) + .context("DisplayConfigGetDeviceInfo DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME"); + } + + let name = wstr(&target_name.monitorFriendlyDeviceName); + let gdi_name = wstr(&source_name.viewGdiDeviceName); + + map.insert(gdi_name, name); + } + Ok(map) +} diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rs index 97014c825..d2f5feb0e 100644 --- a/window/src/os/windows/window.rs +++ b/window/src/os/windows/window.rs @@ -4,12 +4,12 @@ use crate::parameters::{self, Parameters}; use crate::{ Appearance, Clipboard, DeadKeyStatus, Dimensions, Handled, KeyCode, KeyEvent, Modifiers, MouseButtons, MouseCursor, MouseEvent, MouseEventKind, MousePress, Point, RawKeyEvent, Rect, - RequestedWindowGeometry, ScreenPoint, ULength, WindowDecorations, WindowEvent, - WindowEventSender, WindowOps, WindowState, + RequestedWindowGeometry, ResolvedGeometry, ScreenPoint, ULength, WindowDecorations, + WindowEvent, WindowEventSender, WindowOps, WindowState, }; use anyhow::{bail, Context}; use async_trait::async_trait; -use config::{ConfigHandle, DimensionContext, GeometryOrigin, ImePreeditRendering}; +use config::{ConfigHandle, ImePreeditRendering}; use lazy_static::lazy_static; use promise::Future; use raw_window_handle::windows::WindowsHandle; @@ -337,168 +337,6 @@ fn decorations_to_style(decorations: WindowDecorations) -> u32 { } } -#[derive(Debug)] -struct ResolvedGeometry { - x: i32, - y: i32, - width: usize, - height: usize, -} - -fn resolve_geom(geometry: RequestedWindowGeometry) -> ResolvedGeometry { - let mi = unsafe { - match geometry.origin { - GeometryOrigin::ScreenCoordinateSystem => { - // Compute the overall bounds of the virtual display - let mut mi: MONITORINFOEXW = std::mem::zeroed(); - - unsafe extern "system" fn callback( - _mon: HMONITOR, - _hdc: HDC, - rect: *mut RECT, - data: LPARAM, - ) -> i32 { - let mi: &mut MONITORINFOEXW = &mut *(data as *mut MONITORINFOEXW); - let rect: RECT = *rect; - mi.rcMonitor.left = mi.rcMonitor.left.min(rect.left); - mi.rcMonitor.top = mi.rcMonitor.top.min(rect.top); - mi.rcMonitor.right = mi.rcMonitor.right.max(rect.right); - mi.rcMonitor.bottom = mi.rcMonitor.bottom.max(rect.bottom); - winapi::shared::ntdef::TRUE.into() - } - EnumDisplayMonitors( - std::ptr::null_mut(), - std::ptr::null(), - Some(callback), - &mut mi as *mut _ as LPARAM, - ); - - mi - } - GeometryOrigin::MainScreen => { - // The main screen is known as the primary monitor on Windows - let mut mi: MONITORINFOEXW = std::mem::zeroed(); - mi.cbSize = std::mem::size_of::() as u32; - let mon = MonitorFromWindow(std::ptr::null_mut(), MONITOR_DEFAULTTOPRIMARY); - GetMonitorInfoW(mon, &mut mi as *mut MONITORINFOEXW as *mut MONITORINFO); - mi - } - GeometryOrigin::ActiveScreen => { - // Use the monitor of the focused window as the active screen - let mut mi: MONITORINFOEXW = std::mem::zeroed(); - mi.cbSize = std::mem::size_of::() as u32; - let mon = MonitorFromWindow(GetFocus(), MONITOR_DEFAULTTONEAREST); - GetMonitorInfoW(mon, &mut mi as *mut MONITORINFOEXW as *mut MONITORINFO); - mi - } - GeometryOrigin::Named(name) => { - // Iterate the monitors to find a match. - // The device names are things like "\\.\DISPLAY1" which isn't super - // user friendly. There may be an alternative API to get a better name, - // but for now this is good enough. - struct Info { - primary: Option, - named: Option, - all_names: Vec, - wanted_name: String, - } - - unsafe extern "system" fn callback( - mon: HMONITOR, - _hdc: HDC, - _rect: *mut RECT, - data: LPARAM, - ) -> i32 { - let info: &mut Info = &mut *(data as *mut Info); - let mut mi: MONITORINFOEXW = std::mem::zeroed(); - mi.cbSize = std::mem::size_of::() as u32; - GetMonitorInfoW(mon, &mut mi as *mut MONITORINFOEXW as *mut MONITORINFO); - if mi.dwFlags & MONITORINFOF_PRIMARY == MONITORINFOF_PRIMARY { - info.primary.replace(mi.clone()); - } - - // "\\.\DISPLAY1" -> "DISPLAY1" - let len = mi.szDevice.iter().position(|&c| c == 0).unwrap_or(0); - let monitor_name = OsString::from_wide(&mi.szDevice[0..len]) - .to_string_lossy() - .to_string(); - let monitor_name = if let Some(name) = monitor_name.strip_prefix("\\\\.\\") { - name.to_string() - } else { - monitor_name - }; - if info.wanted_name == monitor_name { - info.named.replace(mi.clone()); - } - info.all_names.push(monitor_name); - - winapi::shared::ntdef::TRUE.into() - } - - let mut info = Info { - primary: None, - named: None, - wanted_name: name, - all_names: vec![], - }; - EnumDisplayMonitors( - std::ptr::null_mut(), - std::ptr::null(), - Some(callback), - &mut info as *mut _ as LPARAM, - ); - - log::trace!("available displays: {:?}", info.all_names); - info.named - .or_else(|| { - log::error!( - "Requested display {} was not found; available displays are: {:?}. \ - Using primary display instead", - info.wanted_name, - info.all_names - ); - info.primary - }) - .expect("to find named monitor or primary") - } - } - }; - - let mon_width = (mi.rcMonitor.right - mi.rcMonitor.left) as f32; - let mon_height = (mi.rcMonitor.bottom - mi.rcMonitor.top) as f32; - - let width_context = DimensionContext { - dpi: crate::DEFAULT_DPI as f32, - pixel_max: mon_width, - pixel_cell: mon_width, - }; - let height_context = DimensionContext { - dpi: crate::DEFAULT_DPI as f32, - pixel_max: mon_height, - pixel_cell: mon_height, - }; - - let x_origin = mi.rcMonitor.left; - let y_origin = mi.rcMonitor.top; - - let width = geometry.width.evaluate_as_pixels(width_context) as usize; - let height = geometry.height.evaluate_as_pixels(height_context) as usize; - let x = geometry - .x - .map(|x| x.evaluate_as_pixels(width_context) as i32 + x_origin) - .unwrap_or(CW_USEDEFAULT); - let y = geometry - .y - .map(|y| y.evaluate_as_pixels(height_context) as i32 + y_origin) - .unwrap_or(CW_USEDEFAULT); - ResolvedGeometry { - x, - y, - width, - height, - } -} - impl Window { fn create_window( config: ConfigHandle, @@ -632,7 +470,9 @@ impl Window { // Careful: `raw` owns a ref to inner, but there is no Drop impl let raw = rc_to_pointer(&inner); - let geometry = resolve_geom(geometry); + let conn = Connection::get().expect("Connection::init was not called"); + + let geometry = conn.resolve_geometry(geometry); let hwnd = match Self::create_window(config, class_name, name, geometry, raw) { Ok(hwnd) => HWindow(hwnd), @@ -656,9 +496,7 @@ impl Window { DragAcceptFiles(hwnd.0, winapi::shared::minwindef::TRUE); } - Connection::get() - .expect("Connection::init was not called") - .windows + conn.windows .borrow_mut() .insert(hwnd.clone(), Rc::clone(&inner)); diff --git a/window/src/os/x11/connection.rs b/window/src/os/x11/connection.rs index 37e7f534e..5690b5f41 100644 --- a/window/src/os/x11/connection.rs +++ b/window/src/os/x11/connection.rs @@ -201,8 +201,16 @@ impl ConnectionOps for XConnection { .ok_or_else(|| anyhow::anyhow!("no screens were found"))? .clone(); + // We don't yet know how to determine the active screen, + // so assume the main screen. + // TODO: find focused window and resolve it! + // Maybe something like + // but ported to Rust? + let active = main.clone(); + Ok(Screens { main, + active, by_name, virtual_rect, }) diff --git a/window/src/os/x11/window.rs b/window/src/os/x11/window.rs index 384699ac8..7f941fda8 100644 --- a/window/src/os/x11/window.rs +++ b/window/src/os/x11/window.rs @@ -951,7 +951,7 @@ impl XWindow { y, width, height, - } = resolve_geometry(&conn, geometry)?; + } = conn.resolve_geometry(geometry); let mut events = WindowEventSender::new(event_handler); @@ -1520,75 +1520,3 @@ impl WindowOps for XWindow { }); } } - -#[derive(Debug)] -struct ResolvedGeometry { - x: i16, - y: i16, - width: usize, - height: usize, -} - -fn resolve_geometry( - conn: &XConnection, - geometry: RequestedWindowGeometry, -) -> anyhow::Result { - let bounds = match conn.screens() { - Ok(screens) => { - log::trace!("{screens:?}"); - - match geometry.origin { - GeometryOrigin::ScreenCoordinateSystem => screens.virtual_rect, - GeometryOrigin::MainScreen => screens.main.rect, - GeometryOrigin::ActiveScreen => { - // TODO: find focused window and resolve it! - // Maybe something like - // but ported to Rust? - screens.main.rect - } - GeometryOrigin::Named(name) => match screens.by_name.get(&name) { - Some(info) => info.rect.clone(), - None => { - log::error!( - "Requested display {} was not found; available displays are: {:?}. \ - Using primary display instead", - name, - screens.by_name, - ); - screens.main.rect - } - }, - } - } - Err(_) => euclid::rect(0, 0, 65535, 65535), - }; - - let dpi = conn.default_dpi(); - let width_context = DimensionContext { - dpi: dpi as f32, - pixel_max: bounds.width() as f32, - pixel_cell: bounds.width() as f32, - }; - let height_context = DimensionContext { - dpi: dpi as f32, - pixel_max: bounds.height() as f32, - pixel_cell: bounds.height() as f32, - }; - let width = geometry.width.evaluate_as_pixels(width_context) as usize; - let height = geometry.height.evaluate_as_pixels(height_context) as usize; - let x = geometry - .x - .map(|x| x.evaluate_as_pixels(width_context) as i16 + bounds.origin.x as i16) - .unwrap_or(0); - let y = geometry - .y - .map(|y| y.evaluate_as_pixels(height_context) as i16 + bounds.origin.y as i16) - .unwrap_or(0); - - Ok(ResolvedGeometry { - x, - y, - width, - height, - }) -} diff --git a/window/src/screen.rs b/window/src/screen.rs index 3b75bcdcd..ad9871ca8 100644 --- a/window/src/screen.rs +++ b/window/src/screen.rs @@ -4,6 +4,7 @@ use std::collections::HashMap; #[derive(Debug, Clone)] pub struct Screens { pub main: ScreenInfo, + pub active: ScreenInfo, pub by_name: HashMap, pub virtual_rect: ScreenRect, }