fix(window): hide windows on the display of the monitor that has them

A window whose top-left corner is past the left edge of the screen is
on no display, as far as CGGetDisplaysWithPoint is concerned. Looking
the display up from the corner then found nothing, and hide, the
scrolling rest and the slide back in all skipped the window without a
word. The Scrolling layout lets a column overhang the left edge, so a
column that scrolled out of view that way stayed on screen, and so did
a window of a workspace that was left while it overhung.

A workspace now takes the display from its monitor and hands it down
to Container::hide and Window::hide_on, and arrange_scrolling hands
it to hide_scrolling. A window that is parked remembers the display it
was parked on, so sliding it back in no longer looks at its target.

The lookup by position stays for callers that have no monitor, and is
total: the display under the corner when there is one, otherwise the
display with the most overlap, otherwise the nearest, and the main
display when the system reports none. Not finding a display to hide a
window on is logged as a warning, and which rest a window gets is
logged at trace.
This commit is contained in:
LGUG2Z committed 2026-10-29 16:38:53 -07:00
1 parent acc4d7d67a
commit 65265c95f3
7 files changed
+426 -62

No files matched your search

+6 -1
View File
@@ -5,6 +5,7 @@ use crate::ring::Ring;
use crate::window::Window;
use color_eyre::eyre;
use nanoid::nanoid;
use objc2_core_foundation::CGRect;
use serde::Deserialize;
use serde::Serialize;
@@ -150,10 +151,14 @@ impl Container {
window
}
/// Hide the windows of the container, other than `omit`, on `screen`, the bounds of the display
/// of the monitor that has the container, or on whichever display they are found on if that is
/// not given
pub fn hide(
&mut self,
hiding_position: WindowHidingPosition,
omit: Option<u32>,
screen: Option<CGRect>,
) -> eyre::Result<()> {
for window in self.windows_mut().iter_mut().rev() {
let mut should_hide = omit.is_none();
@@ -166,7 +171,7 @@ impl Container {
}
// a window that has gone away must not leave the ones after it in view
if should_hide && let Err(error) = window.hide(hiding_position) {
if should_hide && let Err(error) = window.hide_on(hiding_position, screen) {
tracing::warn!("failed to hide window {}: {error}", window.id);
}
}
+232 -21
View File
@@ -8,6 +8,7 @@ use objc2_core_graphics::CGDisplayBounds;
use objc2_core_graphics::CGDisplaySerialNumber;
use objc2_core_graphics::CGGetDisplaysWithPoint;
use objc2_core_graphics::CGGetOnlineDisplayList;
use objc2_core_graphics::CGMainDisplayID;
use objc2_core_graphics::CGRectIntersectsRect;
use objc2_core_graphics::CGWarpMouseCursorPosition;
use objc2_core_graphics::CGWindowListCopyWindowInfo;
@@ -60,30 +61,42 @@ impl CoreGraphicsApi {
CGDisplaySerialNumber(display_id)
}
/// The bounds of the display that a window with this frame is on
///
/// The display under the top-left corner of the window answers whenever there is one. A window
/// whose top-left corner is past the edge of every display, such as one that overhangs the left
/// edge of the screen or is parked beyond it, is on the display that it overlaps the most, or
/// failing that on the nearest one. Only a system that reports no displays at all gets the main
/// display, which is logged.
pub fn display_bounds_for_window_rect(window_rect: CGRect) -> Option<CGRect> {
let mut displays: Vec<u32> = Vec::with_capacity(1);
let mut display_count = 0;
unsafe {
match CoreGraphicsError::from(CGGetDisplaysWithPoint(
window_rect.origin,
displays.capacity() as u32,
displays.as_mut_ptr(),
&mut display_count,
)) {
CoreGraphicsError::Success => {
displays.set_len(display_count as usize);
}
error => {
tracing::error!("failed to find display for point: {error}");
return None;
}
}
if let Some(display) = CoreGraphicsApi::display_with_point(window_rect.origin) {
return Some(CoreGraphicsApi::display_bounds(display));
}
displays
.first()
.map(|display| CoreGraphicsApi::display_bounds(*display))
let displays = CoreGraphicsApi::connected_display_ids()
.unwrap_or_default()
.into_iter()
.map(CoreGraphicsApi::display_bounds)
.collect::<Vec<_>>();
if let Some(idx) = display_for_frame(window_rect, &displays) {
tracing::trace!(
"no display under {},{}, using the one that is nearest to the window",
window_rect.origin.x,
window_rect.origin.y,
);
return displays.get(idx).copied();
}
tracing::warn!(
"no display is known for the window at {},{}, using the main display",
window_rect.origin.x,
window_rect.origin.y,
);
let bounds = CoreGraphicsApi::display_bounds(CGMainDisplayID());
(bounds.size.width > 0.0 && bounds.size.height > 0.0).then_some(bounds)
}
pub fn display_with_point(point: CGPoint) -> Option<u32> {
@@ -119,3 +132,201 @@ impl CoreGraphicsApi {
)
}
}
/// Which of `displays` a window with this frame belongs to
///
/// The display under the top-left corner of the window comes first, since that is the one that
/// the system says the window is on. A frame whose corner is on no display, which is the case for a
/// window that overhangs the left or top edge of the screen, belongs to the display that it
/// overlaps the most, and failing that to the nearest display. This is a total function: there is
/// an answer whenever there is a display.
pub fn display_for_frame(frame: CGRect, displays: &[CGRect]) -> Option<usize> {
let contains = |display: &CGRect, x: f64, y: f64| {
x >= display.origin.x
&& x < display.origin.x + display.size.width
&& y >= display.origin.y
&& y < display.origin.y + display.size.height
};
if let Some(idx) = displays
.iter()
.position(|display| contains(display, frame.origin.x, frame.origin.y))
{
return Some(idx);
}
// how far apart two intervals are, which is zero when they touch or overlap
let gap = |start: f64, length: f64, other_start: f64, other_length: f64| {
(other_start - (start + length))
.max(start - (other_start + other_length))
.max(0.0)
};
let overlap = |display: &CGRect| {
let width = (frame.origin.x + frame.size.width).min(display.origin.x + display.size.width)
- frame.origin.x.max(display.origin.x);
let height = (frame.origin.y + frame.size.height)
.min(display.origin.y + display.size.height)
- frame.origin.y.max(display.origin.y);
width.max(0.0) * height.max(0.0)
};
let distance = |display: &CGRect| {
let dx = gap(
frame.origin.x,
frame.size.width,
display.origin.x,
display.size.width,
);
let dy = gap(
frame.origin.y,
frame.size.height,
display.origin.y,
display.size.height,
);
dx * dx + dy * dy
};
// the first of equals wins, so that the answer does not depend on the order of anything but
// the list
let mut best: Option<(usize, f64, f64)> = None;
for (idx, display) in displays.iter().enumerate() {
let (area, away) = (overlap(display), distance(display));
let better = match best {
None => true,
Some((_, best_area, best_away)) => {
area > best_area || (area == best_area && area == 0.0 && away < best_away)
}
};
if better {
best = Some((idx, area, away));
}
}
best.map(|(idx, _, _)| idx)
}
#[cfg(test)]
mod tests {
use super::*;
fn rect(x: f64, y: f64, width: f64, height: f64) -> CGRect {
CGRect::new(
CGPoint::new(x, y),
objc2_core_foundation::CGSize::new(width, height),
)
}
/// A display of 3840 by 2160 on the right, and one of 1920 by 1080 to the left of it
fn displays() -> Vec<CGRect> {
vec![
rect(0.0, 0.0, 3840.0, 2160.0),
rect(-1920.0, 0.0, 1920.0, 1080.0),
]
}
#[test]
fn the_display_under_the_corner_wins_over_the_one_with_more_of_the_window() {
// the corner is on the left display, and nearly all of the window is on the right one
let side_by_side = vec![
rect(0.0, 0.0, 1920.0, 1080.0),
rect(1920.0, 0.0, 1920.0, 1080.0),
];
let frame = rect(1900.0, 100.0, 1800.0, 600.0);
assert_eq!(display_for_frame(frame, &side_by_side), Some(0));
let frame = rect(1930.0, 100.0, 1800.0, 600.0);
assert_eq!(display_for_frame(frame, &side_by_side), Some(1));
}
#[test]
fn a_window_past_the_left_edge_is_on_the_display_it_overlaps() {
let main = vec![rect(0.0, 0.0, 3840.0, 2160.0)];
// Slack, hanging off the left edge: the corner is on no display
assert_eq!(
display_for_frame(rect(-570.0, 60.0, 1840.0, 2000.0), &main),
Some(0)
);
// parked at the edge with a sliver of 5px showing
assert_eq!(
display_for_frame(rect(-1670.0, 60.0, 1675.0, 2000.0), &main),
Some(0)
);
}
#[test]
fn a_window_past_the_edge_with_a_neighbour_beyond_it_is_ambiguous() {
// a window parked at the left edge of the main display has its corner on the neighbour,
// so geometry alone says that it is on the neighbour. This is why the display that a
// workspace hides its windows on comes from the monitor that owns the workspace, and not
// from where the windows are
let frame = rect(-1670.0, 60.0, 1675.0, 900.0);
assert_eq!(display_for_frame(frame, &displays()), Some(1));
}
#[test]
fn a_corner_on_no_display_goes_by_overlap() {
// above everything, with most of the window over the neighbour and a sliver over the main
// display
let frame = rect(-1670.0, -100.0, 1675.0, 900.0);
assert_eq!(display_for_frame(frame, &displays()), Some(1));
let frame = rect(-100.0, -100.0, 1000.0, 900.0);
assert_eq!(display_for_frame(frame, &displays()), Some(0));
}
#[test]
fn a_window_past_the_right_and_top_edges_is_found_too() {
let main = vec![rect(0.0, 0.0, 3840.0, 2160.0)];
assert_eq!(
display_for_frame(rect(3835.0, 60.0, 1275.0, 2000.0), &main),
Some(0)
);
assert_eq!(
display_for_frame(rect(100.0, -300.0, 1000.0, 900.0), &main),
Some(0)
);
}
#[test]
fn a_window_that_overlaps_nothing_is_on_the_nearest_display() {
// wholly past the left edge of the main display, closer to the display on its left
assert_eq!(
display_for_frame(rect(-2100.0, 3000.0, 100.0, 100.0), &displays()),
Some(1)
);
// wholly below everything, below the main display
assert_eq!(
display_for_frame(rect(1000.0, 5000.0, 100.0, 100.0), &displays()),
Some(0)
);
// wholly to the right of everything
assert_eq!(
display_for_frame(rect(9000.0, 100.0, 100.0, 100.0), &displays()),
Some(0)
);
}
#[test]
fn there_is_no_answer_without_displays() {
assert_eq!(display_for_frame(rect(0.0, 0.0, 10.0, 10.0), &[]), None);
}
#[test]
fn equals_are_resolved_by_the_order_of_the_list() {
// exactly between two displays and touching neither
let displays = vec![rect(0.0, 0.0, 100.0, 100.0), rect(300.0, 0.0, 100.0, 100.0)];
let frame = rect(200.0, 0.0, 0.0, 100.0);
assert_eq!(display_for_frame(frame, &displays), Some(0));
}
}
+54
View File
@@ -394,3 +394,57 @@ pub fn is_visible_on_another_display(frame: CGRect, screen_frame: CGRect) -> boo
.filter(|bounds| bounds.origin != screen_frame.origin || bounds.size != screen_frame.size)
.any(|bounds| core_graphics::CoreGraphicsApi::contains_rect(frame, bounds))
}
#[cfg(test)]
mod tests {
use super::*;
fn rect(x: f64, y: f64, width: f64, height: f64) -> CGRect {
CGRect::new(CGPoint::new(x, y), CGSize::new(width, height))
}
const SCREEN: fn() -> CGRect = || rect(0.0, 0.0, 3840.0, 2160.0);
#[test]
fn the_edge_sliver_of_a_window_that_overhangs_the_left_edge() {
// Slack in a column that is partly past the left edge: its corner is on no display, but
// where it rests only depends on the display that it belongs to
let frame = rect(-570.0, 60.0, 1840.0, 2000.0);
let edge = scrolling_edge_sliver(SCREEN(), frame, WindowHidingPosition::BottomLeft);
assert_eq!(edge.origin.x, -1835.0);
assert_eq!(edge.origin.y, 60.0);
assert_eq!(edge.size, frame.size);
}
#[test]
fn the_edge_sliver_of_a_window_that_overhangs_the_right_edge() {
let frame = rect(2500.0, 60.0, 1875.0, 2000.0);
let edge = scrolling_edge_sliver(SCREEN(), frame, WindowHidingPosition::BottomRight);
assert_eq!(edge.origin.x, 3835.0);
assert_eq!(edge.origin.y, 60.0);
assert_eq!(edge.size, frame.size);
}
#[test]
fn a_window_above_the_screen_rests_at_the_same_height() {
let frame = rect(-300.0, -100.0, 1275.0, 900.0);
let edge = scrolling_edge_sliver(SCREEN(), frame, WindowHidingPosition::BottomLeft);
assert_eq!(edge.origin.x, -1270.0);
assert_eq!(edge.origin.y, -100.0);
}
#[test]
fn the_edge_sliver_is_found_on_a_display_that_is_not_at_the_origin() {
let screen = rect(-1920.0, 0.0, 1920.0, 1080.0);
let frame = rect(-2000.0, 40.0, 800.0, 600.0);
let left = scrolling_edge_sliver(screen, frame, WindowHidingPosition::BottomLeft);
assert_eq!(left.origin.x, -1920.0 - 795.0);
let right = scrolling_edge_sliver(screen, frame, WindowHidingPosition::BottomRight);
assert_eq!(right.origin.x, -5.0);
}
}
+4 -2
View File
@@ -163,9 +163,11 @@ impl Workspace {
window.set_position(&target)
}
Visibility::OffLeft => window.hide_scrolling(WindowHidingPosition::BottomLeft),
Visibility::OffLeft => {
window.hide_scrolling(WindowHidingPosition::BottomLeft, screen)
}
Visibility::OffRight => {
window.hide_scrolling(WindowHidingPosition::BottomRight)
window.hide_scrolling(WindowHidingPosition::BottomRight, screen)
}
};
+118 -34
View File
@@ -99,12 +99,23 @@ use strum::Display;
use strum::EnumString;
use tracing::instrument;
/// Where a window that has scrolled out of view was parked
#[derive(Debug, Clone, Copy, PartialEq)]
struct Parked {
/// The side of the display that it left by
position: WindowHidingPosition,
/// The display that it was parked on, which is the display of the monitor that owns the window,
/// and which is not something to work out again from where the window is, since a window that
/// is parked past the edge of a display is not on any display
screen: CGRect,
}
lazy_static::lazy_static! {
/// The windows that have scrolled out of view and been parked, and where they were parked
///
/// A window in here is known to be out of the way without having to ask it, and is brought
/// back in from the edge it left by rather than from the corner it was parked in.
static ref PARKED_WINDOWS: parking_lot::Mutex<HashMap<u32, WindowHidingPosition>> =
static ref PARKED_WINDOWS: parking_lot::Mutex<HashMap<u32, Parked>> =
parking_lot::Mutex::new(HashMap::new());
}
@@ -409,10 +420,29 @@ impl Window {
)
}
/// Hide the window in the corner of the display that it is on
///
/// Prefer [`Window::hide_on`] when the display is known, since a window that hangs over the
/// edge of a display is not always on the display that the lookup by position finds.
#[tracing::instrument(skip_all)]
pub fn hide(
&mut self,
hiding_position: WindowHidingPosition,
) -> Result<(), AccessibilityError> {
self.hide_on(hiding_position, None)
}
/// Hide the window in the corner of `screen`, the bounds of the display that it belongs to
///
/// The display is the display of the monitor that has the window, and it has to come from
/// there for a window that overhangs the left edge of its display, where it is not on any
/// display, or one that overhangs the edge shared with another display, where it is on two. If
/// it is not given it is looked up from where the window is.
#[tracing::instrument(skip_all)]
pub fn hide_on(
&mut self,
hiding_position: WindowHidingPosition,
screen: Option<CGRect>,
) -> Result<(), AccessibilityError> {
// a window that is on its way somewhere is restored to where it was going, not to wherever
// it happened to be when it was hidden
@@ -424,24 +454,36 @@ impl Window {
let mut window_restore_positions = WINDOW_RESTORE_POSITIONS.lock();
if let Entry::Vacant(entry) = window_restore_positions.entry(self.id) {
entry.insert(rect);
drop(window_restore_positions);
}
drop(window_restore_positions);
if let Some(monitor_size) = CoreGraphicsApi::display_bounds_for_window_rect(rect) {
// I don't love this, but it's basically what Aerospace does in lieu of an actual "Hide" API
let hidden_rect = hidden_frame(hiding_position, monitor_size, rect.size);
tracing::debug!(
"hiding {} and setting restore point to {},{}",
let Some(monitor_size) =
screen.or_else(|| CoreGraphicsApi::display_bounds_for_window_rect(rect))
else {
// there is a restore point for a window that was not hidden, which is harmless, but
// a window that is left where it is when it should not be is not
tracing::warn!(
"not hiding {}: there is no display to hide it on",
self.title()
.unwrap_or_else(|| String::from("<NO TITLE FOUND>")),
rect.origin.x,
rect.origin.y,
);
self.set_point(hidden_rect.origin, true)?;
self.set_size(hidden_rect.size, true)?;
}
return Ok(());
};
// I don't love this, but it's basically what Aerospace does in lieu of an actual "Hide" API
let hidden_rect = hidden_frame(hiding_position, monitor_size, rect.size);
tracing::debug!(
"hiding {} and setting restore point to {},{}",
self.title()
.unwrap_or_else(|| String::from("<NO TITLE FOUND>")),
rect.origin.x,
rect.origin.y,
);
self.set_point(hidden_rect.origin, true)?;
self.set_size(hidden_rect.size, true)?;
Ok(())
}
@@ -452,12 +494,17 @@ impl Window {
/// screen. It keeps its size and its height up the screen, so bringing it back is a matter of
/// moving it. With animations on it slides there.
///
/// `screen` is the bounds of the display of the monitor that has the window. A window that is
/// partly past the left edge of the screen is on no display, so this is not something to find
/// out from where the window is.
///
/// Where a neighbouring display would show the window at the edge, it is hidden in the corner
/// of the screen instead, as with [`Window::hide`].
#[tracing::instrument(skip_all)]
pub fn hide_scrolling(
&mut self,
hiding_position: WindowHidingPosition,
screen: Option<CGRect>,
) -> Result<(), AccessibilityError> {
// nothing to do for a window that is already out of the way on this side, which keeps
// every layout update from sending it on the same trip again
@@ -470,7 +517,40 @@ impl Window {
parked_at = None;
}
if parked_at == Some(hiding_position) {
let parked_on = |screen| {
Some(Parked {
position: hiding_position,
screen,
})
};
if let Some(screen) = screen
&& parked_at == parked_on(screen)
{
return Ok(());
}
let rect = match animator::target(self.id) {
Some(target) => CGRect::from(target),
None => MacosApi::window_rect(&self.element)?,
};
let Some(screen) = screen.or_else(|| CoreGraphicsApi::display_bounds_for_window_rect(rect))
else {
tracing::warn!(
"window {} cannot be parked: there is no display to park it on",
self.id
);
return self.hide(hiding_position);
};
let parked = Parked {
position: hiding_position,
screen,
};
if parked_at == Some(parked) {
return Ok(());
}
@@ -481,25 +561,28 @@ impl Window {
None => animation::motion_for(AnimationPrefix::Movement),
};
let rect = match animator::target(self.id) {
Some(target) => CGRect::from(target),
None => MacosApi::window_rect(&self.element)?,
};
let Some(screen) = CoreGraphicsApi::display_bounds_for_window_rect(rect) else {
return self.hide(hiding_position);
};
let edge = scrolling_edge_sliver(screen, rect, hiding_position);
// resting at the edge next to a neighbouring display would be seen there
if is_visible_on_another_display(edge, screen) {
self.hide(hiding_position)?;
PARKED_WINDOWS.lock().insert(self.id, hiding_position);
tracing::trace!(
"window {} is parked in the corner of its display, since the edge is next to another display",
self.id
);
self.hide_on(hiding_position, Some(screen))?;
PARKED_WINDOWS.lock().insert(self.id, parked);
return Ok(());
}
tracing::trace!(
"window {} is parked at the {hiding_position} edge of its display, at {},{}",
self.id,
edge.origin.x,
edge.origin.y,
);
if let Entry::Vacant(entry) = WINDOW_RESTORE_POSITIONS.lock().entry(self.id) {
entry.insert(rect);
}
@@ -527,7 +610,7 @@ impl Window {
None => self.set_point(edge.origin, true)?,
}
PARKED_WINDOWS.lock().insert(self.id, hiding_position);
PARKED_WINDOWS.lock().insert(self.id, parked);
Ok(())
}
@@ -669,9 +752,15 @@ impl Window {
/// Bring a parked window back to the edge of the screen it left by, ready to slide in from there
///
/// Without this it would fly in from the corner it was parked in.
/// Without this it would fly in from the corner it was parked in. The display is the one that
/// it was parked on, and not the one at its target, since a target that overhangs the left
/// edge of the screen is on no display.
fn slide_in_from_edge(&self, target: &Rect) {
let Some(hiding_position) = PARKED_WINDOWS.lock().remove(&self.id) else {
let Some(Parked {
position: hiding_position,
screen,
}) = PARKED_WINDOWS.lock().remove(&self.id)
else {
return;
};
@@ -683,14 +772,9 @@ impl Window {
return;
};
let target = CGRect::from(*target);
let Some(screen) = CoreGraphicsApi::display_bounds_for_window_rect(target) else {
return;
};
// the corner it was parked in is out of sight, so it comes back at the height it is going to
let mut level = current;
level.origin.y = target.origin.y;
level.origin.y = target.top as CGFloat;
let edge = scrolling_edge_sliver(screen, level, hiding_position);
+2 -2
View File
@@ -1360,7 +1360,7 @@ impl WindowManager {
workspace.new_monocle_container()?;
for container in workspace.containers_mut() {
container.hide(hiding_position, None)?;
container.hide(hiding_position, None, None)?;
}
Ok(())
@@ -1396,7 +1396,7 @@ impl WindowManager {
.cycle_monocle_container(direction)?;
for container in self.focused_workspace_mut()?.containers_mut() {
container.hide(hiding_position, None)?;
container.hide(hiding_position, None, None)?;
}
self.update_focused_workspace(true, true)
+10 -2
View File
@@ -13,6 +13,7 @@ use crate::core::ScrollingLayoutOptions;
use crate::core::SocketMessage;
use crate::core::WindowContainerBehaviour;
use crate::core::WindowHidingPosition;
use crate::core_graphics::CoreGraphicsApi;
use crate::lockable_sequence::LockableSequence;
use crate::macos_api::MacosApi;
use crate::ring::Ring;
@@ -29,6 +30,7 @@ use komorebi_layouts::scrolling::model::ScrollingSpace;
use komorebi_themes::Base16ColourPalette;
use komorebi_themes::KomorebiTheme;
use komorebi_themes::KomorebiThemeCustom;
use objc2_core_foundation::CGRect;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
@@ -883,6 +885,12 @@ impl Workspace {
pub fn hide(&mut self, omit: Option<u32>) -> eyre::Result<()> {
let window_hiding_position = self.globals.window_hiding_position;
// windows are hidden on the display of the monitor that has them, and not on the display
// that they are found on, because a window that hangs over the left edge of its display is
// on no display, and could not be hidden at all
let screen =
CoreGraphicsApi::display_bounds_for_window_rect(CGRect::from(self.globals.work_area));
for window in self.floating_windows_mut().iter_mut().rev() {
let mut should_hide = omit.is_none();
@@ -901,7 +909,7 @@ impl Workspace {
}
for container in self.containers_mut() {
container.hide(window_hiding_position, omit)?;
container.hide(window_hiding_position, omit, screen)?;
}
// if let Some(window) = self.maximized_window() {
@@ -909,7 +917,7 @@ impl Workspace {
// }
if let Some(container) = &mut self.monocle_container {
container.hide(window_hiding_position, omit)?;
container.hide(window_hiding_position, omit, screen)?;
}
Ok(())