From dead55af216b6690e5ab1fdd1cfba138e216c047 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Wed, 2 Dec 2026 18:16:48 +0800 Subject: [PATCH] feat(windows): open project windows on the display last worked on (#7123) On Windows, the display of the last focused or moved project window is saved to last-display.json. A project window opened without a position of its own is centred on that display and sized to its work area while the display is still connected and unchanged; otherwise it opens on the primary display. Cascaded windows keep their place, and macOS and Linux are unchanged. Fixes #7031 --- src-tauri/src/lib.rs | 8 ++ src-tauri/src/window_display.rs | 135 ++++++++++++++++++++++++++++++++ src-tauri/src/windows.rs | 4 +- 3 files changed, 145 insertions(+), 2 deletions(-) create mode 100644 src-tauri/src/window_display.rs diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index fa4366acbe..39f5cd29e3 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -38,6 +38,8 @@ mod theme_frame; #[cfg(target_os = "macos")] mod titlebar; mod updates; +#[cfg(any(windows, test))] +mod window_display; mod window_groups; #[cfg(any(windows, test))] mod window_work_area; @@ -295,6 +297,8 @@ pub fn run() { } tauri::WindowEvent::Focused(true) => { application_focus::changed(window.app_handle(), true); + #[cfg(windows)] + window_display::remember(window); if let Some(w) = window.try_state::() { w.focused(window.label()); } @@ -302,6 +306,10 @@ pub fn run() { tauri::WindowEvent::Focused(false) => application_focus::changed(window.app_handle(), false), tauri::WindowEvent::Moved(_) | tauri::WindowEvent::Resized(_) => { window_groups::frame_changed(window.app_handle(), window.label()); + #[cfg(windows)] + if matches!(event, tauri::WindowEvent::Moved(_)) { + window_display::remember(window); + } } tauri::WindowEvent::Destroyed => { // Also release a view that failed during startup, before the parent could watch it. diff --git a/src-tauri/src/window_display.rs b/src-tauri/src/window_display.rs new file mode 100644 index 0000000000..c870718c17 --- /dev/null +++ b/src-tauri/src/window_display.rs @@ -0,0 +1,135 @@ +//! The display the user last worked on, on Windows. The window-state plugin restores only the +//! maximized and full-screen flags there (`window_state_flags`), so without this every project +//! window that opens at launch, or after the last one closed, lands on the primary display. + +use serde::{Deserialize, Serialize}; + +/// A display by its physical position and size in the virtual screen. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +struct Display { + x: i32, + y: i32, + width: u32, + height: u32, +} + +/// The connected display that is the saved one: same position and size. Displays rearranged or +/// resized since then are not matched, so the window opens on the primary display as before. +fn find(connected: &[Display], saved: Display) -> Option { + connected.iter().position(|d| *d == saved) +} + +/// The top-left corner, in the display's logical pixels, that centres a window of `size` in a +/// work area at `origin` of `area` (both logical). +fn centred(origin: (f64, f64), area: (f64, f64), size: (f64, f64)) -> (f64, f64) { + (origin.0 + ((area.0 - size.0) / 2.0).max(0.0), origin.1 + ((area.1 - size.1) / 2.0).max(0.0)) +} + +#[cfg(windows)] +pub use native::{place, remember}; + +#[cfg(windows)] +mod native { + use super::{Display, centred, find}; + use parking_lot::Mutex; + use std::path::PathBuf; + use tauri::{AppHandle, Manager, Monitor, Runtime, Window, utils::config::WindowConfig}; + + const FILE: &str = "last-display.json"; + + /// The saved display, read from disk once. + static SAVED: Mutex>> = Mutex::new(None); + + fn display(monitor: &Monitor) -> Display { + let (position, size) = (monitor.position(), monitor.size()); + Display { x: position.x, y: position.y, width: size.width, height: size.height } + } + + fn file(app: &AppHandle) -> Option { + ide_host::data_dirs::config_dir(&app.config().identifier).ok().map(|dir| dir.join(FILE)) + } + + fn saved(app: &AppHandle) -> Option { + *SAVED.lock().get_or_insert_with(|| { + let text = std::fs::read_to_string(file(app)?).ok()?; + serde_json::from_str(&text).ok() + }) + } + + /// Records the display a project window is on, when it is focused or moved. + pub fn remember(window: &Window) { + if crate::windows::auxiliary_parent(window.label()).is_some() { + return; + } + let Ok(Some(monitor)) = window.current_monitor() else { return }; + let now = display(&monitor); + let app = window.app_handle(); + if saved(app) == Some(now) { + return; + } + *SAVED.lock() = Some(Some(now)); + let Some(path) = file(app) else { return }; + if let Ok(text) = serde_json::to_string(&now) + && let Err(e) = std::fs::write(&path, text) + { + tracing::debug!("cannot save {}: {e}", path.display()); + } + } + + /// Where a new project window opens: the saved display when it is still connected, else the + /// primary one. A window without a position of its own (not cascaded from another window) is + /// centred on it. Returns the display, whose work area sizes the window. + pub fn place(app: &AppHandle, config: &mut WindowConfig) -> Option { + let primary = app.primary_monitor().ok().flatten(); + if config.x.is_some() { + return primary; + } + let connected = app.available_monitors().unwrap_or_default(); + let displays: Vec = connected.iter().map(display).collect(); + let Some(monitor) = saved(app).and_then(|s| find(&displays, s)).map(|i| connected[i].clone()) else { + return primary; + }; + if primary.as_ref().is_some_and(|p| display(p) == display(&monitor)) { + return primary; + } + let scale = monitor.scale_factor(); + let area = monitor.work_area(); + let origin = area.position.to_logical::(scale); + let size = area.size.to_logical::(scale); + let window = (config.width.min(size.width), config.height.min(size.height)); + let (x, y) = centred((origin.x, origin.y), (size.width, size.height), window); + // tao places a logical position on the display it falls on, using that display's scale. + config.x = Some(x); + config.y = Some(y); + config.center = false; + Some(monitor) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const PRIMARY: Display = Display { x: 0, y: 0, width: 2560, height: 1440 }; + const SECOND: Display = Display { x: 2560, y: 0, width: 1920, height: 1080 }; + + #[test] + fn finds_the_saved_display_only_while_it_is_connected_unchanged() { + assert_eq!(find(&[PRIMARY, SECOND], SECOND), Some(1)); + assert_eq!(find(&[PRIMARY], SECOND), None); + // Rearranged to the left of the primary display: not the saved one any more. + assert_eq!(find(&[PRIMARY, Display { x: -1920, ..SECOND }], SECOND), None); + } + + #[test] + fn centres_in_the_work_area_and_keeps_a_larger_window_at_its_corner() { + assert_eq!(centred((2560.0, 0.0), (1920.0, 1040.0), (1440.0, 900.0)), (2800.0, 70.0)); + assert_eq!(centred((2560.0, 0.0), (1280.0, 680.0), (1440.0, 900.0)), (2560.0, 0.0)); + } + + #[test] + fn the_saved_display_round_trips_through_json() { + let text = serde_json::to_string(&SECOND).unwrap(); + assert_eq!(serde_json::from_str::(&text).unwrap(), SECOND); + } +} diff --git a/src-tauri/src/windows.rs b/src-tauri/src/windows.rs index 0137ad7275..ec66daffdf 100644 --- a/src-tauri/src/windows.rs +++ b/src-tauri/src/windows.rs @@ -1102,9 +1102,9 @@ fn build_project_window(app: &AppHandle, mut config: WindowConfig) -> IdeResult< #[cfg(target_os = "linux")] let show_after_build = crate::linux_window_state::prepare(app, &mut config); // Windows opens a project window at the configured size (window-state restores only the - // maximized flag there), which Restore Down returns to. + // maximized flag there), which Restore Down returns to, on the display last worked on. #[cfg(windows)] - if let Ok(Some(monitor)) = app.primary_monitor() { + if let Some(monitor) = crate::window_display::place(app, &mut config) { let area = monitor.work_area().size.to_logical::(monitor.scale_factor()); let min = (config.min_width.unwrap_or(0.0), config.min_height.unwrap_or(0.0)); let (size, min) = fit_new_window((config.width, config.height), min, (area.width, area.height));