From aae32d4650b904807a1534a09d3301911e783759 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 13:12:48 -0800 Subject: [PATCH 1/2] Windows: dialogs and popups open on a connected monitor, clear of the taskbar The desktop app passed the framework a window system that lists no monitors, so a dialog such as Preferences reopened at its saved desktop position without being fitted to any display, and palette popups had no monitor to stay inside. The app's window system now lists the monitors through winit, with each monitor's work area on Windows (GetMonitorInfo), so a saved dialog that no connected monitor shows comes back onto one with its title bar reachable, and popups stay above the taskbar. A listing is reused for one second and kept when winit stops on a display that went away while it was listed. macOS lists no monitors, as before: winit gives each display's position in that display's own scale, so displays with different scales overlap. The main window's restore uses the same listing. Fixes #10230 Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com> --- apps/vectorcraft/src/main.rs | 17 +- apps/vectorcraft/src/window_system.rs | 224 ++++++++++++++++++++++++++ 2 files changed, 227 insertions(+), 14 deletions(-) create mode 100644 apps/vectorcraft/src/window_system.rs diff --git a/apps/vectorcraft/src/main.rs b/apps/vectorcraft/src/main.rs index 63135d00e5..ff8a113827 100644 --- a/apps/vectorcraft/src/main.rs +++ b/apps/vectorcraft/src/main.rs @@ -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; @@ -91,7 +92,6 @@ use craft::ui::shell::embed; use craft::window::Prefix; use craft::window::policy::{TitleBarPref, decide_for}; use craft::window::restore::Store; -use craft::window::system::SystemWindows; use vectorcraft_engine::Session; use vectorcraft_engine::cmd::fileio; use vectorcraft_engine::file_access::{self, AutomationRoots}; @@ -117,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, 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?; @@ -885,7 +874,7 @@ fn main() -> std::process::ExitCode { if let Some(window) = &winit_window { restore_main_window(window, &placement, settings.lock().get().ui.legacy_window, wayland); } - let spec = InstallSpec::new(shell_info, Arc::new(SystemWindows)) + let spec = InstallSpec::new(shell_info, Arc::new(window_system::DesktopWindows::new(winit_window.as_ref()))) .app_id(vectorcraft_ui_egui::os_window::app_id()) .placement(Arc::new(Mutex::new(placement))) .frame(decision); diff --git a/apps/vectorcraft/src/window_system.rs b/apps/vectorcraft/src/window_system.rs new file mode 100644 index 0000000000..d05bb80d65 --- /dev/null +++ b/apps/vectorcraft/src/window_system.rs @@ -0,0 +1,224 @@ +//! 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, SystemWindows, WindowSystem}; +use winit::window::Window; + +/// 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, Option)> { + 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 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. +pub(super) struct DesktopWindows { + list: Box Option> + Send + Sync>, + now: Box Instant + Send + Sync>, + /// The last listing that succeeded, and when it was made. + listed: Mutex)>>, +} + +impl DesktopWindows { + /// Lists the monitors of `window`'s desktop; none without a window, and none on macOS. + pub(super) fn new(window: Option<&Arc>) -> 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> + 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]> { + SystemWindows.desktop_pointer() + } + + fn buttons_held(&self) -> Option { + SystemWindows.buttons_held() + } + + fn discard_marked_text(&self) -> bool { + SystemWindows.discard_marked_text() + } + + fn command_held(&self) -> Option { + SystemWindows.command_held() + } + + fn warp_pointer(&self, to: [f32; 2]) -> bool { + SystemWindows.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 { + 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)() { + Some(monitors) => { + *listed = Some((now, monitors.clone())); + monitors + } + None => listed.as_ref().map(|(_, monitors)| monitors.clone()).unwrap_or_default(), + } + } +} + +#[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>, 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, 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| monitors.into_iter().map(|m| m.key.name).collect::>(); + 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:?}"); + } + + #[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"); + } +} From 4fe7cbfbf6d4ec55cc7f2e588fe9af12c5d8af2e Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 5 Dec 2026 14:09:57 -0800 Subject: [PATCH 2/2] Windows: list no monitors when their scales differ The framework finds the monitor a palette window is on by testing the window's top-left corner, in the window's own points, at each listed monitor's scale. With a scale-1 primary listed before a scale-2 secondary, a palette on the secondary matched the primary, and its popups were kept in the primary's work area, away from their opener. The desktop window system now lists monitors only when they all share one scale. On a desktop with mixed scales, popups stay within the span of the app's windows and dialogs reopen where they were saved, as before this branch. --- apps/vectorcraft/src/window_system.rs | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/apps/vectorcraft/src/window_system.rs b/apps/vectorcraft/src/window_system.rs index d05bb80d65..7e87d5dca8 100644 --- a/apps/vectorcraft/src/window_system.rs +++ b/apps/vectorcraft/src/window_system.rs @@ -69,7 +69,8 @@ fn from_edges(left: i32, top: i32, right: i32, bottom: i32) -> Option<([i32; 2], /// The platform's window services, with 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. +/// 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 Option> + Send + Sync>, now: Box Instant + Send + Sync>, @@ -121,7 +122,7 @@ impl WindowSystem for DesktopWindows { { return monitors.clone(); } - match (self.list)() { + match (self.list)().map(one_scale) { Some(monitors) => { *listed = Some((now, monitors.clone())); monitors @@ -131,6 +132,15 @@ impl WindowSystem for DesktopWindows { } } +/// `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) -> Vec { + 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::*; @@ -214,6 +224,18 @@ mod tests { 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])));