Merge pull request #10989 from dotCooCoo/fix/monitor-work-area-placement

Windows: dialogs and popups open on a connected monitor, clear of the taskbar
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-05 15:45:59 -08:00
commit 66b6db183d
2 files changed
+255 -15

No files matched your search

+6 -15
View File
@@ -68,6 +68,7 @@ mod single_instance;
mod system_fonts;
mod tablet;
mod window_frame;
mod window_system;
mod windows_alt_codes;
#[cfg(windows)]
mod windows_cores;
@@ -116,20 +117,9 @@ const MIN_SIZE: [f32; 2] = [800.0, 500.0];
/// framework maximizes the window when its default size would not fit the current screen.
fn restore_main_window(window: &winit::window::Window, store: &Store, legacy: Option<vectorcraft_ui_egui::state::LegacyWindow>, wayland: bool) {
use craft::behavior::placement::{Defaults, Placement, place};
use craft::behavior::{Monitor, MonitorKey};
use winit::dpi::{LogicalSize, PhysicalPosition};
let handles: Vec<_> = window.available_monitors().collect();
let monitors: Vec<_> = handles
.iter()
.map(|monitor| {
let size = monitor.size();
let size = [size.width, size.height];
let position = monitor.position();
Monitor::new(MonitorKey::new(monitor.name().unwrap_or_default(), size), [position.x, position.y], size, monitor.scale_factor() as f32)
})
.collect();
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor));
let (monitors, home) = window_system::monitor_layout(window).unwrap_or_default();
let defaults = Defaults::new(DEFAULT_SIZE, MIN_SIZE).with_no_position(wayland);
let saved = store.get(craft::window::restore::MAIN).or_else(|| {
let old = legacy?;
@@ -896,9 +886,10 @@ fn main() -> std::process::ExitCode {
restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland);
}
// A pen or a finger in contact counts as the primary button (`windows_stylus`).
let spec = main_window_spec(shell_info, Arc::new(windows_stylus::ContactWindows), host_services::open_link)
.placement(Arc::new(Mutex::new(placement)))
.frame(decision);
let spec =
main_window_spec(shell_info, Arc::new(window_system::DesktopWindows::new(winit_window.as_ref())), host_services::open_link)
.placement(Arc::new(Mutex::new(placement)))
.frame(decision);
let spec = match start_pen(&winit_window) {
Some(pen) => spec.pen(pen),
None => spec,
+249
View File
@@ -0,0 +1,249 @@
//! The desktop's monitors for window and popup placement: where each one is, its size and scale, and on Windows the
//! part the taskbar leaves free.
use std::panic::AssertUnwindSafe;
use std::sync::{Arc, Mutex, PoisonError, Weak};
use std::time::{Duration, Instant};
use craft::behavior::{Monitor, MonitorKey};
use craft::window::system::{HeldButtons, WindowSystem};
use winit::window::Window;
use crate::windows_stylus::ContactWindows;
/// How long one listing of the monitors is used. Placement asks for the monitors several times a frame; a display
/// that is added, removed or moved shows up in the first listing after this.
const RELIST_AFTER: Duration = Duration::from_secs(1);
/// The monitors in physical desktop pixels, and the index of the one showing `window` (else the primary one).
/// `None` when winit stops on a display that went away while it was being listed (Windows).
pub(super) fn monitor_layout(window: &Window) -> Option<(Vec<Monitor>, Option<usize>)> {
let listing = std::panic::catch_unwind(AssertUnwindSafe(|| {
let handles: Vec<_> = window.available_monitors().collect();
let home = window.current_monitor().or_else(|| window.primary_monitor()).and_then(|monitor| handles.iter().position(|m| *m == monitor));
let monitors = handles
.iter()
.map(|handle| {
let size = handle.size();
let size = [size.width, size.height];
let position = handle.position();
let monitor = Monitor::new(
MonitorKey::new(handle.name().unwrap_or_default(), size),
[position.x, position.y],
size,
handle.scale_factor() as f32,
);
match work_px(&monitor) {
Some((pos, size)) => monitor.with_work_px(pos, size),
None => monitor,
}
})
.collect();
(monitors, home)
}));
listing.map_err(|_| log::debug!("a display went away while the monitors were listed")).ok()
}
/// The work area of the monitor whose top-left pixel is `monitor`'s, from `GetMonitorInfo`. winsafe comes with the
/// wgpu renderer, which every desktop package builds with.
#[cfg(all(windows, feature = "wgpu"))]
fn work_px(monitor: &Monitor) -> Option<([i32; 2], [u32; 2])> {
use winsafe::{HMONITOR, POINT, co};
let [x, y] = monitor.pos_px;
let info = HMONITOR::MonitorFromPoint(POINT { x, y }, co::MONITOR::DEFAULTTONULL).GetMonitorInfo().ok()?;
let work = info.rcWork;
from_edges(work.left, work.top, work.right, work.bottom)
}
/// Other platforms report no work area.
#[cfg(not(all(windows, feature = "wgpu")))]
fn work_px(_: &Monitor) -> Option<([i32; 2], [u32; 2])> {
None
}
/// The top-left corner and size of the pixel rectangle with these edges; `None` for an empty or inverted one.
#[cfg(any(all(windows, feature = "wgpu"), test))]
fn from_edges(left: i32, top: i32, right: i32, bottom: i32) -> Option<([i32; 2], [u32; 2])> {
let width = u32::try_from(right.checked_sub(left)?).ok().filter(|w| *w > 0)?;
let height = u32::try_from(bottom.checked_sub(top)?).ok().filter(|h| *h > 0)?;
Some(([left, top], [width, height]))
}
/// The platform's window services with a pen or a finger in contact counted as the primary button
/// ([`ContactWindows`]), and the monitors listed through winit. On macOS no monitors are listed: winit
/// gives each display's position in that display's own scale, so the pixel areas of displays with different scales
/// overlap and placement could pick the wrong one. Elsewhere monitors with different scales are not listed either
/// ([`one_scale`]).
pub(super) struct DesktopWindows {
list: Box<dyn Fn() -> Option<Vec<Monitor>> + Send + Sync>,
now: Box<dyn Fn() -> Instant + Send + Sync>,
/// The last listing that succeeded, and when it was made.
listed: Mutex<Option<(Instant, Vec<Monitor>)>>,
}
impl DesktopWindows {
/// Lists the monitors of `window`'s desktop; none without a window, and none on macOS.
pub(super) fn new(window: Option<&Arc<Window>>) -> Self {
let window = if cfg!(target_os = "macos") { Weak::new() } else { window.map_or_else(Weak::new, Arc::downgrade) };
Self::with(move || window.upgrade().and_then(|window| monitor_layout(&window)).map(|(monitors, _)| monitors), Instant::now)
}
/// Lists the monitors with `list` (`None` when a listing fails), timed by `now`.
fn with(list: impl Fn() -> Option<Vec<Monitor>> + Send + Sync + 'static, now: impl Fn() -> Instant + Send + Sync + 'static) -> Self {
Self { list: Box::new(list), now: Box::new(now), listed: Mutex::default() }
}
}
impl WindowSystem for DesktopWindows {
fn desktop_pointer(&self) -> Option<[f32; 2]> {
ContactWindows.desktop_pointer()
}
fn buttons_held(&self) -> Option<HeldButtons> {
ContactWindows.buttons_held()
}
fn discard_marked_text(&self) -> bool {
ContactWindows.discard_marked_text()
}
fn command_held(&self) -> Option<bool> {
ContactWindows.command_held()
}
fn warp_pointer(&self, to: [f32; 2]) -> bool {
ContactWindows.warp_pointer(to)
}
/// The monitors of the last listing, listed again once [`RELIST_AFTER`] has passed. A listing that fails keeps
/// the last one, and the next call lists again.
fn monitors(&self) -> Vec<Monitor> {
let now = (self.now)();
let mut listed = self.listed.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((at, monitors)) = listed.as_ref()
&& now.saturating_duration_since(*at) < RELIST_AFTER
{
return monitors.clone();
}
match (self.list)().map(one_scale) {
Some(monitors) => {
*listed = Some((now, monitors.clone()));
monitors
}
None => listed.as_ref().map(|(_, monitors)| monitors.clone()).unwrap_or_default(),
}
}
}
/// `monitors` when they all have one scale, else none. The framework finds the monitor a palette window is on by
/// testing the window's corner, in the window's own points, at each monitor's scale, so with mixed scales a palette
/// on one monitor can be matched to another and its popups kept in that monitor's work area. Without a listing,
/// popups stay within the span of the app's windows and dialogs reopen where they were saved.
fn one_scale(monitors: Vec<Monitor>) -> Vec<Monitor> {
let mixed = monitors.windows(2).any(|pair| pair[0].scale != pair[1].scale);
if mixed { Vec::new() } else { monitors }
}
#[cfg(test)]
mod tests {
use super::*;
use craft::behavior::placement::{Defaults, Placement, place};
use std::sync::atomic::{AtomicUsize, Ordering};
fn monitor(name: &str, pos: [i32; 2], size: [u32; 2], scale: f32) -> Monitor {
Monitor::new(MonitorKey::new(name, size), pos, size, scale)
}
/// A clock the test moves.
fn clock() -> (Arc<Mutex<Instant>>, impl Fn() -> Instant + Send + Sync + 'static) {
let time = Arc::new(Mutex::new(Instant::now()));
let read = Arc::clone(&time);
(time, move || *read.lock().unwrap())
}
fn advance(time: &Mutex<Instant>, by: Duration) {
let mut now = time.lock().unwrap();
*now += by;
}
/// The monitors come from the desktop listing, which runs once per [`RELIST_AFTER`] however often placement asks,
/// and a display that changed shows up in the next listing.
#[test]
fn monitors_are_listed_once_a_second_and_follow_display_changes() {
let listings = Arc::new(AtomicUsize::new(0));
let count = Arc::clone(&listings);
let (time, now) = clock();
let system = DesktopWindows::with(
move || {
let n = count.fetch_add(1, Ordering::SeqCst);
let mut monitors = vec![monitor("A", [0, 0], [1920, 1080], 1.0)];
if n > 0 {
monitors.push(monitor("B", [1920, 0], [2560, 1440], 1.0));
}
Some(monitors)
},
now,
);
let names = |monitors: Vec<Monitor>| monitors.into_iter().map(|m| m.key.name).collect::<Vec<_>>();
assert_eq!(names(system.monitors()), ["A"]);
assert_eq!(names(system.monitors()), ["A"]);
advance(&time, RELIST_AFTER - Duration::from_millis(1));
assert_eq!(names(system.monitors()), ["A"]);
assert_eq!(listings.load(Ordering::SeqCst), 1, "calls within the reuse time share one listing");
advance(&time, Duration::from_millis(1));
assert_eq!(names(system.monitors()), ["A", "B"], "the added display shows up in the next listing");
assert_eq!(listings.load(Ordering::SeqCst), 2);
}
/// A listing that fails (a display went away while it was listed) keeps the last monitors, and the next call
/// lists again instead of waiting for the reuse time.
#[test]
fn a_failed_listing_keeps_the_last_monitors() {
let listings = Arc::new(AtomicUsize::new(0));
let count = Arc::clone(&listings);
let (time, now) = clock();
let system =
DesktopWindows::with(move || (count.fetch_add(1, Ordering::SeqCst) == 0).then(|| vec![monitor("A", [0, 0], [1920, 1080], 1.0)]), now);
assert_eq!(system.monitors().len(), 1);
advance(&time, RELIST_AFTER);
assert_eq!(system.monitors().len(), 1, "the failed listing keeps the last one");
assert_eq!(system.monitors().len(), 1);
assert_eq!(listings.load(Ordering::SeqCst), 3, "each call after a failed listing lists again");
}
/// A dialog saved on a monitor that is no longer connected (or at a place no monitor shows) reopens with its whole
/// frame inside a connected monitor's work area, clear of the taskbar.
#[test]
fn a_dialog_saved_off_every_monitor_opens_inside_a_work_area() {
let (_, now) = clock();
let system = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0).with_work_px([0, 0], [1920, 1040])]), now);
let mut saved = Placement::new([600.0, 400.0], 1.0);
saved.position_px = Some([3000, 900]);
let placed = place(Some(&saved), &system.monitors(), None, &Defaults::new([600.0, 400.0], [200.0, 100.0]));
let [x, y] = placed.position_px.expect("the dialog keeps a position");
let [width, height] = placed.normal.size;
let frame = egui::Rect::from_min_size(egui::pos2(x as f32, y as f32), egui::vec2(width, height));
let work = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1920.0, 1040.0));
assert!(work.contains_rect(frame), "{frame:?} is inside {work:?}");
}
/// Monitors with different scales are not listed, so a palette's popups on a scale-2 monitor beside a scale-1 one
/// are not kept in the other monitor's work area; monitors that share a scale are listed.
#[test]
fn monitors_with_mixed_scales_are_not_listed() {
let (_, now) = clock();
let mixed = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [1920, 1080], 1.0), monitor("B", [1920, 0], [3840, 2160], 2.0)]), now);
assert!(mixed.monitors().is_empty(), "mixed scales list no monitors");
let (_, now) = clock();
let shared = DesktopWindows::with(|| Some(vec![monitor("A", [0, 0], [3840, 2160], 1.5), monitor("B", [3840, 0], [3840, 2160], 1.5)]), now);
assert_eq!(shared.monitors().len(), 2, "one scale lists every monitor");
}
#[test]
fn work_area_edges_give_corner_and_size() {
assert_eq!(from_edges(-1920, -200, 0, 840), Some(([-1920, -200], [1920, 1040])));
assert_eq!(from_edges(0, 0, 0, 1040), None, "no width");
assert_eq!(from_edges(100, 0, 0, 1040), None, "inverted");
assert_eq!(from_edges(i32::MIN, 0, i32::MAX, 10), None, "overflowing width");
}
}