Skip to content

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.

window: report occlusion changes and stop dropping focus edges

RoversX80c34c4f62ff
diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rs
index a74b1d8c..38ced586 100644
--- a/wezterm-gui/src/termwindow/mod.rs
+++ b/wezterm-gui/src/termwindow/mod.rs
@@ -1892,6 +1892,11 @@ pub struct TermWindow {
os_parameters: Option<parameters::Parameters>,
/// When we most recently received keyboard focus
pub focused: Option<Instant>,
+ /// When the window stopped being visible to the user (fully covered,
+ /// minimized, on another macOS Space, app hidden). None while
+ /// visible. The timestamp doubles as the start of the grace period
+ /// before occlusion-driven cache release.
+ occluded: Option<Instant>,
fonts: Rc<FontConfiguration>,
/// Window dimensions and dpi
pub dimensions: Dimensions,
@@ -2747,6 +2752,18 @@ impl TermWindow {
|| self.workspace_sidebar_hover.needs_frames()
}
+ /// Tracks whether the user can see this window at all. macOS reports
+ /// the transition via WindowEvent::OcclusionChanged; other platforms
+ /// never emit it and the window simply counts as always visible.
+ fn occlusion_changed(&mut self, visible: bool, _window: &Window) {
+ log::trace!("Setting occlusion visible={visible:?}");
+ if visible {
+ self.occluded = None;
+ } else if self.occluded.is_none() {
+ self.occluded = Some(Instant::now());
+ }
+ }
+
fn focus_changed(&mut self, focused: bool, window: &Window) {
if focused == self.focused.is_some() {
// Level rechecks (and AppKit itself) can repeat an edge; a
@@ -2757,6 +2774,14 @@ impl TermWindow {
}
log::trace!("Setting focus to {:?}", focused);
self.focused = if focused { Some(Instant::now()) } else { None };
+ if focused {
+ // Focus implies visible; belt-and-braces cover for a lost
+ // occlusion edge (the window backend re-posts rather than
+ // drops them). If a window somehow gains key focus while
+ // genuinely still hidden, this skips at most one episode's
+ // release — accepted.
+ self.occluded = None;
+ }
// Disarm the unfocused repaint throttle either way: on focus the
// invalidate below repaints immediately and a stale latch would
// swallow the next output event; on blur the first output should
@@ -3078,6 +3103,7 @@ impl TermWindow {
config_overrides,
palette: None,
focused: None,
+ occluded: None,
mux_window_id,
mux_window_id_for_subscriptions: Arc::new(Mutex::new(mux_window_id)),
fonts: Rc::clone(&fontconfig),
@@ -3613,6 +3639,10 @@ impl TermWindow {
self.focus_changed(focused, window);
Ok(true)
}
+ WindowEvent::OcclusionChanged(visible) => {
+ self.occlusion_changed(visible, window);
+ Ok(true)
+ }
WindowEvent::MouseEvent(event) => {
self.mouse_event_impl(event, window);
Ok(true)
diff --git a/window/examples/async.rs b/window/examples/async.rs
index 3fe34805..369d6538 100644
--- a/window/examples/async.rs
+++ b/window/examples/async.rs
@@ -79,6 +79,7 @@ impl MyWindow {
}
}
WindowEvent::AppearanceChanged(_)
+ | WindowEvent::OcclusionChanged(_)
| WindowEvent::AdviseDeadKeyStatus(_)
| WindowEvent::AdviseModifiersLedStatus(_, _)
| WindowEvent::Notification(_)
diff --git a/window/src/lib.rs b/window/src/lib.rs
index 82f8a77a..a6e779d6 100644
--- a/window/src/lib.rs
+++ b/window/src/lib.rs
@@ -624,6 +624,12 @@ pub enum WindowEvent {
/// Called when the window gains/loses focus
FocusChanged(bool),
+ /// Called when the window stops being visible to the user (false:
+ /// fully covered, minimized, on another macOS Space, or the app is
+ /// hidden) and when it becomes visible again (true). Only the macOS
+ /// backend emits this today.
+ OcclusionChanged(bool),
+
AdviseDeadKeyStatus(DeadKeyStatus),
NativeTextInputReplace {
diff --git a/window/src/os/macos/window.rs b/window/src/os/macos/window.rs
index 5cbb33b0..a7effd9a 100644
--- a/window/src/os/macos/window.rs
+++ b/window/src/os/macos/window.rs
@@ -438,6 +438,11 @@ pub fn set_application_icon_from_file(path: &Path) -> anyhow::Result<()> {
Ok(())
}
+#[link(name = "Foundation", kind = "framework")]
+extern "C" {
+ static NSRunLoopCommonModes: id;
+}
+
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
fn CGSMainConnectionID() -> id;
@@ -3548,28 +3553,81 @@ impl WindowView {
}
}
+ /// Re-post `selector` for a later runloop turn in the common modes,
+ /// so the retry also fires inside tracking loops (title-bar drags,
+ /// live resize, open menus) — a plain afterDelay: schedules only in
+ /// the default mode and can defer for the whole interaction.
+ ///
+ /// Earlier pending posts of the same selector are cancelled first
+ /// (the rechecks are level reads, one is enough), and the small
+ /// non-zero delay keeps a busy-borrow retry from turning into a
+ /// zero-delay spin should a future handler ever hold the borrow
+ /// across a nested runloop.
+ fn perform_in_common_modes(view_ptr: id, selector: Sel) {
+ unsafe {
+ let () = msg_send![class!(NSObject), cancelPreviousPerformRequestsWithTarget: view_ptr
+ selector: selector
+ object: nil];
+ let modes: id = msg_send![class!(NSArray), arrayWithObject: NSRunLoopCommonModes];
+ let () = msg_send![view_ptr, performSelector: selector
+ withObject: nil
+ afterDelay: 0.02
+ inModes: modes];
+ }
+ }
+
extern "C" fn did_become_key(this: &mut Object, _sel: Sel, _id: id) {
+ let view_ptr: id = this as *mut Object;
if let Some(this) = Self::get_this(this) {
if let Ok(mut inner) = this.inner.try_borrow_mut() {
inner.events.dispatch(WindowEvent::FocusChanged(true));
} else {
- log::trace!("skipping focus gained notification while window is busy");
+ // Key-window state is level-triggered and queryable, so a
+ // busy window re-reads it next turn instead of dropping
+ // the edge: a stale focus flag now also means a stale
+ // repaint throttle and frame latency, not just a wrong
+ // cursor style.
+ log::trace!("re-posting focus recheck while window is busy");
+ Self::perform_in_common_modes(view_ptr, sel!(thinktermRecheckKey));
}
this.update_application_presentation(true);
}
}
extern "C" fn did_resign_key(this: &mut Object, _sel: Sel, _id: id) {
+ let view_ptr: id = this as *mut Object;
if let Some(this) = Self::get_this(this) {
if let Ok(mut inner) = this.inner.try_borrow_mut() {
inner.events.dispatch(WindowEvent::FocusChanged(false));
} else {
- log::trace!("skipping focus lost notification while window is busy");
+ log::trace!("re-posting focus recheck while window is busy");
+ Self::perform_in_common_modes(view_ptr, sel!(thinktermRecheckKey));
}
this.update_application_presentation(true);
}
}
+ extern "C" fn recheck_key(view: &mut Object, _sel: Sel) {
+ let view_ptr: id = view as *mut Object;
+ if let Some(this) = Self::get_this(view) {
+ // See recheck_occlusion: a post-close recheck must not
+ // dispatch a spurious blur into a torn-down TermWindow.
+ let window: id = unsafe { msg_send![view_ptr, window] };
+ if window.is_null() {
+ return;
+ }
+ let is_key = unsafe {
+ let key: BOOL = msg_send![window, isKeyWindow];
+ key == YES
+ };
+ if let Ok(mut inner) = this.inner.try_borrow_mut() {
+ inner.events.dispatch(WindowEvent::FocusChanged(is_key));
+ } else {
+ Self::perform_in_common_modes(view_ptr, sel!(thinktermRecheckKey));
+ }
+ }
+ }
+
extern "C" fn did_change_occlusion_state(view: &mut Object, _sel: Sel, _id: id) {
// AppKit suppresses drawRect for occluded windows (covered, or on
// another Space). If a frame was requested while we were hidden, the
@@ -3579,23 +3637,42 @@ impl WindowView {
const NS_WINDOW_OCCLUSION_STATE_VISIBLE: NSUInteger = 1 << 1;
let view_ptr: id = view as *mut Object;
if let Some(this) = Self::get_this(view) {
+ // A deferred recheck can fire after the window closed
+ // (performSelector retains the view); a nil window must not
+ // dispatch a destructive "occluded" edge into a torn-down
+ // TermWindow.
+ let window: id = unsafe { msg_send![view_ptr, window] };
+ if window.is_null() {
+ return;
+ }
let visible = unsafe {
- let window: id = msg_send![view_ptr, window];
- if window.is_null() {
- false
- } else {
- let state: NSUInteger = msg_send![window, occlusionState];
- (state & NS_WINDOW_OCCLUSION_STATE_VISIBLE) != 0
- }
+ let state: NSUInteger = msg_send![window, occlusionState];
+ (state & NS_WINDOW_OCCLUSION_STATE_VISIBLE) != 0
};
if visible && this.invalidated.get() {
unsafe {
let () = msg_send![view_ptr, setNeedsDisplay: YES];
}
}
+ // Deliver the transition to the app layer. Occlusion is
+ // level-triggered and queryable, so unlike focus a busy
+ // window must not drop the edge — a lost "visible again"
+ // would leave the GUI convinced the window is still hidden
+ // and let a deferred cache release run in front of the
+ // user. Re-post and re-read instead.
+ if let Ok(mut inner) = this.inner.try_borrow_mut() {
+ inner.events.dispatch(WindowEvent::OcclusionChanged(visible));
+ } else {
+ log::trace!("re-posting occlusion recheck while window is busy");
+ Self::perform_in_common_modes(view_ptr, sel!(thinktermRecheckOcclusion));
+ }
}
}
+ extern "C" fn recheck_occlusion(this: &mut Object, _sel: Sel) {
+ Self::did_change_occlusion_state(this, sel!(windowDidChangeOcclusionState:), nil);
+ }
+
// Switch the coordinate system to have 0,0 in the top left
extern "C" fn is_flipped(_this: &Object, _sel: Sel) -> BOOL {
YES
@@ -4898,6 +4975,14 @@ impl WindowView {
sel!(thinktermRearmNeedsDisplay),
Self::rearm_needs_display as extern "C" fn(&mut Object, Sel),
);
+ cls.add_method(
+ sel!(thinktermRecheckOcclusion),
+ Self::recheck_occlusion as extern "C" fn(&mut Object, Sel),
+ );
+ cls.add_method(
+ sel!(thinktermRecheckKey),
+ Self::recheck_key as extern "C" fn(&mut Object, Sel),
+ );
cls.add_method(
sel!(thinktermDrainNotifications),
Self::drain_notifications as extern "C" fn(&mut Object, Sel),