A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
gui: restore the main window's placement on Windows
RoversX35ae208d0359
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex 0a662131..706306fc 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -67,7 +67,7 @@ settings-theme-save-error = Design-Modus konnte nicht gespeichert werden: { $errsettings-main-renderer = Renderer des Hauptfensterssettings-main-renderer-description = Gilt nach einem Neustart für das Haupt-Terminalfenster.settings-restore-window-frame = Fensterrahmen des Hauptfensters wiederherstellen-settings-restore-window-frame-description = macOS stellt Größe und Position des zuletzt genutzten Haupt-Terminalfensters wieder her.+settings-restore-window-frame-description = Öffnet das Haupt-Terminalfenster wieder in der zuletzt verwendeten Größe und Position.settings-restart = ThinkTerm neu startensettings-restart-app = Neu startensettings-restart-status = Renderer-Änderungen: { $status }.diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex 1d4880b0..729cf995 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -67,7 +67,7 @@ settings-theme-save-error = Unable to save theme mode: { $error }settings-main-renderer = Main Window Renderersettings-main-renderer-description = Applies to the main terminal window after restart.settings-restore-window-frame = Restore Main Window Frame-settings-restore-window-frame-description = macOS restores the last main terminal window size and position.+settings-restore-window-frame-description = Reopen the main terminal window at the size and position it was last left.settings-restart = Restart ThinkTermsettings-restart-app = Restartsettings-restart-status = Renderer changes: { $status }.diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex 5493afd6..8b976f0f 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -67,7 +67,7 @@ settings-theme-save-error = Impossible d’enregistrer le thème : { $error }settings-main-renderer = Moteur de rendu de la fenêtre principalesettings-main-renderer-description = S’applique à la fenêtre principale du terminal après redémarrage.settings-restore-window-frame = Restaurer la taille et la position de la fenêtre principale-settings-restore-window-frame-description = macOS restaure la dernière taille et position de la fenêtre principale du terminal.+settings-restore-window-frame-description = Rouvre la fenêtre principale du terminal à la taille et à la position où elle a été laissée.settings-restart = Redémarrer ThinkTermsettings-restart-app = Redémarrersettings-restart-status = Modifications du moteur de rendu : { $status }.diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 8369d443..8ec7c0fe 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -64,7 +64,7 @@ settings-theme-save-error = テーマモードを保存できません:{ $errosettings-main-renderer = メインウィンドウのレンダラーsettings-main-renderer-description = 再起動後にメインターミナルウィンドウへ適用します。settings-restore-window-frame = メインウィンドウの位置とサイズを復元-settings-restore-window-frame-description = macOS で前回のメインターミナルウィンドウのサイズと位置を復元します。+settings-restore-window-frame-description = メインターミナルウィンドウを前回終了時のサイズと位置で開きます。settings-restart = ThinkTerm を再起動settings-restart-app = 再起動settings-restart-status = レンダラーの変更:{ $status }。diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex 1c59b4e1..2eb16dc1 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -64,7 +64,7 @@ settings-theme-save-error = 无法保存主题模式:{ $error }settings-main-renderer = 主窗口渲染器settings-main-renderer-description = 重启后应用于主终端窗口。settings-restore-window-frame = 恢复主窗口位置与大小-settings-restore-window-frame-description = macOS 会恢复上次主终端窗口的大小和位置。+settings-restore-window-frame-description = 按上次关闭时的大小和位置重新打开主终端窗口。settings-restart = 重启 ThinkTermsettings-restart-app = 重启settings-restart-status = 渲染器更改:{ $status }。diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 0ed2fa8f..70ca882c 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -47,6 +47,7 @@ mod glyphcache;mod i18n;mod input_diagnostics;mod inputmap;+mod main_window_placement;mod markdown_editor;mod local_sessions;mod native_paths;diff --git a/wezterm-gui/src/main_window_placement.rs b/wezterm-gui/src/main_window_placement.rsnew file mode 100644index 00000000..c3f55c81--- /dev/null+++ b/wezterm-gui/src/main_window_placement.rs@@ -0,0 +1,456 @@+//! Remembering where the main window was, and putting it back there.+//!+//! macOS does this for us: the window is given a frame autosave name and AppKit+//! keeps the frame in the user defaults. Windows has no such facility, so this+//! module is the equivalent -- it listens for+//! [`window::WindowEvent::WindowFrameChanged`], writes the placement into the+//! native settings, and hands it back to `TermWindow::new` at the next launch.+//!+//! Three things are worth knowing about it:+//!+//! * **One window owns the placement.** ThinkTerm can have several terminal+//! windows; if they all restored the same rect they would open in a stack,+//! and if they all saved it the last one to move would win. So exactly one+//! window holds a claim at a time -- the first one created -- and only that+//! window restores or records. When it closes the claim is released, and+//! whichever window is still open takes it over on its next move.+//!+//! * **Writes are debounced.** A drag produces a message per mouse-move; the+//! settings file is rewritten 500ms after the last of them, on a worker+//! thread, and synchronously on close so that a normal quit cannot race the+//! process exit. A crash loses at most the last half second of dragging.+//!+//! * **A remembered rect is checked against the displays attached now**, not+//! the ones it was saved on. See [`placement_is_usable`].++use crate::native_settings::{self, NativeMainWindowPlacement, NativeScreenRect};+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::{Condvar, Mutex, OnceLock};+use std::time::{Duration, Instant};+use window::ScreenRect;++/// How long the window has to stay still before its placement is written.+const DEBOUNCE: Duration = Duration::from_millis(500);++/// Anything smaller than this is not a window someone arranged, it is damage:+/// a truncated settings file, a hand edit, a window that was mid-teardown when+/// the rect was read.+const MIN_FRAME_WIDTH: i32 = 200;+const MIN_FRAME_HEIGHT: i32 = 120;++/// How much of the window's width has to be on a display for it to be worth+/// reopening there -- enough to see and to grab.+const MIN_VISIBLE_WIDTH: i32 = 120;++/// The band at the top of the window that has to land inside a work area. It+/// does not have to be the real title bar height; it has to be enough of one+/// that the window can be dragged back out of wherever it ended up.+const TITLE_BAR_HEIGHT: i32 = 32;++/// The window that owns the saved placement, as `mux_window_id + 1`, or 0 for+/// "no window holds the claim". Offset by one so that window 0 is not confused+/// with the vacant state.+static MAIN_WINDOW: AtomicUsize = AtomicUsize::new(0);++/// The placement to open a window at.+#[derive(Debug, Clone, Copy)]+pub(crate) struct RestoredFrame {+ pub(crate) frame: ScreenRect,+ pub(crate) maximized: bool,+}++/// Claim the main-window role for this window, or confirm it already holds it.+///+/// Called once when a window is created -- deciding whether it restores the+/// saved placement -- and again on every frame change, which is what lets a+/// surviving window pick up the role after the window that held it closed.+pub(crate) fn claim_main_window(mux_window_id: usize) -> bool {+ let token = mux_window_id.wrapping_add(1);+ match MAIN_WINDOW.compare_exchange(0, token, Ordering::AcqRel, Ordering::Acquire) {+ Ok(_) => true,+ Err(current) => current == token,+ }+}++fn holds_claim(mux_window_id: usize) -> bool {+ MAIN_WINDOW.load(Ordering::Acquire) == mux_window_id.wrapping_add(1)+}++/// The window is going away. Write out whatever the debounce is still holding+/// -- synchronously, because the process may be seconds from exiting -- and let+/// another window take the role over.+pub(crate) fn window_closed(mux_window_id: usize) {+ if !holds_claim(mux_window_id) {+ return;+ }+ flush();+ MAIN_WINDOW.store(0, Ordering::Release);+}++/// The window may be going away: a close was requested, but something may yet+/// cancel it. Get the placement on disk without giving up the claim.+pub(crate) fn close_requested(mux_window_id: usize) {+ if holds_claim(mux_window_id) {+ flush();+ }+}++/// Record where the main window now is. Cheap to call from the event handler:+/// the file write happens later, on another thread, and only if the window+/// stays put.+pub(crate) fn record(mux_window_id: usize, frame: ScreenRect, maximized: bool) {+ if !claim_main_window(mux_window_id) {+ return;+ }+ if !native_settings::restore_main_window_frame_enabled() {+ return;+ }++ let frame = NativeScreenRect {+ x: frame.origin.x as i32,+ y: frame.origin.y as i32,+ width: frame.size.width as i32,+ height: frame.size.height as i32,+ };++ let placement = NativeMainWindowPlacement {+ x: frame.x,+ y: frame.y,+ width: frame.width,+ height: frame.height,+ maximized,+ work_area: work_area_for(frame),+ };++ let (lock, cvar) = debounce_state();+ {+ let mut pending = lock.lock().unwrap_or_else(|err| err.into_inner());+ pending.placement = Some(placement);+ pending.deadline = Instant::now() + DEBOUNCE;+ }+ cvar.notify_all();+}++/// Write any pending placement now, on this thread.+pub(crate) fn flush() {+ let Some(state) = DEBOUNCE_STATE.get() else {+ return;+ };+ let placement = {+ let mut pending = state.0.lock().unwrap_or_else(|err| err.into_inner());+ pending.placement.take()+ };+ if let Some(placement) = placement {+ native_settings::save_main_window_placement(placement);+ }+}++/// The frame the main window should open at, if one was saved and it still+/// makes sense on this desktop.+pub(crate) fn frame_to_restore() -> Option<RestoredFrame> {+ let placement = native_settings::main_window_placement()?;+ let frame = NativeScreenRect {+ x: placement.x,+ y: placement.y,+ width: placement.width,+ height: placement.height,+ };++ let work_areas = work_areas();+ if work_areas.is_empty() {+ // Nothing to check the rect against. Opening blind risks a window+ // nobody can reach, so take the default geometry instead.+ log::warn!("no display work areas reported; ignoring the saved main window placement");+ return None;+ }++ if !placement_is_usable(frame, &work_areas) {+ log::warn!(+ "saved main window placement {frame:?} does not land on any \+ attached display (work areas {work_areas:?}); using the default geometry"+ );+ return None;+ }++ Some(RestoredFrame {+ frame: euclid::rect(+ frame.x as isize,+ frame.y as isize,+ frame.width as isize,+ frame.height as isize,+ ),+ maximized: placement.maximized,+ })+}++/// Is a remembered frame still somewhere a person could use it?+///+/// Displays get unplugged, resolutions change, a laptop comes back from the+/// dock with one screen instead of three. The rule is deliberately about the+/// *title bar* rather than about area: a window is recoverable exactly when+/// enough of its top edge is on a work area to see it and drag it. So the+/// frame must overlap some attached display's work area by at least+/// [`MIN_VISIBLE_WIDTH`] horizontally (or its whole width, if it is narrower+/// than that), and its top edge must sit within that work area with at least+/// [`TITLE_BAR_HEIGHT`] to spare below.+///+/// Note that this is checked against the work areas reported *now*. The work+/// area stored beside the placement records what it was measured against; it+/// is not what grants permission to use it.+fn placement_is_usable(frame: NativeScreenRect, work_areas: &[NativeScreenRect]) -> bool {+ if frame.width < MIN_FRAME_WIDTH || frame.height < MIN_FRAME_HEIGHT {+ return false;+ }++ work_areas.iter().any(|area| {+ let overlap = (frame.x + frame.width).min(area.x + area.width) - frame.x.max(area.x);+ overlap >= MIN_VISIBLE_WIDTH.min(frame.width)+ && frame.y >= area.y+ && frame.y <= area.y + area.height - TITLE_BAR_HEIGHT+ })+}++struct Pending {+ placement: Option<NativeMainWindowPlacement>,+ deadline: Instant,+}++static DEBOUNCE_STATE: OnceLock<(Mutex<Pending>, Condvar)> = OnceLock::new();++fn debounce_state() -> &'static (Mutex<Pending>, Condvar) {+ let state = DEBOUNCE_STATE.get_or_init(|| {+ (+ Mutex::new(Pending {+ placement: None,+ deadline: Instant::now(),+ }),+ Condvar::new(),+ )+ });++ static WORKER: OnceLock<()> = OnceLock::new();+ WORKER.get_or_init(|| {+ std::thread::Builder::new()+ .name("main-window-placement".to_string())+ .spawn(|| debounce_worker(DEBOUNCE_STATE.get().expect("initialized above")))+ .map(|_| ())+ .unwrap_or_else(|err| {+ log::warn!("unable to start the window placement writer: {err:#}");+ })+ });++ state+}++fn debounce_worker(state: &'static (Mutex<Pending>, Condvar)) {+ let (lock, cvar) = state;+ loop {+ let placement = {+ let mut pending = lock.lock().unwrap_or_else(|err| err.into_inner());+ loop {+ if pending.placement.is_none() {+ // Nothing to write: either nothing has moved yet, or+ // `flush` took the pending value out from under us. Wait+ // for the next edge rather than spinning.+ pending = cvar.wait(pending).unwrap_or_else(|err| err.into_inner());+ continue;+ }+ // Something is pending; it goes out once the window has been+ // still for `DEBOUNCE`. Every further move pushes the deadline+ // out, so a long drag costs exactly one write.+ let now = Instant::now();+ if now >= pending.deadline {+ break;+ }+ let wait = pending.deadline - now;+ pending = cvar+ .wait_timeout(pending, wait)+ .unwrap_or_else(|err| err.into_inner())+ .0;+ }+ pending.placement.take()+ };++ if let Some(placement) = placement {+ native_settings::save_main_window_placement(placement);+ }+ }+}++/// The work areas of every display attached right now.+#[cfg(windows)]+fn work_areas() -> Vec<NativeScreenRect> {+ use winapi::shared::minwindef::{LPARAM, TRUE};+ use winapi::shared::windef::{HDC, HMONITOR, LPRECT};+ use winapi::um::winuser::{EnumDisplayMonitors, GetMonitorInfoW, MONITORINFO};++ unsafe extern "system" fn callback(+ mon: HMONITOR,+ _hdc: HDC,+ _rect: LPRECT,+ data: LPARAM,+ ) -> i32 {+ let areas = &mut *(data as *mut Vec<NativeScreenRect>);+ let mut mi: MONITORINFO = std::mem::zeroed();+ mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;+ if GetMonitorInfoW(mon, &mut mi) != 0 {+ areas.push(NativeScreenRect {+ x: mi.rcWork.left,+ y: mi.rcWork.top,+ width: mi.rcWork.right - mi.rcWork.left,+ height: mi.rcWork.bottom - mi.rcWork.top,+ });+ }+ TRUE+ }++ let mut areas: Vec<NativeScreenRect> = Vec::new();+ unsafe {+ EnumDisplayMonitors(+ std::ptr::null_mut(),+ std::ptr::null(),+ Some(callback),+ &mut areas as *mut _ as LPARAM,+ );+ }+ areas+}++/// The work area of the display the window is on, recorded next to the+/// placement so a later launch can tell whether the desktop still looks the+/// way it did.+#[cfg(windows)]+fn work_area_for(frame: NativeScreenRect) -> NativeScreenRect {+ use winapi::shared::windef::RECT;+ use winapi::um::winuser::{+ GetMonitorInfoW, MonitorFromRect, MONITORINFO, MONITOR_DEFAULTTONEAREST,+ };++ let rect = RECT {+ left: frame.x,+ top: frame.y,+ right: frame.x + frame.width,+ bottom: frame.y + frame.height,+ };++ unsafe {+ let mut mi: MONITORINFO = std::mem::zeroed();+ mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;+ let mon = MonitorFromRect(&rect, MONITOR_DEFAULTTONEAREST);+ if GetMonitorInfoW(mon, &mut mi) != 0 {+ NativeScreenRect {+ x: mi.rcWork.left,+ y: mi.rcWork.top,+ width: mi.rcWork.right - mi.rcWork.left,+ height: mi.rcWork.bottom - mi.rcWork.top,+ }+ } else {+ NativeScreenRect::default()+ }+ }+}++/// Only the Windows backend reports frame changes or honours a restored frame,+/// so everywhere else this is inert: nothing is ever recorded, and a settings+/// file carrying a placement from a Windows machine is ignored rather than+/// applied to a desktop whose displays we cannot enumerate here.+#[cfg(not(windows))]+fn work_areas() -> Vec<NativeScreenRect> {+ Vec::new()+}++#[cfg(not(windows))]+fn work_area_for(_frame: NativeScreenRect) -> NativeScreenRect {+ NativeScreenRect::default()+}++#[cfg(test)]+mod tests {+ use super::*;++ fn rect(x: i32, y: i32, width: i32, height: i32) -> NativeScreenRect {+ NativeScreenRect {+ x,+ y,+ width,+ height,+ }+ }++ /// 1024x768 with a 40px taskbar along the bottom, which is what the+ /// machine this was developed on has.+ fn one_display() -> Vec<NativeScreenRect> {+ vec![rect(0, 0, 1024, 728)]+ }++ #[test]+ fn an_ordinary_window_comes_back() {+ assert!(placement_is_usable(rect(120, 90, 700, 500), &one_display()));+ }++ #[test]+ fn a_window_from_a_display_that_is_gone_does_not() {+ assert!(!placement_is_usable(+ rect(5000, 5000, 700, 500),+ &one_display()+ ));+ }++ /// The interesting rejection: the window is still horizontally on screen,+ /// but it was dragged down until the title bar is past the work area, so+ /// reopening it there would leave nothing to grab.+ #[test]+ fn a_title_bar_below_the_work_area_does_not() {+ assert!(!placement_is_usable(+ rect(120, 720, 700, 500),+ &one_display()+ ));+ // ... while one that still clears the title bar band does.+ assert!(placement_is_usable(+ rect(120, 690, 700, 500),+ &one_display()+ ));+ }++ #[test]+ fn a_window_hanging_off_the_right_edge_survives_if_enough_is_visible() {+ assert!(placement_is_usable(+ rect(900, 100, 700, 500),+ &one_display()+ ));+ assert!(!placement_is_usable(+ rect(960, 100, 700, 500),+ &one_display()+ ));+ }++ /// A window above the top of the work area has its title bar off screen on+ /// Windows, where nothing can be dragged down from there.+ #[test]+ fn a_window_above_the_work_area_does_not() {+ assert!(!placement_is_usable(+ rect(120, -40, 700, 500),+ &one_display()+ ));+ }++ #[test]+ fn a_degenerate_rect_does_not() {+ assert!(!placement_is_usable(rect(0, 0, 0, 0), &one_display()));+ assert!(!placement_is_usable(rect(10, 10, 199, 500), &one_display()));+ assert!(!placement_is_usable(rect(10, 10, 700, 119), &one_display()));+ }++ /// A second display to the left lives at negative coordinates, which the+ /// overlap arithmetic has to survive.+ #[test]+ fn a_window_on_a_secondary_display_comes_back() {+ let displays = vec![rect(0, 0, 1024, 728), rect(-1280, -200, 1280, 984)];+ assert!(placement_is_usable(rect(-1200, -150, 700, 500), &displays));+ // Unplug it and the same rect is no longer anywhere.+ assert!(!placement_is_usable(+ rect(-1200, -150, 700, 500),+ &one_display()+ ));+ }+}diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex d8db8302..30ae2b1d 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -329,11 +329,50 @@ pub(crate) struct NativeCompatibilitySettings {pub(crate) last_imported_at: Option<String>,}+/// A rectangle in physical screen pixels, as the platform reports it.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]+#[serde(default)]+pub(crate) struct NativeScreenRect {+ pub(crate) x: i32,+ pub(crate) y: i32,+ pub(crate) width: i32,+ pub(crate) height: i32,+}++/// Where the main window was the last time it was moved, resized or closed,+/// so the next launch can reopen it there.+///+/// The rect is the window's **outer frame** in physical screen pixels, in its+/// normal (unmaximized) state -- a maximized window remembers the rect it+/// would return to, next to `maximized: true`, so both the state and the size+/// behind it survive.+///+/// `work_area` is the work area of the display the window was on when this was+/// written. It is not what decides whether the placement is still usable --+/// the displays attached *now* decide that, see+/// `main_window_placement::placement_is_usable` -- but it records which desktop+/// layout the rect was measured against, which makes an unchanged layout cheap+/// to recognise and a rejected placement possible to explain.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)]+#[serde(default)]+pub(crate) struct NativeMainWindowPlacement {+ pub(crate) x: i32,+ pub(crate) y: i32,+ pub(crate) width: i32,+ pub(crate) height: i32,+ pub(crate) maximized: bool,+ pub(crate) work_area: NativeScreenRect,+}+#[derive(Debug, Clone, Deserialize, Serialize)]#[serde(default)]pub(crate) struct NativeWindowSettings {pub(crate) restore_main_window_frame: bool,pub(crate) main_renderer: Option<NativeRendererBackend>,+ /// Written by the GUI rather than by the Settings UI; `None` until the+ /// main window has been placed somewhere worth remembering. Only consulted+ /// when `restore_main_window_frame` is on.+ pub(crate) main_window_placement: Option<NativeMainWindowPlacement>,}impl Default for NativeWindowSettings {@@ -341,6 +380,7 @@ impl Default for NativeWindowSettings {Self {restore_main_window_frame: true,main_renderer: None,+ main_window_placement: None,}}}@@ -652,6 +692,38 @@ pub(crate) fn save(settings: &ThinkTermNativeSettings) -> anyhow::Result<()> {Ok(())}+/// Where the main window should reopen, or `None` if nothing has been+/// remembered yet or the user turned the setting off.+pub(crate) fn main_window_placement() -> Option<NativeMainWindowPlacement> {+ let settings = load_shared();+ if !settings.window.restore_main_window_frame {+ return None;+ }+ settings.window.main_window_placement+}++/// Whether moving or resizing the main window should still be recorded.+/// Read per move/resize edge rather than cached, so turning the setting off+/// in Settings takes effect on the next drag rather than the next launch.+pub(crate) fn restore_main_window_frame_enabled() -> bool {+ load_shared().window.restore_main_window_frame+}++/// Persist where the main window is. A no-op when nothing changed, which is+/// the common case: the debounce upstream of this already collapses a drag+/// into one call, and a drag that ends where it started should not rewrite+/// the file.+pub(crate) fn save_main_window_placement(placement: NativeMainWindowPlacement) {+ let mut settings = load();+ if settings.window.main_window_placement == Some(placement) {+ return;+ }+ settings.window.main_window_placement = Some(placement);+ if let Err(err) = save(&settings) {+ log::warn!("failed to save main window placement: {err:#}");+ }+}+/// Persist the palette-picked color scheme so new windows and the next/// launch start with it. A no-op when the stored value already matches.pub(crate) fn save_color_scheme(name: Option<String>) {diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex b54ae781..06bf4090 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -2178,6 +2178,9 @@ impl SettingsWindow {x: None,y: None,macos_frame_autosave_name: None,+ // The Settings window is not the main window: it neither restores+ // a remembered frame nor records one.+ windows_frame_rect: None,origin: GeometryOrigin::default(),};diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex c0ad1714..c88a594f 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -2107,6 +2107,16 @@ pub(crate) struct CapturedSidebar {pub(crate) list: Option<(HeapQuadMark, HeapQuadMark)>,}+/// How many times a restored window may be put back on its remembered frame+/// while startup settles. Enough for the handful of resizes a launch produces,+/// short enough that it cannot turn into a loop.+const RESTORED_FRAME_ATTEMPTS: u8 = 8;++/// How long after opening a restored window its frame is still worth+/// correcting. Long enough to cover the resizes a launch produces, short+/// enough that it is over before the user has reached for the window.+const RESTORED_FRAME_SETTLE_TIME: Duration = Duration::from_secs(3);+pub struct TermWindow {pub window: Option<Window>,pub config: ConfigHandle,@@ -2301,6 +2311,19 @@ pub struct TermWindow {opengl_info: Option<String>,+ /// The frame a restored main window is meant to occupy, until the startup+ /// resizes have settled on it. See `reassert_restored_frame`.+ restored_frame_target: Option<ScreenRect>,+ /// How many more times that correction may be applied before giving up, so+ /// a backend that will not take the frame cannot be fought forever.+ restored_frame_attempts: u8,+ /// When to stop correcting regardless. Startup does not always disturb the+ /// frame -- a window that reopens at a size the GUI is happy with is left+ /// alone -- and without a deadline the correction would still be armed+ /// much later, when the first thing it "corrected" would be the user+ /// resizing their own window.+ restored_frame_deadline: Option<Instant>,+/// Keeps track of double and triple clickslast_mouse_click: Option<LastMouseClick>,@@ -3926,6 +3949,9 @@ impl TermWindow {key_table_state: KeyTableState::default(),modal: RefCell::new(None),opengl_info: None,+ restored_frame_target: None,+ restored_frame_attempts: 0,+ restored_frame_deadline: None,};let tw = Rc::new(RefCell::new(myself));@@ -3945,6 +3971,28 @@ impl TermWindow {origin = position.origin;}+ // The main window -- the first one this process opens -- reopens where+ // it was last left, provided that is still somewhere on this desktop.+ // `claim_main_window` runs first and unconditionally: a window that is+ // not restoring its frame is still the window that records one, should+ // the setting be turned on while it is open.+ //+ // An explicit position outranks a remembered one. Someone who passed+ // `--position`, or moved the window from the CLI, is asking about this+ // launch, not the last one.+ //+ // macOS is untouched by any of this and keeps using AppKit's frame+ // autosave below; `frame_to_restore` yields nothing there.+ let restored_frame = if crate::main_window_placement::claim_main_window(mux_window_id)+ && native_settings.window.restore_main_window_frame+ && x.is_none()+ && y.is_none()+ {+ crate::main_window_placement::frame_to_restore()+ } else {+ None+ };+let geometry = RequestedWindowGeometry {width: Dimension::Pixels(dimensions.pixel_width as f32),height: Dimension::Pixels(dimensions.pixel_height as f32),@@ -3957,6 +4005,7 @@ impl TermWindow {} else {None},+ windows_frame_rect: restored_frame.map(|restored| restored.frame),origin,};log::trace!("{:?}", geometry);@@ -3976,7 +4025,17 @@ impl TermWindow {).await?;window.set_titlebar_sidebar_button_visible(true);- tw.borrow_mut().window.replace(window.clone());+ {+ let mut tw = tw.borrow_mut();+ tw.window.replace(window.clone());+ // Opening at the remembered rect is only half of it; see+ // `settle_restored_frame` for what startup does to it afterwards.+ if let Some(restored) = restored_frame.filter(|restored| !restored.maximized) {+ tw.restored_frame_target = Some(restored.frame);+ tw.restored_frame_attempts = RESTORED_FRAME_ATTEMPTS;+ tw.restored_frame_deadline = Some(Instant::now() + RESTORED_FRAME_SETTLE_TIME);+ }+ }Self::apply_icon(&window)?;@@ -4088,6 +4147,15 @@ impl TermWindow {myself.resize_mux_tabs_to_current_terminal_size();}window.show();+ // Maximizing after the window is shown, rather than asking for a+ // maximized window up front: `show` is an ordinary "restore and+ // show" on Windows and would undo an earlier maximize. Doing it+ // this way round also leaves the rect we opened at as the one+ // Windows puts the window back at, so unmaximizing lands on the+ // size the window had before it was maximized.+ if restored_frame.map_or(false, |restored| restored.maximized) {+ window.maximize();+ }myself.subscribe_to_pane_updates();myself.emit_window_event("window-config-reloaded", None);myself.emit_status_event();@@ -4127,6 +4195,7 @@ impl TermWindow {log::debug!("{event:?}");match event {WindowEvent::Destroyed => {+ crate::main_window_placement::window_closed(self.mux_window_id);self.flush_right_sidebar_note_blocking();self.clear_gui_recovery_intent();// Ensure that we cancel any overlays we had running, so@@ -4139,9 +4208,22 @@ impl TermWindow {Ok(false)}WindowEvent::CloseRequested => {+ // Get the placement on disk before anything that might quit+ // the process gets going. The claim is kept: the close may+ // still be called off by a confirmation prompt.+ crate::main_window_placement::close_requested(self.mux_window_id);self.close_requested(window);Ok(true)}+ WindowEvent::WindowFrameChanged { frame, maximized } => {+ // While a restored frame is still being asserted the window is+ // passing through geometry nobody chose; recording it would+ // save the startup wobble rather than where the window lives.+ if !self.settle_restored_frame(frame, maximized, window) {+ crate::main_window_placement::record(self.mux_window_id, frame, maximized);+ }+ Ok(true)+ }WindowEvent::AppearanceChanged(appearance) => {log::debug!("Appearance is now {:?}", appearance);// This is a bit fugly; we get per-window notifications@@ -4443,6 +4525,53 @@ impl TermWindow {}}+ /// Put a restored window back on the frame it reopened at, if startup has+ /// moved it off. Returns true while that is still in progress.+ ///+ /// Opening at the remembered rect is not enough on its own: the first real+ /// resize event makes the GUI recompute its pixel size from the font+ /// metrics and the configured rows and columns and ask the window for+ /// *that*, which throws away the size we just reopened at. Suppressing+ /// that recalculation is the wrong fix -- it is what keeps the terminal's+ /// shape across a dpi change -- so the remembered frame is simply asserted+ /// again afterwards.+ ///+ /// Each correction produces another frame-changed event, so this settles+ /// as soon as the frame matches; the attempt budget keeps it from becoming+ /// a tug of war with a backend that will not take the rect. A window that+ /// comes back maximized is left alone: its frame is the screen's, and the+ /// rect we opened at is already its restore rect.+ fn settle_restored_frame(+ &mut self,+ frame: ScreenRect,+ maximized: bool,+ window: &Window,+ ) -> bool {+ let Some(target) = self.restored_frame_target else {+ return false;+ };++ let expired = self+ .restored_frame_deadline+ .map_or(true, |deadline| Instant::now() > deadline);++ if maximized || frame == target || self.restored_frame_attempts == 0 || expired {+ if frame != target && !maximized {+ log::warn!(+ "gave up restoring the main window frame to {target:?}; it settled at {frame:?}"+ );+ }+ self.restored_frame_target = None;+ self.restored_frame_deadline = None;+ return false;+ }++ self.restored_frame_attempts -= 1;+ log::trace!("re-asserting restored main window frame {target:?}, saw {frame:?}");+ window.set_frame_rect(target);+ true+ }+fn do_paint(&mut self, window: &Window) -> bool {// A repaint of a hidden window (a resize completing, a config// reload) regrows what the occlusion release dropped; mark thediff --git a/window/examples/async.rs b/window/examples/async.rsindex 369d6538..278edc30 100644--- a/window/examples/async.rs+++ b/window/examples/async.rs@@ -96,6 +96,7 @@ impl MyWindow {| WindowEvent::ToggleWorkspaceSidebar| WindowEvent::WorkspaceSidebarButtonHover(_)| WindowEvent::MouseLeave+ | WindowEvent::WindowFrameChanged { .. }| WindowEvent::SetInnerSizeCompleted => {}}}diff --git a/window/src/lib.rs b/window/src/lib.rsindex cf4c03f2..04938ebb 100644--- a/window/src/lib.rs+++ b/window/src/lib.rs@@ -614,6 +614,26 @@ pub enum WindowEvent {/// Called when a program-requested set_inner_size() has finishedSetInnerSizeCompleted,+ /// The geometry a later launch would want to restore this window to has+ /// changed: the window was moved, resized, maximized or unmaximized.+ ///+ /// `frame` is the *outer frame* rect in physical screen pixels -- the rect+ /// the platform reports for the window itself, not its client area -- and+ /// it is always the **normal-state** rect, so a maximized window reports+ /// the rect it would return to rather than the screen it now covers.+ ///+ /// Nothing is dispatched while the window is minimized or full screen:+ /// neither state describes a geometry worth remembering.+ ///+ /// Only the Windows backend sends this. It is the only one where the GUI+ /// would otherwise never hear about a plain move, and the only one whose+ /// placement ThinkTerm persists itself; macOS restores its main window+ /// through the system's frame autosave instead.+ WindowFrameChanged {+ frame: ScreenRect,+ maximized: bool,+ },+/// Called when the window has been invalidated and needs to/// be repaintedNeedRepaint,@@ -814,6 +834,18 @@ pub trait WindowOps {/// windows to move themselves (not Wayland).fn set_window_position(&self, _coords: ScreenPoint) {}+ /// Move and size the window to an exact outer-frame rect, in physical+ /// screen pixels -- the same coordinates+ /// [`WindowEvent::WindowFrameChanged`] reports and+ /// [`RequestedWindowGeometry::windows_frame_rect`] opens at.+ ///+ /// Unlike `set_inner_size`, this says nothing about the client area, so a+ /// remembered frame can be re-applied without the frame-to-client+ /// arithmetic that would round-trip it inexactly.+ ///+ /// Only the Windows backend implements it.+ fn set_frame_rect(&self, _rect: ScreenRect) {}+/// inform the windowing system of the current textual/// cursor input location. This is used primarily for/// the platform specific input method editor@@ -902,6 +934,19 @@ pub struct RequestedWindowGeometry {pub x: Option<Dimension>,pub y: Option<Dimension>,pub macos_frame_autosave_name: Option<String>,+ /// An exact outer-frame rect, in physical screen pixels, to open the+ /// window at -- the counterpart of [`WindowEvent::WindowFrameChanged`],+ /// and the only way to reproduce a remembered placement exactly.+ ///+ /// When set it supersedes `width`, `height`, `x`, `y` and `origin`. Those+ /// describe a *client* area, which the backend then grows by whatever+ /// frame the system draws; a window whose frame is being restored must not+ /// go through that conversion or it gains the frame's thickness on every+ /// launch. ThinkTerm also draws its own title bar, so the frame-to-client+ /// relationship the conversion assumes is not the one it has.+ ///+ /// Only the Windows backend honours it; elsewhere it is ignored.+ pub windows_frame_rect: Option<ScreenRect>,/// Specifies basis for evaluating x/y coords./// Also applies to width/height when computing % based dimensionspub origin: GeometryOrigin,diff --git a/window/src/os/windows/window.rs b/window/src/os/windows/window.rsindex 70676b37..0207811c 100644--- a/window/src/os/windows/window.rs+++ b/window/src/os/windows/window.rs@@ -138,6 +138,10 @@ pub(crate) struct WindowInner {/// Last effective visibility sent to the platform-neutral window layer./// WM_WINDOWPOSCHANGED is noisy, so only edges should restart its timers.occlusion_visible: Option<bool>,+ /// Last restore geometry reported as `WindowFrameChanged`, for the same+ /// reason as `occlusion_visible`: the owner wants the edges, not a message+ /// per pixel of a drag.+ last_frame_event: Option<(ScreenRect, bool)>,}#[derive(Debug, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]@@ -750,6 +754,7 @@ impl Window {class_name: &str,name: &str,geometry: ResolvedGeometry,+ frame_rect: Option<ScreenRect>,lparam: *const RefCell<WindowInner>,) -> anyhow::Result<HWND> {let class_name = wide_string(class_name);@@ -782,6 +787,40 @@ impl Window {let decorations = config.window_decorations;let style = decorations_to_style(decorations);+ // A remembered frame is already in the units CreateWindowExW wants --+ // an outer-frame rect in screen pixels -- so it goes straight through,+ // with none of the client-to-window growing or monitor guessing that+ // the rest of this function does. That is what makes the round trip+ // exact: what `GetWindowRect` gave us last time is what it gives us+ // again, with no frame thickness added and no dpi re-derivation.+ if let Some(frame) = frame_rect {+ let name = wide_string(name);+ let hwnd = unsafe {+ CreateWindowExW(+ 0,+ class_name.as_ptr(),+ name.as_ptr(),+ style,+ frame.origin.x as i32,+ frame.origin.y as i32,+ frame.size.width as i32,+ frame.size.height as i32,+ null_mut(),+ null_mut(),+ null_mut(),+ std::mem::transmute(lparam),+ )+ };++ if hwnd.is_null() {+ let err = IoError::last_os_error();+ bail!("CreateWindowExW: {}", err);+ }++ schedule_apply_decoration(hwnd, decorations);+ return Ok(hwnd);+ }+// A WS_POPUP window has no system frame to place, so we choose its// position ourselves. Put it on the monitor `active_monitor` picks,// because that is the monitor whose dpi `default_dpi` reported when@@ -892,6 +931,7 @@ impl Window {paint_throttled: false,invalidated: true,occlusion_visible: None,+ last_frame_event: None,}));// Careful: `raw` owns a ref to inner, but there is no Drop impl@@ -903,17 +943,26 @@ impl Window {// measures the requested size against this dpi, and `create_window`// needs to know which monitor's scale the result assumed.let creation_dpi = conn.default_dpi() as usize;+ // Taken before `resolve_geometry` consumes the request: a remembered+ // frame bypasses the resolution entirely.+ let frame_rect = geometry.windows_frame_rect;let geometry = conn.resolve_geometry(geometry);- let hwnd =- match Self::create_window(config.clone(), class_name, name, geometry.clone(), raw) {- Ok(hwnd) => HWindow(hwnd),- Err(err) => {- // Ensure that we drop the extra ref to raw before we return- drop(unsafe { Rc::from_raw(raw) });- return Err(err);- }- };+ let hwnd = match Self::create_window(+ config.clone(),+ class_name,+ name,+ geometry.clone(),+ frame_rect,+ raw,+ ) {+ Ok(hwnd) => HWindow(hwnd),+ Err(err) => {+ // Ensure that we drop the extra ref to raw before we return+ drop(unsafe { Rc::from_raw(raw) });+ return Err(err);+ }+ };let window_handle = Window(hwnd);inner.borrow_mut()@@ -926,13 +975,19 @@ impl Window {// the new size in `last_size` regardless - so correcting the size any// earlier would leave the owner believing the dimensions it asked for// while the later, real resize deduped itself away as "no change".- resize_client_for_actual_monitor(- hwnd.0,- decorations_to_style(config.window_decorations),- &config,- &geometry,- creation_dpi,- );+ // Skipped for a restored frame: that correction exists to re-derive a+ // window size from a requested *client* size once the real monitor is+ // known, and the restored rect is already the size we want, measured+ // on this same desktop the last time the window was open.+ if frame_rect.is_none() {+ resize_client_for_actual_monitor(+ hwnd.0,+ decorations_to_style(config.window_decorations),+ &config,+ &geometry,+ creation_dpi,+ );+ }apply_theme(hwnd.0);enable_blur_behind(hwnd.0);@@ -1210,6 +1265,27 @@ impl WindowOps for Window {.detach();}+ fn set_frame_rect(&self, rect: ScreenRect) {+ let hwnd = self.0;+ // Scheduled rather than immediate for the same reason the other window+ // ops here are: SetWindowPos re-enters the window proc, which wants a+ // borrow of the inner state the caller may still be holding.+ promise::spawn::spawn(async move {+ unsafe {+ SetWindowPos(+ hwnd.0,+ null_mut(),+ rect.origin.x as i32,+ rect.origin.y as i32,+ rect.size.width as i32,+ rect.size.height as i32,+ SWP_NOZORDER | SWP_NOACTIVATE,+ );+ }+ })+ .detach();+ }+fn maximize(&self) {schedule_show_window(self.0, ShowWindowCommand::Maximize);}@@ -2133,10 +2209,115 @@ unsafe fn wm_windowposchanged() -> Option<LRESULT> {// let pos = &*(lparam as *const WINDOWPOS);dispatch_occlusion_changed_if_needed(hwnd);+ dispatch_frame_changed_if_needed(hwnd);wm_size(hwnd, 0, 0, 0)?;Some(0)}+/// The restore geometry of the window, or `None` if this is a moment whose+/// geometry is not worth remembering.+///+/// A minimized window has no meaningful rect at all. A full-screen one -- ours+/// or the system's idea of one -- has the monitor's, which is not something a+/// later launch should reopen at. A maximized window has the work area's, so+/// its *restore* rect is read from `GetWindowPlacement` instead: that is the+/// rect Windows itself would put the window back at.+///+/// `rcNormalPosition` is documented as being in workspace coordinates, which+/// differ from screen coordinates when the taskbar is docked to the top or the+/// left edge, so it is shifted by the monitor's work-area origin to match what+/// `GetWindowRect` would have said. The ordinary, unmaximized path takes+/// `GetWindowRect` directly and needs no such correction.+unsafe fn restore_frame_rect(+ hwnd: HWND,+ self_drawn_full_screen: bool,+) -> Option<(ScreenRect, bool)> {+ if IsIconic(hwnd) != winapi::shared::minwindef::FALSE {+ return None;+ }++ let state = get_window_state(hwnd);+ if self_drawn_full_screen || state == WindowState::FULL_SCREEN {+ return None;+ }++ let maximized = state == WindowState::MAXIMIZED;++ let rect = if maximized {+ let mut placement = WINDOWPLACEMENT {+ length: std::mem::size_of::<WINDOWPLACEMENT>() as _,+ ..Default::default()+ };+ if GetWindowPlacement(hwnd, &mut placement) != winapi::shared::minwindef::TRUE {+ return None;+ }++ let mut mi: MONITORINFO = std::mem::zeroed();+ mi.cbSize = std::mem::size_of::<MONITORINFO>() as u32;+ let (dx, dy) =+ if GetMonitorInfoW(MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST), &mut mi) != 0 {+ (+ mi.rcWork.left - mi.rcMonitor.left,+ mi.rcWork.top - mi.rcMonitor.top,+ )+ } else {+ (0, 0)+ };++ let mut rect = placement.rcNormalPosition;+ rect.left += dx;+ rect.right += dx;+ rect.top += dy;+ rect.bottom += dy;+ rect+ } else {+ let mut rect: RECT = std::mem::zeroed();+ if GetWindowRect(hwnd, &mut rect) == 0 {+ return None;+ }+ rect+ };++ let width = rect_width(&rect);+ let height = rect_height(&rect);+ if width <= 0 || height <= 0 {+ return None;+ }++ Some((+ euclid::rect(+ rect.left as isize,+ rect.top as isize,+ width as isize,+ height as isize,+ ),+ maximized,+ ))+}++/// Tell the owner where the window would want to reopen. WM_WINDOWPOSCHANGED+/// is the only message that covers plain moves as well as resizes, and it is+/// noisy, so -- as with the occlusion dispatch above -- only edges go out.+unsafe fn dispatch_frame_changed_if_needed(hwnd: HWND) {+ let Some(inner) = rc_from_hwnd(hwnd) else {+ return;+ };+ let mut inner = inner.borrow_mut();++ let Some(current) = restore_frame_rect(hwnd, inner.saved_placement.is_some()) else {+ return;+ };+ if inner.last_frame_event == Some(current) {+ return;+ }+ inner.last_frame_event = Some(current);++ let (frame, maximized) = current;+ inner+ .events+ .dispatch(WindowEvent::WindowFrameChanged { frame, maximized });+}+fn window_is_effectively_visible(is_visible: bool, is_iconic: bool) -> bool {is_visible && !is_iconic}