Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

fix(window): restore main window geometry in logical units on macOS

t8y2d145aa4e8f20
diff --git a/src-tauri/src/commands/app_settings.rs b/src-tauri/src/commands/app_settings.rs
index f605b09aeb..d53dc21917 100644
--- a/src-tauri/src/commands/app_settings.rs
+++ b/src-tauri/src/commands/app_settings.rs
@@ -165,6 +165,10 @@ pub async fn complete_app_close(app: AppHandle, window: Window, action: String)
// Take the whole app off-screen first so WKWebView teardown during
// process exit cannot flash the window red on macOS 12. `AppHandle::hide`
// is macOS-only, so this block is compiled per-platform.
+ // Hiding can blank the frame, and the window-state plugin saves
+ // at exit; keep the geometry `request_app_close` captured while
+ // the window was still visible (issue #13168).
+ crate::window_state_guard::remember_main_window_geometry(&app);
let _ = window.hide();
let _ = app.hide();
tokio::time::sleep(std::time::Duration::from_millis(crate::EXIT_HIDE_GRACE_MS)).await;
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 97cf34bb61..e9a9677eee 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -23,6 +23,7 @@ mod webview2_legacy_css;
mod webview2_preflight;
#[cfg(any(target_os = "windows", test))]
mod webview2_recovery;
+mod window_geometry;
mod window_state_guard;
#[cfg(target_os = "windows")]
mod windows_appcompat;
@@ -770,6 +771,11 @@ pub(crate) fn request_app_close<R: tauri::Runtime>(app: &tauri::AppHandle<R>, ta
return;
}
show_main_window(app);
+ // The prompt only resolves to a quit after the user answers, by which
+ // point the window may already be hidden. Record its visible frame now;
+ // `complete_app_close` and the dock/menu quit keep this capture unless the
+ // window has meanwhile moved.
+ window_state_guard::remember_main_window_geometry(app);
let _ = app.emit(APP_CLOSE_REQUESTED_EVENT, target);
}
@@ -1939,6 +1945,9 @@ pub fn run() {
.plugin(
tauri_plugin_window_state::Builder::default()
.with_state_flags(window_state_guard::persisted_main_window_state_flags())
+ // The main window's geometry is restored by `window_state_guard`
+ // in logical units; the plugin's physical restore is the bug in
+ // issue #13168.
.skip_initial_state("main")
.build(),
);
@@ -3165,6 +3174,7 @@ pub fn run() {
// shutdown below gives WindowServer time to remove it.
if should_hide_window_before_exit(std::env::consts::OS) {
if let Some(window) = app_handle.get_webview_window("main") {
+ window_state_guard::remember_main_window_geometry(app_handle);
let _ = window.hide();
}
}
diff --git a/src-tauri/src/window_geometry.rs b/src-tauri/src/window_geometry.rs
new file mode 100644
index 0000000000..ebd1e7401e
--- /dev/null
+++ b/src-tauri/src/window_geometry.rs
@@ -0,0 +1,208 @@
+//! Display-space conversions for window geometry (issue #13168).
+//!
+//! A window reports its position/size as `logical value × the factor of the
+//! display it is on`, while Tauri reports every monitor rect as `its logical
+//! bounds × its own factor`. `LogicalPosition/LogicalSize` are passed through
+//! untouched, so a physical rect is meaningful only together with the factor it
+//! was captured at: reading 1x pixels at 2x, as `tauri-plugin-window-state`
+//! does when it cannot find the saved display, halves them.
+
+/// A physical-pixel rectangle: a window outer frame reported at one factor, or
+/// a display in the origin-relative space of that factor.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) struct PhysicalWindowRect {
+ pub(crate) x: i32,
+ pub(crate) y: i32,
+ pub(crate) width: u32,
+ pub(crate) height: u32,
+}
+
+/// The same rectangle in logical units (`scale_factor = 1`).
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) struct LogicalRect {
+ pub(crate) x: f64,
+ pub(crate) y: f64,
+ pub(crate) width: f64,
+ pub(crate) height: f64,
+}
+
+/// A display as Tauri reports it, plus its own scale factor.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) struct MonitorRect {
+ pub(crate) x: i32,
+ pub(crate) y: i32,
+ pub(crate) width: u32,
+ pub(crate) height: u32,
+ pub(crate) scale_factor: f64,
+}
+
+impl From<&tauri::Monitor> for MonitorRect {
+ fn from(monitor: &tauri::Monitor) -> Self {
+ let (position, size) = (*monitor.position(), *monitor.size());
+ Self {
+ x: position.x,
+ y: position.y,
+ width: size.width,
+ height: size.height,
+ scale_factor: clean_scale_factor(monitor.scale_factor()),
+ }
+ }
+}
+
+impl MonitorRect {
+ pub(crate) fn contains_point(&self, x: i32, y: i32) -> bool {
+ let (x, y, left, top) = (i64::from(x), i64::from(y), i64::from(self.x), i64::from(self.y));
+ x >= left && x < left + i64::from(self.width) && y >= top && y < top + i64::from(self.height)
+ }
+
+ /// The same display, ignoring its factor (which may have changed since).
+ pub(crate) fn is_same_display(&self, other: &Self) -> bool {
+ self.x == other.x && self.y == other.y && self.width == other.width && self.height == other.height
+ }
+
+ /// The display's bounds in logical units.
+ pub(crate) fn logical(&self) -> LogicalRect {
+ to_logical(
+ PhysicalWindowRect { x: self.x, y: self.y, width: self.width, height: self.height },
+ self.scale_factor,
+ )
+ }
+}
+
+/// Logical values are only meaningful with a positive finite factor.
+pub(crate) fn clean_scale_factor(scale_factor: f64) -> f64 {
+ if scale_factor.is_finite() && scale_factor > 0.0 {
+ scale_factor
+ } else {
+ 1.0
+ }
+}
+
+/// Physical → logical at an explicit factor.
+pub(crate) fn to_logical(rect: PhysicalWindowRect, scale_factor: f64) -> LogicalRect {
+ let factor = clean_scale_factor(scale_factor);
+ LogicalRect {
+ x: rect.x as f64 / factor,
+ y: rect.y as f64 / factor,
+ width: rect.width as f64 / factor,
+ height: rect.height as f64 / factor,
+ }
+}
+
+/// `rect`'s origin relative to `monitor`, in points. On macOS a reported
+/// position is `AppKit points × the window's factor`, while display origins
+/// from `MonitorRect::logical` are points, so dividing by the window's factor
+/// gives the saved logical position. Equal factors give the plain point
+/// difference.
+pub(crate) fn offset_in_monitor(rect: PhysicalWindowRect, factor: f64, monitor: &MonitorRect) -> (f64, f64) {
+ let factor = clean_scale_factor(factor);
+ let origin = monitor.logical();
+ (rect.x as f64 / factor - origin.x, rect.y as f64 / factor - origin.y)
+}
+
+/// The display a saved physical rect was on: the one containing its origin,
+/// else the one it overlaps most, else the nearest one.
+/// Logical minimum of the main window, used to reject the impossible reading
+/// of a legacy physical rect at the wrong display factor.
+const MIN_LOGICAL_WINDOW_SIZE: (u32, u32) = (900, 600);
+
+fn plausible_logical_size(rect: PhysicalWindowRect, monitor: &MonitorRect) -> bool {
+ let factor = clean_scale_factor(monitor.scale_factor);
+ rect.width as f64 / factor >= f64::from(MIN_LOGICAL_WINDOW_SIZE.0)
+ && rect.height as f64 / factor >= f64::from(MIN_LOGICAL_WINDOW_SIZE.1)
+}
+
+pub(crate) fn matching_monitor(rect: PhysicalWindowRect, monitors: &[MonitorRect]) -> Option<MonitorRect> {
+ // A legacy state file has pixels only. Mixed-DPI physical monitor boxes
+ // overlap, so prefer the display whose factor yields a size the window
+ // could actually have had. The issue's 1280x800 px state is 1280x800 pt at
+ // 1x (valid) but 640x400 pt at 2x (below the minimum), which picks the
+ // external display instead of the built-in one.
+ if let Some(containing) =
+ monitors.iter().find(|monitor| plausible_logical_size(rect, monitor) && monitor.contains_point(rect.x, rect.y))
+ {
+ return Some(*containing);
+ }
+ if let Some(containing) = monitors.iter().find(|monitor| monitor.contains_point(rect.x, rect.y)) {
+ return Some(*containing);
+ }
+ let (left, top) = (i64::from(rect.x), i64::from(rect.y));
+ let (right, bottom) = (left + i64::from(rect.width), top + i64::from(rect.height));
+ let overlap = |monitor: &MonitorRect| {
+ let (m_left, m_top) = (i64::from(monitor.x), i64::from(monitor.y));
+ let (m_right, m_bottom) = (m_left + i64::from(monitor.width), m_top + i64::from(monitor.height));
+ (right.min(m_right) - left.max(m_left)).max(0) * (bottom.min(m_bottom) - top.max(m_top)).max(0)
+ };
+ if let Some(best) = monitors.iter().copied().filter(|monitor| overlap(monitor) > 0).max_by_key(overlap) {
+ return Some(best);
+ }
+ monitors.iter().copied().min_by_key(|monitor| {
+ let (m_left, m_top) = (i64::from(monitor.x), i64::from(monitor.y));
+ let (m_right, m_bottom) = (m_left + i64::from(monitor.width), m_top + i64::from(monitor.height));
+ let (gap_x, gap_y) = ((m_left - right).max(left - m_right).max(0), (m_top - bottom).max(top - m_bottom).max(0));
+ gap_x * gap_x + gap_y * gap_y
+ })
+}
+
+/// The display a logical rect is on: the one containing its origin, else the
+/// one it overlaps most, else the first.
+pub(crate) fn monitor_for_logical(rect: LogicalRect, monitors: &[MonitorRect]) -> Option<MonitorRect> {
+ monitors
+ .iter()
+ .find(|monitor| {
+ let bounds = monitor.logical();
+ rect.x >= bounds.x
+ && rect.x < bounds.x + bounds.width
+ && rect.y >= bounds.y
+ && rect.y < bounds.y + bounds.height
+ })
+ .or_else(|| monitors.iter().find(|monitor| overlaps_logical(rect, &monitor.logical())))
+ .or(monitors.first())
+ .copied()
+}
+
+fn overlaps_logical(a: LogicalRect, b: &LogicalRect) -> bool {
+ a.x < b.x + b.width && a.x + a.width > b.x && a.y < b.y + b.height && a.y + a.height > b.y
+}
+
+/// Caps `rect`'s size to the display it is on and centers it back onto that
+/// display when it would fall outside (the logical twin of the physical clamp).
+pub(crate) fn fit_logical(rect: LogicalRect, monitors: &[MonitorRect]) -> LogicalRect {
+ let Some(bounds) = monitor_for_logical(rect, monitors).map(|monitor| monitor.logical()) else {
+ return rect;
+ };
+ let width = rect.width.min(bounds.width);
+ let height = rect.height.min(bounds.height);
+ LogicalRect {
+ x: centered_axis(rect.x, width, bounds.x, bounds.width),
+ y: centered_axis(rect.y, height, bounds.y, bounds.height),
+ width,
+ height,
+ }
+}
+
+fn centered_axis(start: f64, length: f64, monitor_start: f64, monitor_length: f64) -> f64 {
+ let slack = (monitor_length - length).max(0.0);
+ if start < monitor_start || start > monitor_start + slack {
+ monitor_start + (slack / 2.0).round()
+ } else {
+ start
+ }
+}
+
+/// Origin of the one logical frame shared by all displays, given `primary`.
+/// On macOS every origin is AppKit points relative to the main display's
+/// top-left, and Tauri reports each origin multiplied by its own factor, so a
+/// display above or left of the main one shows up as a negative logical origin
+/// and a shared frame is in use. Windows and X11 keep separate pixel origins,
+/// which a display left of or above the primary also makes negative, so this
+/// only holds when the primary sits at `(0, 0)` and nothing reports a negative
+/// origin — the macOS setup, where logical positions really are points.
+pub(crate) fn shared_frame_base(monitors: &[MonitorRect], primary: Option<&MonitorRect>) -> Option<LogicalRect> {
+ let primary = primary?.logical();
+ let shared = monitors.iter().all(|monitor| {
+ let origin = monitor.logical();
+ origin.x >= 0.0 && origin.y >= 0.0
+ });
+ (shared && primary.x == 0.0 && primary.y == 0.0).then_some(primary)
+}
diff --git a/src-tauri/src/window_state_guard.rs b/src-tauri/src/window_state_guard.rs
index 3577b1ca1d..a3599cfd1e 100644
--- a/src-tauri/src/window_state_guard.rs
+++ b/src-tauri/src/window_state_guard.rs
@@ -1,30 +1,39 @@
-use serde::Deserialize;
+//! Main-window geometry persistence and restore.
+//!
+//! `tauri-plugin-window-state` saves `outer_position`/`inner_size` as physical
+//! pixels (`logical points × the factor of the display the window was on`) and
+//! restores them with `set_position(Physical…)`/`set_size(Physical…)`, which
+//! tao converts back using the *restoring* window's factor, i.e. the display it
+//! was created on. That only round-trips on a display whose factor equals the
+//! saving one: after closing DBX on a 1x external display of a mixed-DPI macOS
+//! setup, those pixels are read at 2x, so the window lands on the 2x main
+//! display at half its size (issue #13168). The plugin's "saved rect
+//! intersects a monitor" guard does not notice, because each monitor rect is
+//! scaled by that monitor's own factor.
+//!
+//! DBX keeps the plugin for the file format, flags and event cache, but also
+//! records the window's geometry in the same `.window-state.json` entry
+//! (`logical`, a field the plugin ignores). On macOS, whose displays share one
+//! point frame, it restores that geometry with `LogicalPosition`/`LogicalSize`,
+//! which tao applies without converting. Other platforms keep the plugin's
+//! physical round trip.
+
+use serde::{Deserialize, Serialize};
use std::fs;
-use tauri::{AppHandle, Manager, PhysicalPosition, PhysicalSize, Runtime, WebviewWindow};
+use tauri::{AppHandle, LogicalPosition, LogicalSize, Manager, PhysicalPosition, PhysicalSize, Runtime, WebviewWindow};
use tauri_plugin_window_state::{AppHandleExt, StateFlags};
+use crate::window_geometry::{
+ clean_scale_factor, fit_logical, matching_monitor, offset_in_monitor, shared_frame_base, LogicalRect, MonitorRect,
+ PhysicalWindowRect,
+};
+
/// Must match `minWidth`/`minHeight` and `width`/`height` of the main window in
/// `tauri.conf.json`. Logical pixels.
const MIN_WINDOW_SIZE: (u32, u32) = (900, 600);
const DEFAULT_WINDOW_SIZE: (u32, u32) = (1280, 800);
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) struct PhysicalWindowRect {
- pub(crate) x: i32,
- pub(crate) y: i32,
- pub(crate) width: u32,
- pub(crate) height: u32,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(crate) struct PhysicalMonitorRect {
- pub(crate) x: i32,
- pub(crate) y: i32,
- pub(crate) width: u32,
- pub(crate) height: u32,
-}
-
-#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Eq)]
+#[derive(Debug, Clone, Copy, Deserialize, PartialEq)]
struct PersistedWindowState {
width: u32,
height: u32,
@@ -35,19 +44,33 @@ struct PersistedWindowState {
maximized: bool,
decorated: bool,
fullscreen: bool,
+ /// Written by DBX; absent in states written by older builds.
+ logical: Option<WindowGeometry>,
}
-pub(crate) fn corrected_window_rect(
- window: PhysicalWindowRect,
- monitor: PhysicalMonitorRect,
-) -> Option<PhysicalWindowRect> {
- let width = window.width.min(monitor.width);
- let height = window.height.min(monitor.height);
- let x = centered_axis_position(window.x, width, monitor.x, monitor.width);
- let y = centered_axis_position(window.y, height, monitor.y, monitor.height);
- let corrected = PhysicalWindowRect { x, y, width, height };
+/// Window logical position/size plus the factor of the display it was on.
+/// Positions are relative to that display's logical origin, so they stay valid
+/// when the window is recreated on another display.
+#[derive(Debug, Clone, Copy, Deserialize, PartialEq, Serialize)]
+pub(crate) struct WindowGeometry {
+ x: f64,
+ y: f64,
+ width: f64,
+ height: f64,
+ scale_factor: f64,
+}
- (corrected != window).then_some(corrected)
+impl WindowGeometry {
+ pub(crate) fn is_usable(&self) -> bool {
+ [self.x, self.y, self.width, self.height, self.scale_factor].iter().all(|value| value.is_finite())
+ && self.width > 0.0
+ && self.height > 0.0
+ && self.scale_factor > 0.0
+ }
+
+ pub(crate) fn logical(&self) -> LogicalRect {
+ LogicalRect { x: self.x, y: self.y, width: self.width, height: self.height }
+ }
}
/// The window-state plugin caches `Resized` events without a non-zero check, so
@@ -56,16 +79,24 @@ pub(crate) fn corrected_window_rect(
/// below by the minimum, so a persisted size under it (at 1x scale, the lowest
/// physical size that minimum can have) is corrupt and falls back to the default.
pub(crate) fn sane_window_size(saved: (u32, u32), default_scale: f64) -> (u32, u32) {
- if saved.0 >= MIN_WINDOW_SIZE.0 && saved.1 >= MIN_WINDOW_SIZE.1 {
- return saved;
- }
let scale = if default_scale.is_finite() && default_scale >= 1.0 { default_scale } else { 1.0 };
- ((DEFAULT_WINDOW_SIZE.0 as f64 * scale).round() as u32, (DEFAULT_WINDOW_SIZE.1 as f64 * scale).round() as u32)
+ let sane = |value: u32, min: u32, default: u32| if value >= min { value } else { default };
+ let (width, height) = (
+ sane((saved.0 as f64 / scale).round() as u32, MIN_WINDOW_SIZE.0, DEFAULT_WINDOW_SIZE.0),
+ sane((saved.1 as f64 / scale).round() as u32, MIN_WINDOW_SIZE.1, DEFAULT_WINDOW_SIZE.1),
+ );
+ (((width as f64) * scale).round() as u32, ((height as f64) * scale).round() as u32)
+}
+
+pub(crate) fn persisted_main_window_state_flags() -> StateFlags {
+ StateFlags::SIZE | StateFlags::POSITION | StateFlags::MAXIMIZED | StateFlags::DECORATIONS | StateFlags::FULLSCREEN
}
pub(crate) fn enforce_main_window_bounds<R: Runtime>(app: &AppHandle<R>) {
if let Some(window) = app.get_webview_window("main") {
- if enforce_window_bounds(&window) {
+ if let Some(rect) = enforce_window_bounds(&window) {
+ let _ = window.set_size(PhysicalSize::new(rect.width, rect.height));
+ let _ = window.set_position(PhysicalPosition::new(rect.x, rect.y));
let _ = app.save_window_state(persisted_main_window_state_flags());
}
}
@@ -78,42 +109,22 @@ pub(crate) fn restore_main_window_state<R: Runtime>(app: &AppHandle<R>) {
let Some(state) = load_main_window_state(app) else {
return;
};
-
- let persisted_rect = persisted_window_rect(state);
- let (width, height) =
- sane_window_size((persisted_rect.width, persisted_rect.height), window.scale_factor().unwrap_or(1.0));
- let saved_rect = PhysicalWindowRect { width, height, ..persisted_rect };
- let monitors = window
- .available_monitors()
- .unwrap_or_default()
- .into_iter()
- .map(|monitor| PhysicalMonitorRect {
- x: monitor.position().x,
- y: monitor.position().y,
- width: monitor.size().width,
- height: monitor.size().height,
- })
- .collect::<Vec<_>>();
- let fallback_monitor =
- window.current_monitor().ok().flatten().or_else(|| window.primary_monitor().ok().flatten()).map(|monitor| {
- PhysicalMonitorRect {
- x: monitor.position().x,
- y: monitor.position().y,
- width: monitor.size().width,
- height: monitor.size().height,
- }
- });
- let monitor = matching_monitor(saved_rect, &monitors).or(fallback_monitor);
- let restored_rect = monitor.and_then(|monitor| corrected_window_rect(saved_rect, monitor)).unwrap_or(saved_rect);
+ let monitors = monitor_rects(&window);
+ let primary = window.primary_monitor().ok().flatten().map(|monitor| MonitorRect::from(&monitor));
let _ = window.set_decorations(state.decorated);
- let restored = window
- .set_size(PhysicalSize::new(restored_rect.width, restored_rect.height))
- .and_then(|_| window.set_position(PhysicalPosition::new(restored_rect.x, restored_rect.y)))
- .is_ok();
-
- if restored && restored_rect != persisted_rect {
- let _ = app.save_window_state(persisted_main_window_state_flags());
+ // Only macOS has one logical frame for all displays (AppKit points), which
+ // is the setup issue #13168 is about. Elsewhere displays have separate pixel
+ // origins, so the pre-existing physical path is kept.
+ let geometry = cfg!(target_os = "macos")
+ .then(|| shared_frame_base(&monitors, primary.as_ref()).and_then(|_| logical_geometry(&state, &monitors)))
+ .flatten()
+ .filter(WindowGeometry::is_usable);
+ match geometry.filter(|geometry| set_logical_geometry(&window, geometry)) {
+ // The plugin's own restore skips the main window, so make its cache and
+ // the file agree with the frame just applied.
+ Some(geometry) => persist_logical_geometry(app, &geometry),
+ None => restore_physical_window_state(&window, &state, &monitors),
}
if state.maximized {
let _ = window.maximize();
@@ -123,199 +134,245 @@ pub(crate) fn restore_main_window_state<R: Runtime>(app: &AppHandle<R>) {
}
}
-pub(crate) fn persisted_main_window_state_flags() -> StateFlags {
- StateFlags::SIZE | StateFlags::POSITION | StateFlags::MAXIMIZED | StateFlags::DECORATIONS | StateFlags::FULLSCREEN
+/// Logical geometry to restore on macOS, in the shared point frame.
+///
+/// A DBX entry holds the window's point position relative to an unknown display
+/// plus the factor the window reported: on macOS the same position is reported
+/// in every start (the AppKit point frame), so on restore the display it is on
+/// is simply the one containing it. A state written by an older build holds the
+/// plugin's pixels, which on macOS are AppKit points × the factor the window
+/// reported at save time; those land on a display by their pixels, and
+/// dividing by that display's factor gives the points back.
+fn logical_geometry(state: &PersistedWindowState, monitors: &[MonitorRect]) -> Option<WindowGeometry> {
+ let (mut geometry, factor, home) = match state.logical.filter(WindowGeometry::is_usable) {
+ Some(logical) => {
+ let rect = logical.logical();
+ let factor = clean_scale_factor(logical.scale_factor);
+ let home = matching_monitor(relative_rect(&rect), monitors);
+ (rect, factor, home)
+ }
+ None => {
+ let pixels = saved_physical_rect(state);
+ let monitor = matching_monitor(pixels, monitors)?;
+ let factor = monitor.scale_factor;
+ let (width, height) = sane_window_size((pixels.width, pixels.height), factor);
+ let rect = PhysicalWindowRect { width, height, ..pixels };
+ (point_frame(rect, factor, &monitor), factor, Some(monitor))
+ }
+ };
+ if !monitor_containing(&geometry, monitors) {
+ // Created on another display (or the saved one is gone): keep the
+ // offset in the frame of a display that still exists.
+ let (target, home) = (monitors.first()?, home?);
+ geometry.x += target.logical().x - home.logical().x;
+ geometry.y += target.logical().y - home.logical().y;
+ }
+ let fitted = fit_logical(geometry, monitors);
+ Some(WindowGeometry { x: fitted.x, y: fitted.y, width: fitted.width, height: fitted.height, scale_factor: factor })
}
-fn load_main_window_state<R: Runtime>(app: &AppHandle<R>) -> Option<PersistedWindowState> {
- let path = app.path().app_config_dir().ok()?.join(app.filename());
- let states: serde_json::Value = serde_json::from_slice(&fs::read(path).ok()?).ok()?;
- serde_json::from_value(states.get("main")?.clone()).ok()
+fn relative_rect(rect: &LogicalRect) -> PhysicalWindowRect {
+ PhysicalWindowRect {
+ x: rect.x.round() as i32,
+ y: rect.y.round() as i32,
+ width: rect.width.max(0.0) as u32,
+ height: rect.height.max(0.0) as u32,
+ }
}
-fn persisted_window_rect(state: PersistedWindowState) -> PhysicalWindowRect {
- let (x, y) = if state.maximized { (state.prev_x, state.prev_y) } else { (state.x, state.y) };
- PhysicalWindowRect { x, y, width: state.width, height: state.height }
+/// `rect` (reported at `factor`) on `monitor` in the point frame.
+fn point_frame(rect: PhysicalWindowRect, factor: f64, monitor: &MonitorRect) -> LogicalRect {
+ let factor = clean_scale_factor(factor);
+ let origin = monitor.logical();
+ let (x, y) = offset_in_monitor(rect, factor, monitor);
+ LogicalRect {
+ x: origin.x + x,
+ y: origin.y + y,
+ width: rect.width as f64 / factor,
+ height: rect.height as f64 / factor,
+ }
}
-fn matching_monitor(window: PhysicalWindowRect, monitors: &[PhysicalMonitorRect]) -> Option<PhysicalMonitorRect> {
- monitors
- .iter()
- .copied()
- .find(|monitor| monitor_contains_point(*monitor, window.x, window.y))
- .or_else(|| monitors.iter().copied().find(|monitor| rects_intersect(window, *monitor)))
+fn monitor_containing(geometry: &LogicalRect, monitors: &[MonitorRect]) -> bool {
+ monitors.iter().any(|monitor| {
+ let bounds = monitor.logical();
+ geometry.x >= bounds.x
+ && geometry.y >= bounds.y
+ && geometry.x < bounds.x + bounds.width
+ && geometry.y < bounds.y + bounds.height
+ })
}
-fn monitor_contains_point(monitor: PhysicalMonitorRect, x: i32, y: i32) -> bool {
- let x = i64::from(x);
- let y = i64::from(y);
- let left = i64::from(monitor.x);
- let top = i64::from(monitor.y);
- x >= left && x < left + i64::from(monitor.width) && y >= top && y < top + i64::from(monitor.height)
+/// `rect` (reported at `factor`) on `monitor` as a stored display-relative geometry.
+fn logical_in_monitor(rect: PhysicalWindowRect, factor: f64, monitor: &MonitorRect) -> WindowGeometry {
+ let point = point_frame(rect, factor, monitor);
+ let origin = monitor.logical();
+ WindowGeometry {
+ x: point.x - origin.x,
+ y: point.y - origin.y,
+ width: point.width,
+ height: point.height,
+ scale_factor: clean_scale_factor(factor),
+ }
}
-fn rects_intersect(window: PhysicalWindowRect, monitor: PhysicalMonitorRect) -> bool {
- let window_left = i64::from(window.x);
- let window_top = i64::from(window.y);
- let window_right = window_left + i64::from(window.width);
- let window_bottom = window_top + i64::from(window.height);
- let monitor_left = i64::from(monitor.x);
- let monitor_top = i64::from(monitor.y);
- let monitor_right = monitor_left + i64::from(monitor.width);
- let monitor_bottom = monitor_top + i64::from(monitor.height);
-
- window_left < monitor_right
- && window_right > monitor_left
- && window_top < monitor_bottom
- && window_bottom > monitor_top
+fn set_logical_geometry<R: Runtime>(window: &WebviewWindow<R>, geometry: &WindowGeometry) -> bool {
+ window
+ .set_size(LogicalSize::new(geometry.width, geometry.height))
+ .and_then(|_| window.set_position(LogicalPosition::new(geometry.x, geometry.y)))
+ .is_ok()
}
-fn enforce_window_bounds<R: Runtime>(window: &WebviewWindow<R>) -> bool {
- if window.is_maximized().unwrap_or(false) || window.is_fullscreen().unwrap_or(false) {
- return false;
+/// Records the main window's geometry in logical units while the window is
+/// still visible. macOS quits through `AppHandle::hide` + `app.exit`, and the
+/// window-state plugin saves at exit, possibly from a frame that hiding
+/// blanked; the answer to the close prompt may also arrive long after it
+/// appeared. Callers capture before hiding and when a close is requested;
+/// repeats within a minute are skipped, but the first call always stores, so a
+/// single quit keeps its exact frame.
+pub(crate) fn remember_main_window_geometry<R: Runtime>(app: &AppHandle<R>) {
+ static LAST_CAPTURE: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);
+ let now = std::time::Instant::now();
+ if let Ok(mut last) = LAST_CAPTURE.lock() {
+ if last.is_some_and(|last| now.duration_since(last) < std::time::Duration::from_secs(60)) {
+ return;
+ }
+ *last = Some(now);
}
-
- let monitor = match window.current_monitor().ok().flatten().or_else(|| window.primary_monitor().ok().flatten()) {
- Some(monitor) => monitor,
- None => return false,
- };
- let monitor_position = monitor.position();
- let monitor_size = monitor.size();
- let window_position = match window.outer_position() {
- Ok(position) => position,
- Err(_) => return false,
+ let Some(window) = app.get_webview_window("main") else {
+ return;
};
- let window_size = match window.outer_size() {
- Ok(size) => size,
- Err(_) => return false,
+ let visible = window.is_visible().unwrap_or(false)
+ && !window.is_minimized().unwrap_or(false)
+ && !window.is_maximized().unwrap_or(false)
+ && !window.is_fullscreen().unwrap_or(false);
+ let (Ok(position), Ok(size), Ok(scale_factor)) =
+ (window.outer_position(), window.inner_size(), window.scale_factor())
+ else {
+ return;
};
-
- let corrected = corrected_window_rect(
- PhysicalWindowRect {
- x: window_position.x,
- y: window_position.y,
- width: window_size.width,
- height: window_size.height,
- },
- PhysicalMonitorRect {
- x: monitor_position.x,
- y: monitor_position.y,
- width: monitor_size.width,
- height: monitor_size.height,
- },
- );
-
- if let Some(rect) = corrected {
- let _ = window.set_size(PhysicalSize::new(rect.width, rect.height));
- let _ = window.set_position(PhysicalPosition::new(rect.x, rect.y));
- true
- } else {
- false
- }
-}
-
-fn centered_axis_position(window_start: i32, window_length: u32, monitor_start: i32, monitor_length: u32) -> i32 {
- let max_start = monitor_start + monitor_length.saturating_sub(window_length) as i32;
- if window_start < monitor_start || window_start > max_start {
- monitor_start + monitor_length.saturating_sub(window_length) as i32 / 2
- } else {
- window_start
+ let rect = PhysicalWindowRect { x: position.x, y: position.y, width: size.width, height: size.height };
+ let geometry = visible
+ .then(|| {
+ matching_monitor(rect, &monitor_rects(&window))
+ .map(|monitor| logical_in_monitor(rect, scale_factor, &monitor))
+ })
+ .flatten()
+ .filter(|geometry| geometry.is_usable());
+ if let Some(geometry) = geometry {
+ persist_logical_geometry(app, &geometry);
}
}
-#[cfg(test)]
-mod tests {
- use super::{
- corrected_window_rect, matching_monitor, persisted_window_rect, sane_window_size, PersistedWindowState,
- PhysicalMonitorRect, PhysicalWindowRect,
+/// Writes the geometry next to the plugin's fields, then lets the plugin save
+/// (it re-reads the file, so the field must be in place first).
+fn persist_logical_geometry<R: Runtime>(app: &AppHandle<R>, geometry: &WindowGeometry) {
+ let Ok(path) = app.path().app_config_dir().map(|dir| dir.join(app.filename())) else {
+ return;
};
- use tauri_plugin_window_state::StateFlags;
-
- #[test]
- fn persisted_state_excludes_window_visibility() {
- let flags = super::persisted_main_window_state_flags();
-
- assert!(flags.contains(StateFlags::SIZE));
- assert!(flags.contains(StateFlags::POSITION));
- assert!(!flags.contains(StateFlags::VISIBLE));
- }
-
- #[test]
- fn moves_window_back_onto_monitor_when_restored_above_screen() {
- let corrected = corrected_window_rect(
- PhysicalWindowRect { x: 118, y: -1042, width: 1512, height: 866 },
- PhysicalMonitorRect { x: 0, y: 0, width: 1512, height: 982 },
- );
-
- assert_eq!(corrected, Some(PhysicalWindowRect { x: 0, y: 58, width: 1512, height: 866 }));
+ let Some(mut states) =
+ fs::read(&path).ok().and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
+ else {
+ return;
+ };
+ if let (Some(mut main), Ok(logical)) =
+ (states.get_mut("main").map(serde_json::Value::take), serde_json::to_value(geometry))
+ {
+ main["logical"] = logical;
+ states["main"] = main;
}
-
- #[test]
- fn leaves_window_unchanged_when_it_fits_monitor() {
- let corrected = corrected_window_rect(
- PhysicalWindowRect { x: 80, y: 60, width: 1280, height: 800 },
- PhysicalMonitorRect { x: 0, y: 0, width: 1512, height: 982 },
- );
-
- assert_eq!(corrected, None);
+ if let Ok(encoded) = serde_json::to_vec_pretty(&states) {
+ let _ = fs::write(path, encoded);
}
+ let _ = app.save_window_state(persisted_main_window_state_flags());
+}
- #[test]
- fn shrinks_window_that_is_larger_than_monitor() {
- let corrected = corrected_window_rect(
- PhysicalWindowRect { x: -200, y: -120, width: 4096, height: 2160 },
- PhysicalMonitorRect { x: 0, y: 0, width: 1440, height: 900 },
- );
-
- assert_eq!(corrected, Some(PhysicalWindowRect { x: 0, y: 0, width: 1440, height: 900 }));
- }
+fn restore_physical_window_state<R: Runtime>(
+ window: &WebviewWindow<R>,
+ state: &PersistedWindowState,
+ monitors: &[MonitorRect],
+) {
+ let persisted_rect = saved_physical_rect(state);
+ let scale_factor = clean_scale_factor(window.scale_factor().unwrap_or(1.0));
+ let (width, height) = sane_window_size((persisted_rect.width, persisted_rect.height), scale_factor);
+ let saved_rect = PhysicalWindowRect { x: persisted_rect.x, y: persisted_rect.y, width, height };
+ let fallback_monitor = window
+ .current_monitor()
+ .ok()
+ .flatten()
+ .or_else(|| window.primary_monitor().ok().flatten())
+ .map(|monitor| MonitorRect::from(&monitor));
+ let monitor = matching_monitor(saved_rect, monitors).or(fallback_monitor);
+ let restored_rect = monitor.and_then(|monitor| corrected_window_rect(saved_rect, monitor)).unwrap_or(saved_rect);
- #[test]
- fn repairs_oversized_maximized_window_and_restores_maximized_state() {
- let saved = PersistedWindowState {
- width: 7120,
- height: 2082,
- x: 0,
- y: 88,
- prev_x: 0,
- prev_y: 176,
- maximized: true,
- decorated: true,
- fullscreen: false,
- };
- let saved_rect = persisted_window_rect(saved);
- let monitor = PhysicalMonitorRect { x: 0, y: 0, width: 3600, height: 2338 };
+ let restored = window
+ .set_size(PhysicalSize::new(restored_rect.width, restored_rect.height))
+ .and_then(|_| window.set_position(PhysicalPosition::new(restored_rect.x, restored_rect.y)))
+ .is_ok();
- assert_eq!(
- corrected_window_rect(saved_rect, monitor),
- Some(PhysicalWindowRect { x: 0, y: 176, width: 3600, height: 2082 })
- );
+ if restored && restored_rect != persisted_rect {
+ let _ = window.app_handle().save_window_state(persisted_main_window_state_flags());
}
+}
- #[test]
- fn chooses_monitor_containing_saved_window_origin() {
- let window = PhysicalWindowRect { x: -900, y: -1200, width: 2560, height: 1600 };
- let monitors = [
- PhysicalMonitorRect { x: 0, y: 0, width: 3600, height: 2338 },
- PhysicalMonitorRect { x: -1007, y: -1440, width: 3440, height: 1440 },
- ];
+/// Last-resort physical placement: clamp the rect onto `monitor`.
+pub(crate) fn corrected_window_rect(window: PhysicalWindowRect, monitor: MonitorRect) -> Option<PhysicalWindowRect> {
+ let width = window.width.min(monitor.width);
+ let height = window.height.min(monitor.height);
+ let x = centered_axis(window.x, width, monitor.x, monitor.width);
+ let y = centered_axis(window.y, height, monitor.y, monitor.height);
+ let corrected = PhysicalWindowRect { x, y, width, height };
+ (corrected != window).then_some(corrected)
+}
- assert_eq!(matching_monitor(window, &monitors), Some(monitors[1]));
+fn centered_axis(window_start: i32, window_length: u32, monitor_start: i32, monitor_length: u32) -> i32 {
+ let slack = monitor_length.saturating_sub(window_length);
+ let max_start = monitor_start + slack as i32;
+ if window_start < monitor_start || window_start > max_start {
+ monitor_start + slack as i32 / 2
+ } else {
+ window_start
}
+}
- #[test]
- fn keeps_persisted_size_at_or_above_the_minimum() {
- assert_eq!(sane_window_size((1280, 800), 1.0), (1280, 800));
- assert_eq!(sane_window_size((900, 600), 2.0), (900, 600));
+fn enforce_window_bounds<R: Runtime>(window: &WebviewWindow<R>) -> Option<PhysicalWindowRect> {
+ if window.is_maximized().unwrap_or(false) || window.is_fullscreen().unwrap_or(false) {
+ return None;
}
+ let monitor = window.current_monitor().ok().flatten().or_else(|| window.primary_monitor().ok().flatten())?;
+ let (Ok(position), Ok(size)) = (window.outer_position(), window.outer_size()) else {
+ return None;
+ };
+ let rect = PhysicalWindowRect { x: position.x, y: position.y, width: size.width, height: size.height };
+ corrected_window_rect(rect, MonitorRect::from(&monitor))
+}
- #[test]
- fn replaces_corrupt_persisted_size_with_the_scaled_default() {
- for corrupt in [(0, 0), (160, 28), (440, 68), (1280, 0), (0, 800), (899, 800), (1280, 599)] {
- assert_eq!(sane_window_size(corrupt, 1.0), (1280, 800), "{corrupt:?}");
- assert_eq!(sane_window_size(corrupt, 2.0), (2560, 1600), "{corrupt:?}");
+/// Every display Tauri knows, with the special ones appended if missing.
+fn monitor_rects<R: Runtime>(window: &WebviewWindow<R>) -> Vec<MonitorRect> {
+ let mut monitors =
+ window.available_monitors().unwrap_or_default().iter().map(MonitorRect::from).collect::<Vec<_>>();
+ for monitor in
+ [window.current_monitor().ok().flatten(), window.primary_monitor().ok().flatten()].into_iter().flatten()
+ {
+ let rect = MonitorRect::from(&monitor);
+ if !monitors.iter().any(|known| known.is_same_display(&rect)) {
+ monitors.push(rect);
}
- assert_eq!(sane_window_size((0, 0), f64::NAN), (1280, 800));
- assert_eq!(sane_window_size((0, 0), 0.0), (1280, 800));
}
+ monitors
+}
+
+fn load_main_window_state<R: Runtime>(app: &AppHandle<R>) -> Option<PersistedWindowState> {
+ let path = app.path().app_config_dir().ok()?.join(app.filename());
+ let states: serde_json::Value = serde_json::from_slice(&fs::read(path).ok()?).ok()?;
+ serde_json::from_value(states.get("main")?.clone()).ok()
}
+
+fn saved_physical_rect(state: &PersistedWindowState) -> PhysicalWindowRect {
+ let (x, y) = if state.maximized { (state.prev_x, state.prev_y) } else { (state.x, state.y) };
+ PhysicalWindowRect { x, y, width: state.width, height: state.height }
+}
+
+#[cfg(test)]
+#[path = "window_state_guard_tests.rs"]
+mod tests;
diff --git a/src-tauri/src/window_state_guard_tests.rs b/src-tauri/src/window_state_guard_tests.rs
new file mode 100644
index 0000000000..b47fca2e62
--- /dev/null
+++ b/src-tauri/src/window_state_guard_tests.rs
@@ -0,0 +1,186 @@
+//! Unit tests for issue #13168: the display-space helpers in `window_geometry`
+//! together with the window-state logic that restores the main window.
+
+use crate::window_geometry::{
+ fit_logical, matching_monitor, monitor_for_logical, offset_in_monitor, to_logical, LogicalRect, MonitorRect,
+ PhysicalWindowRect,
+};
+use crate::window_state_guard::{corrected_window_rect, sane_window_size, WindowGeometry};
+use tauri_plugin_window_state::StateFlags;
+
+fn rect(x: i32, y: i32, width: u32, height: u32) -> PhysicalWindowRect {
+ PhysicalWindowRect { x, y, width, height }
+}
+
+fn logical(x: f64, y: f64, width: f64, height: f64) -> LogicalRect {
+ LogicalRect { x, y, width, height }
+}
+
+fn monitor(x: i32, y: i32, width: u32, height: u32, scale_factor: f64) -> MonitorRect {
+ MonitorRect { x, y, width, height, scale_factor }
+}
+
+/// Issue #13168: a 2x built-in main display (1728×1117 pt) plus a 1x external
+/// display to its right, whose points start at (1728, -323). Tauri reports
+/// each origin multiplied by that display's factor, so `MonitorRect::logical`
+/// gives back the AppKit points.
+fn mixed_dpi() -> Vec<MonitorRect> {
+ vec![monitor(0, 0, 3456, 2234, 2.0), monitor(1728, -323, 2560, 1440, 1.0)]
+}
+
+#[test]
+fn persisted_state_excludes_window_visibility() {
+ let flags = crate::window_state_guard::persisted_main_window_state_flags();
+ assert!(flags.contains(StateFlags::SIZE));
+ assert!(flags.contains(StateFlags::POSITION));
+ assert!(!flags.contains(StateFlags::VISIBLE));
+}
+
+#[test]
+fn keeps_persisted_size_at_or_above_the_minimum() {
+ assert_eq!(sane_window_size((1280, 800), 1.0), (1280, 800));
+ // 900x600 px at 2x is 450x300 pt, below the logical minimum; the old
+ // physical check let it through, the logical one falls back to the default.
+ assert_eq!(sane_window_size((900, 600), 2.0), (2560, 1600));
+ assert_eq!(sane_window_size((1800, 1200), 2.0), (1800, 1200));
+ assert_eq!(sane_window_size((3150, 2168), 2.0), (3150, 2168));
+}
+
+#[test]
+fn replaces_corrupt_persisted_size_with_the_scaled_default() {
+ for corrupt in [(0, 0), (160, 28), (440, 68), (1280, 0), (0, 800), (899, 800), (1280, 599)] {
+ assert_eq!(sane_window_size(corrupt, 1.0), (1280, 800), "{corrupt:?}");
+ assert_eq!(sane_window_size(corrupt, 2.0), (2560, 1600), "{corrupt:?}");
+ }
+ assert_eq!(sane_window_size((0, 0), f64::NAN), (1280, 800));
+ assert_eq!(sane_window_size((0, 0), 0.0), (1280, 800));
+}
+
+#[test]
+fn to_logical_divides_by_the_factor() {
+ assert_eq!(to_logical(rect(2368, 183, 1280, 800), 1.0), logical(2368.0, 183.0, 1280.0, 800.0));
+ assert_eq!(to_logical(rect(2368, 183, 1280, 800), 2.0), logical(1184.0, 91.5, 640.0, 400.0));
+ assert_eq!(to_logical(rect(33, 7, 1281, 801), 2.0), logical(16.5, 3.5, 640.5, 400.5));
+ assert_eq!(to_logical(rect(1184, 91, 640, 400), 1.25), logical(947.2, 72.8, 512.0, 320.0));
+ for factor in [0.0, -2.0, f64::NAN, f64::INFINITY] {
+ assert_eq!(to_logical(rect(-10, 20, 100, 50), factor), logical(-10.0, 20.0, 100.0, 50.0), "{factor}");
+ }
+}
+
+#[test]
+fn monitor_bounds_are_points_through_each_monitor_factor() {
+ let monitors = mixed_dpi();
+ let (built_in, external) = (monitors[0].logical(), monitors[1].logical());
+ assert_eq!((built_in.x, built_in.y, built_in.width, built_in.height), (0.0, 0.0, 1728.0, 1117.0));
+ assert_eq!((external.x, external.y, external.width, external.height), (1728.0, -323.0, 2560.0, 1440.0));
+}
+
+#[test]
+fn offset_is_the_saved_point_position_at_each_factor() {
+ let monitors = mixed_dpi();
+ // On the 1x external display a reported position is its points.
+ assert_eq!(offset_in_monitor(rect(2368, 183, 1280, 800), 1.0, &monitors[1]), (640.0, 506.0));
+ // On the 2x built-in display 3150×2168 px are 1575×1084 pt at (152, 33).
+ assert_eq!(offset_in_monitor(rect(304, 66, 3150, 2168), 2.0, &monitors[0]), (152.0, 33.0));
+ // The 1x pixels read at 2x are 640×400 pt at (1184, 91.5): the issue.
+ assert_eq!(offset_in_monitor(rect(2368, 183, 1280, 800), 2.0, &monitors[0]), (1184.0, 91.5));
+}
+
+#[test]
+fn matching_monitor_prefers_origin_then_overlap_then_distance() {
+ let monitors = mixed_dpi();
+ assert_eq!(matching_monitor(rect(2368, 183, 1280, 800), &monitors), Some(monitors[1]));
+ assert_eq!(matching_monitor(rect(100, 100, 1280, 800), &monitors), Some(monitors[0]));
+ // Origin above both displays, overlapping only the external one.
+ assert_eq!(matching_monitor(rect(3600, -700, 400, 200), &monitors), Some(monitors[1]));
+ assert_eq!(matching_monitor(rect(1500, 900, 2000, 600), &monitors), Some(monitors[0]));
+ // Outside both: the nearest display wins.
+ assert_eq!(matching_monitor(rect(9000, 4000, 100, 100), &monitors), Some(monitors[1]));
+ assert_eq!(matching_monitor(rect(-5000, 4000, 100, 100), &monitors), Some(monitors[0]));
+ assert_eq!(matching_monitor(rect(0, 0, 10, 10), &[]), None);
+}
+
+#[test]
+fn logical_monitor_lookup_uses_points() {
+ let monitors = mixed_dpi();
+ assert_eq!(monitor_for_logical(logical(2368.0, 183.0, 1280.0, 800.0), &monitors), Some(monitors[1]));
+ assert_eq!(monitor_for_logical(logical(152.0, 33.0, 1575.0, 1084.0), &monitors), Some(monitors[0]));
+ // The reported symptom lands on the built-in display, where the pre-fix
+ // code left the window.
+ assert_eq!(monitor_for_logical(logical(1184.0, 91.5, 640.0, 400.0), &monitors), Some(monitors[0]));
+ assert_eq!(monitor_for_logical(logical(5000.0, 5000.0, 100.0, 100.0), &monitors), Some(monitors[0]));
+}
+
+#[test]
+fn fit_logical_keeps_or_centers_like_the_physical_clamp() {
+ let monitors = mixed_dpi();
+ let inside = logical(152.0, 33.0, 1575.0, 1084.0);
+ assert_eq!(fit_logical(inside, &monitors), inside);
+ // Above the display: centered in it.
+ let above = logical(59.0, -521.0, 756.0, 433.0);
+ // x is inside the built-in display, so only the vertical axis is centered.
+ assert_eq!(fit_logical(above, &monitors), logical(59.0, 342.0, 756.0, 433.0));
+ // Larger than the display: shrunk, kept at its origin.
+ let huge = logical(10.0, 20.0, 4000.0, 3000.0);
+ // Equal to the display: the out-of-range origin is centered to 0.
+ assert_eq!(fit_logical(huge, &monitors), logical(0.0, 0.0, 1728.0, 1117.0));
+ // No displays: unchanged.
+ assert_eq!(fit_logical(above, &[]), above);
+}
+
+#[test]
+fn corrected_window_rect_still_clamps_physical_frames() {
+ let built_in = MonitorRect { x: 0, y: 0, width: 1512, height: 982, scale_factor: 2.0 };
+ // Restored above the screen: back onto the display.
+ assert_eq!(corrected_window_rect(rect(118, -1042, 1512, 866), built_in), Some(rect(0, 58, 1512, 866)));
+ // Fits: untouched.
+ assert_eq!(corrected_window_rect(rect(80, 60, 1280, 800), built_in), None);
+ // Larger than the display: shrunk.
+ let small = MonitorRect { x: 0, y: 0, width: 1440, height: 900, scale_factor: 1.0 };
+ assert_eq!(corrected_window_rect(rect(-200, -120, 4096, 2160), small), Some(rect(0, 0, 1440, 900)));
+}
+
+#[test]
+fn issue_13168_restores_the_frame_saved_on_the_1x_display() {
+ // Closed at (2368, 183) at 1280×800 px on the 1x external display and
+ // reopened with the main (2x) display current: pre-fix the pixels were read
+ // at 2x, giving 640×400 pt at (1184, 91.5). In the point frame the same
+ // window is 1280×800 pt at (2368, 183), on its own display.
+ let monitors = mixed_dpi();
+ let saved = rect(2368, 183, 1280, 800);
+ let external = matching_monitor(saved, &monitors).expect("saved on the external display");
+ let origin = external.logical();
+ let (x, y) = offset_in_monitor(saved, external.scale_factor, &external);
+ let stored = WindowGeometry {
+ x,
+ y,
+ width: saved.width as f64 / external.scale_factor,
+ height: saved.height as f64 / external.scale_factor,
+ scale_factor: external.scale_factor,
+ };
+ assert!(stored.is_usable());
+ let point = stored.logical();
+ let placed = fit_logical(logical(origin.x + point.x, origin.y + point.y, point.width, point.height), &monitors);
+ assert_eq!(placed, logical(2368.0, 183.0, 1280.0, 800.0));
+ assert_eq!(monitor_for_logical(placed, &monitors), Some(monitors[1]));
+}
+
+#[test]
+fn issue_13168_restores_the_frame_of_a_window_closed_on_the_2x_display() {
+ let monitors = mixed_dpi();
+ let saved = rect(304, 66, 3150, 2168);
+ let built_in = matching_monitor(saved, &monitors).expect("saved on the built-in display");
+ let origin = built_in.logical();
+ let (x, y) = offset_in_monitor(saved, built_in.scale_factor, &built_in);
+ let placed = fit_logical(
+ logical(origin.x + x, origin.y + y, saved.width as f64 / 2.0, saved.height as f64 / 2.0),
+ &monitors,
+ );
+ assert_eq!(placed, logical(152.0, 33.0, 1575.0, 1084.0));
+}
+
+#[test]
+fn the_halved_restore_is_the_reported_symptom() {
+ // What `set_position(Physical…)`/`set_size(Physical…)` did to 1x pixels at 2x.
+ assert_eq!(to_logical(rect(2368, 183, 1280, 800), 2.0), logical(1184.0, 91.5, 640.0, 400.0));
+}